Fix isLuks message (should appear only in verbose mode).
[platform/upstream/cryptsetup.git] / src / cryptsetup.c
1 /*
2  * cryptsetup - setup cryptographic volumes for dm-crypt
3  *
4  * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2011, Red Hat, Inc. All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdint.h>
26 #include <stdarg.h>
27 #include <inttypes.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <assert.h>
32 #include <limits.h>
33 #include <libcryptsetup.h>
34 #include <popt.h>
35
36 #include "cryptsetup.h"
37
38 static int opt_verbose = 0;
39 static int opt_debug = 0;
40 static const char *opt_cipher = NULL;
41 static const char *opt_hash = NULL;
42 static int opt_verify_passphrase = 0;
43 static const char *opt_key_file = NULL;
44 static const char *opt_master_key_file = NULL;
45 static const char *opt_header_backup_file = NULL;
46 static const char *opt_uuid = NULL;
47 static const char *opt_header_device = NULL;
48 static int opt_key_size = 0;
49 static long opt_keyfile_size = 0;
50 static long opt_new_keyfile_size = 0;
51 static int opt_key_slot = CRYPT_ANY_SLOT;
52 static uint64_t opt_size = 0;
53 static uint64_t opt_offset = 0;
54 static uint64_t opt_skip = 0;
55 static int opt_skip_valid = 0;
56 static int opt_readonly = 0;
57 static int opt_iteration_time = 1000;
58 static int opt_batch_mode = 0;
59 static int opt_version_mode = 0;
60 static int opt_timeout = 0;
61 static int opt_tries = 3;
62 static int opt_align_payload = 0;
63 static int opt_random = 0;
64 static int opt_urandom = 0;
65 static int opt_dump_master_key = 0;
66 static int opt_shared = 0;
67 static int opt_allow_discards = 0;
68
69 static const char **action_argv;
70 static int action_argc;
71
72 static int action_create(int arg);
73 static int action_remove(int arg);
74 static int action_resize(int arg);
75 static int action_status(int arg);
76 static int action_luksFormat(int arg);
77 static int action_luksOpen(int arg);
78 static int action_luksAddKey(int arg);
79 static int action_luksKillSlot(int arg);
80 static int action_luksRemoveKey(int arg);
81 static int action_luksChangeKey(int arg);
82 static int action_isLuks(int arg);
83 static int action_luksUUID(int arg);
84 static int action_luksDump(int arg);
85 static int action_luksSuspend(int arg);
86 static int action_luksResume(int arg);
87 static int action_luksBackup(int arg);
88 static int action_luksRestore(int arg);
89 static int action_loopaesOpen(int arg);
90
91 static struct action_type {
92         const char *type;
93         int (*handler)(int);
94         int arg;
95         int required_action_argc;
96         int required_memlock;
97         const char *arg_desc;
98         const char *desc;
99 } action_types[] = {
100         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
101         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
102         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
103         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
104         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
105         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
106         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
107         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
108         { "luksChangeKey",action_luksChangeKey, 0, 1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
109         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
110         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
111         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
112         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
113         { "luksDump",   action_luksDump,        0, 1, 1, N_("<device>"), N_("dump LUKS partition information") },
114         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
115         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
116         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
117         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
118         { "loopaesOpen",action_loopaesOpen,     0, 2, 1, N_("<device> <name> "), N_("open loop-AES device as mapping <name>") },
119         { "loopaesClose",action_remove,         0, 1, 1, N_("<name>"), N_("remove loop-AES mapping") },
120         { NULL, NULL, 0, 0, 0, NULL, NULL }
121 };
122
123 __attribute__((format(printf, 5, 6)))
124 static void clogger(struct crypt_device *cd, int level, const char *file,
125                    int line, const char *format, ...)
126 {
127         va_list argp;
128         char *target = NULL;
129
130         va_start(argp, format);
131
132         if (vasprintf(&target, format, argp) > 0) {
133                 if (level >= 0) {
134                         crypt_log(cd, level, target);
135 #ifdef CRYPT_DEBUG
136                 } else if (opt_debug)
137                         printf("# %s:%d %s\n", file ?: "?", line, target);
138 #else
139                 } else if (opt_debug)
140                         printf("# %s\n", target);
141 #endif
142         }
143
144         va_end(argp);
145         free(target);
146 }
147
148 static int _yesDialog(const char *msg, void *usrptr __attribute__((unused)))
149 {
150         char *answer = NULL;
151         size_t size = 0;
152         int r = 1;
153
154         if(isatty(0) && !opt_batch_mode) {
155                 log_std("\nWARNING!\n========\n");
156                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
157                 if(getline(&answer, &size, stdin) == -1) {
158                         perror("getline");
159                         free(answer);
160                         return 0;
161                 }
162                 if(strcmp(answer, "YES\n"))
163                         r = 0;
164                 free(answer);
165         }
166
167         return r;
168 }
169
170 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
171 {
172         switch(level) {
173
174         case CRYPT_LOG_NORMAL:
175                 fputs(msg, stdout);
176                 break;
177         case CRYPT_LOG_VERBOSE:
178                 if (opt_verbose)
179                         fputs(msg, stdout);
180                 break;
181         case CRYPT_LOG_ERROR:
182                 fputs(msg, stderr);
183                 break;
184         case CRYPT_LOG_DEBUG:
185                 if (opt_debug)
186                         printf("# %s\n", msg);
187                 break;
188         default:
189                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
190                 break;
191         }
192 }
193
194 static void _quiet_log(int level, const char *msg, void *usrptr)
195 {
196         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
197                 level = CRYPT_LOG_VERBOSE;
198         _log(level, msg, usrptr);
199 }
200
201 static void show_status(int errcode)
202 {
203         char error[256], *error_;
204
205         if(!opt_verbose)
206                 return;
207
208         if(!errcode) {
209                 log_std(_("Command successful.\n"));
210                 return;
211         }
212
213         crypt_get_error(error, sizeof(error));
214
215         if (!error[0]) {
216                 error_ = strerror_r(-errcode, error, sizeof(error));
217                 if (error_ != error) {
218                         strncpy(error, error_, sizeof(error));
219                         error[sizeof(error) - 1] = '\0';
220                 }
221         }
222
223         log_err(_("Command failed with code %i"), -errcode);
224         if (*error)
225                 log_err(": %s\n", error);
226         else
227                 log_err(".\n");
228 }
229
230 static int action_create(int arg __attribute__((unused)))
231 {
232         struct crypt_device *cd = NULL;
233         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
234         struct crypt_params_plain params = {
235                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
236                 .skip = opt_skip,
237                 .offset = opt_offset,
238                 .size = opt_size,
239         };
240         char *password = NULL;
241         size_t passwordLen;
242         size_t key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8;
243         uint32_t activate_flags = 0;
244         int r;
245
246         if (params.hash && !strcmp(params.hash, "plain"))
247                 params.hash = NULL;
248
249         /* FIXME: temporary hack */
250         if (opt_key_file && strcmp(opt_key_file, "-"))
251                 params.hash = NULL;
252
253         if (opt_keyfile_size && opt_key_file)
254                 log_std(("Ignoring keyfile size option, keyfile read size "
255                          "is always the same as encryption key size.\n"));
256
257         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
258                                       cipher, NULL, cipher_mode);
259         if (r < 0) {
260                 log_err("No known cipher specification pattern detected.\n");
261                 goto out;
262         }
263
264         if ((r = crypt_init(&cd, action_argv[1])))
265                 goto out;
266
267         crypt_set_timeout(cd, opt_timeout);
268         crypt_set_password_retry(cd, opt_tries);
269
270         r = crypt_format(cd, CRYPT_PLAIN,
271                          cipher, cipher_mode,
272                          NULL, NULL,
273                          key_size,
274                          &params);
275         if (r < 0)
276                 goto out;
277
278         if (opt_readonly)
279                 activate_flags |= CRYPT_ACTIVATE_READONLY;
280
281         if (opt_shared)
282                 activate_flags |= CRYPT_ACTIVATE_SHARED;
283
284         if (opt_allow_discards)
285                 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
286
287         if (opt_key_file)
288                 /* With hashing, read the whole keyfile */
289                 r = crypt_activate_by_keyfile(cd, action_argv[0],
290                         CRYPT_ANY_SLOT, opt_key_file, params.hash ? 0 : key_size,
291                         activate_flags);
292         else {
293                 r = crypt_get_key(_("Enter passphrase: "),
294                                   &password, &passwordLen, opt_keyfile_size,
295                                   NULL, opt_timeout,
296                                   opt_batch_mode ? 0 : opt_verify_passphrase,
297                                   cd);
298                 if (r < 0)
299                         goto out;
300
301                 r = crypt_activate_by_passphrase(cd, action_argv[0],
302                         CRYPT_ANY_SLOT, password, passwordLen, activate_flags);
303         }
304 out:
305         crypt_free(cd);
306         crypt_safe_free(password);
307
308         return r;
309 }
310
311 static int action_loopaesOpen(int arg __attribute__((unused)))
312 {
313         struct crypt_device *cd = NULL;
314         struct crypt_params_loopaes params = {
315                 .hash = opt_hash ?: NULL,
316                 .offset = opt_offset,
317                 .skip = opt_skip_valid ? opt_skip : opt_offset,
318         };
319         unsigned int key_size = (opt_key_size ?: DEFAULT_LOOPAES_KEYBITS) / 8;
320         uint32_t activate_flags = 0;
321         int r;
322
323         if (!opt_key_file) {
324                 log_err(_("Option --key-file is required.\n"));
325                 return -EINVAL;
326         }
327
328         if (opt_readonly)
329                 activate_flags |= CRYPT_ACTIVATE_READONLY;
330
331         if (opt_allow_discards)
332                 activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
333
334         if ((r = crypt_init(&cd, action_argv[0])))
335                 goto out;
336
337         r = crypt_format(cd, CRYPT_LOOPAES, opt_cipher ?: DEFAULT_LOOPAES_CIPHER,
338                          NULL, NULL, NULL, key_size, &params);
339         if (r < 0)
340                 goto out;
341
342         r = crypt_activate_by_keyfile(cd, action_argv[1], CRYPT_ANY_SLOT,
343                                       opt_key_file, opt_keyfile_size, activate_flags);
344 out:
345         crypt_free(cd);
346
347         return r;
348 }
349
350 static int action_remove(int arg __attribute__((unused)))
351 {
352         struct crypt_device *cd = NULL;
353         int r;
354
355         r = crypt_init_by_name(&cd, action_argv[0]);
356         if (r == 0)
357                 r = crypt_deactivate(cd, action_argv[0]);
358
359         crypt_free(cd);
360         return r;
361 }
362
363 static int action_resize(int arg __attribute__((unused)))
364 {
365         struct crypt_device *cd = NULL;
366         int r;
367
368         r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
369         if (r == 0)
370                 r = crypt_resize(cd, action_argv[0], opt_size);
371
372         crypt_free(cd);
373         return r;
374 }
375
376 static int action_status(int arg __attribute__((unused)))
377 {
378         crypt_status_info ci;
379         struct crypt_active_device cad;
380         struct crypt_device *cd = NULL;
381         char *backing_file;
382         const char *device;
383         int r = 0;
384
385         ci = crypt_status(NULL, action_argv[0]);
386         switch (ci) {
387         case CRYPT_INVALID:
388                 r = -EINVAL;
389                 break;
390         case CRYPT_INACTIVE:
391                 log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
392                 r = -ENODEV;
393                 break;
394         case CRYPT_ACTIVE:
395         case CRYPT_BUSY:
396                 log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
397                         ci == CRYPT_BUSY ? " and is in use" : "");
398                 r = crypt_init_by_name(&cd, action_argv[0]);
399                 if (r < 0 || !crypt_get_type(cd))
400                         goto out;
401
402                 log_std("  type:    %s\n", crypt_get_type(cd));
403
404                 r = crypt_get_active_device(cd, action_argv[0], &cad);
405                 if (r < 0)
406                         goto out;
407
408                 log_std("  cipher:  %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
409                 log_std("  keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
410                 device = crypt_get_device_name(cd);
411                 log_std("  device:  %s\n", device);
412                 if (crypt_loop_device(device)) {
413                         backing_file = crypt_loop_backing_file(device);
414                         log_std("  loop:    %s\n", backing_file);
415                         free(backing_file);
416                 }
417                 log_std("  offset:  %" PRIu64 " sectors\n", cad.offset);
418                 log_std("  size:    %" PRIu64 " sectors\n", cad.size);
419                 if (cad.iv_offset)
420                         log_std("  skipped: %" PRIu64 " sectors\n", cad.iv_offset);
421                 log_std("  mode:    %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
422                                            "readonly" : "read/write");
423                 if (cad.flags & CRYPT_ACTIVATE_ALLOW_DISCARDS)
424                         log_std("  flags:   discards\n");
425         }
426 out:
427         crypt_free(cd);
428         return r;
429 }
430
431 static int _read_mk(const char *file, char **key, int keysize)
432 {
433         int fd;
434
435         *key = crypt_safe_alloc(keysize);
436         if (!*key)
437                 return -ENOMEM;
438
439         fd = open(file, O_RDONLY);
440         if (fd == -1) {
441                 log_err("Cannot read keyfile %s.\n", file);
442                 goto fail;
443         }
444         if ((read(fd, *key, keysize) != keysize)) {
445                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
446                 close(fd);
447                 goto fail;
448         }
449         close(fd);
450         return 0;
451 fail:
452         crypt_safe_free(*key);
453         *key = NULL;
454         return -EINVAL;
455 }
456
457 static int action_luksFormat(int arg __attribute__((unused)))
458 {
459         int r = -EINVAL, keysize;
460         const char *header_device;
461         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
462         char *password = NULL;
463         size_t passwordLen;
464         struct crypt_device *cd = NULL;
465         struct crypt_params_luks1 params = {
466                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
467                 .data_alignment = opt_align_payload,
468                 .data_device = opt_header_device ? action_argv[0] : NULL,
469         };
470
471         header_device = opt_header_device ?: action_argv[0];
472
473         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."),
474                     header_device) == -1) {
475                 log_err(_("memory allocation error in action_luksFormat"));
476                 r = -ENOMEM;
477                 goto out;
478         }
479         r = _yesDialog(msg, NULL) ? 0 : -EINVAL;
480         free(msg);
481         if (r < 0)
482                 goto out;
483
484         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
485                                       cipher, NULL, cipher_mode);
486         if (r < 0) {
487                 log_err(_("No known cipher specification pattern detected.\n"));
488                 goto out;
489         }
490
491         if ((r = crypt_init(&cd, header_device))) {
492                 if (opt_header_device)
493                         log_err(_("Cannot use %s as on-disk header.\n"), header_device);
494                 goto out;
495         }
496
497         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
498
499         crypt_set_password_verify(cd, 1);
500         crypt_set_timeout(cd, opt_timeout);
501         if (opt_iteration_time)
502                 crypt_set_iterarion_time(cd, opt_iteration_time);
503
504         if (opt_random)
505                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
506         else if (opt_urandom)
507                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
508
509         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
510                           opt_keyfile_size, opt_key_file, opt_timeout,
511                           opt_batch_mode ? 0 : 1 /* always verify */, cd);
512         if (r < 0)
513                 goto out;
514
515         if (opt_master_key_file) {
516                 r = _read_mk(opt_master_key_file, &key, keysize);
517                 if (r < 0)
518                         goto out;
519         }
520
521         r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
522                          opt_uuid, key, keysize, &params);
523         if (r < 0)
524                 goto out;
525
526         r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
527                                             key, keysize,
528                                             password, passwordLen);
529 out:
530         crypt_free(cd);
531         crypt_safe_free(key);
532         crypt_safe_free(password);
533
534         return r;
535 }
536
537 static int action_luksOpen(int arg __attribute__((unused)))
538 {
539         struct crypt_device *cd = NULL;
540         const char *data_device, *header_device;
541         uint32_t flags = 0;
542         int r;
543
544         if (opt_header_device) {
545                 header_device = opt_header_device;
546                 data_device = action_argv[0];
547         } else {
548                 header_device = action_argv[0];
549                 data_device = NULL;
550         }
551
552         if ((r = crypt_init(&cd, header_device)))
553                 goto out;
554
555         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
556                 goto out;
557
558         if (data_device &&
559             (r = crypt_set_data_device(cd, data_device)))
560                 goto out;
561
562         if (!data_device && (crypt_get_data_offset(cd) < 8)) {
563                 log_err(_("Reduced data offset is allowed only for detached LUKS header.\n"));
564                 r = -EINVAL;
565                 goto out;
566         }
567
568         crypt_set_timeout(cd, opt_timeout);
569         crypt_set_password_retry(cd, opt_tries);
570
571         if (opt_iteration_time)
572                 crypt_set_iterarion_time(cd, opt_iteration_time);
573
574         if (opt_readonly)
575                 flags |= CRYPT_ACTIVATE_READONLY;
576
577         if (opt_allow_discards)
578                 flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
579
580         if (opt_key_file) {
581                 crypt_set_password_retry(cd, 1);
582                 r = crypt_activate_by_keyfile(cd, action_argv[1],
583                         opt_key_slot, opt_key_file, opt_keyfile_size,
584                         flags);
585         } else
586                 r = crypt_activate_by_passphrase(cd, action_argv[1],
587                         opt_key_slot, NULL, 0, flags);
588 out:
589         crypt_free(cd);
590         return r;
591 }
592
593 static int verify_keyslot(struct crypt_device *cd, int key_slot,
594                           char *msg_last, char *msg_pass,
595                           const char *key_file, int keyfile_size)
596 {
597         crypt_keyslot_info ki;
598         char *password = NULL;
599         size_t passwordLen;
600         int i, r;
601
602         ki = crypt_keyslot_status(cd, key_slot);
603         if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
604                 return -EPERM;
605
606         r = crypt_get_key(msg_pass, &password, &passwordLen,
607                           keyfile_size, key_file, opt_timeout,
608                           opt_batch_mode ? 0 : opt_verify_passphrase, cd);
609         if(r < 0)
610                 goto out;
611
612         if (ki == CRYPT_SLOT_ACTIVE_LAST) {
613                 /* check the last keyslot */
614                 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
615                                                  password, passwordLen, 0);
616         } else {
617                 /* try all other keyslots */
618                 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
619                         if (i == key_slot)
620                                 continue;
621                         ki = crypt_keyslot_status(cd, key_slot);
622                         if (ki == CRYPT_SLOT_ACTIVE)
623                         r = crypt_activate_by_passphrase(cd, NULL, i,
624                                                          password, passwordLen, 0);
625                         if (r == i)
626                                 break;
627                 }
628         }
629
630         if (r < 0)
631                 log_err(_("No key available with this passphrase.\n"));
632 out:
633         crypt_safe_free(password);
634         return r;
635 }
636
637 static int action_luksKillSlot(int arg __attribute__((unused)))
638 {
639         struct crypt_device *cd = NULL;
640         int r;
641
642         if ((r = crypt_init(&cd, action_argv[0])))
643                 goto out;
644
645         crypt_set_confirm_callback(cd, _yesDialog, NULL);
646         crypt_set_timeout(cd, opt_timeout);
647
648         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
649                 goto out;
650
651         switch (crypt_keyslot_status(cd, opt_key_slot)) {
652         case CRYPT_SLOT_ACTIVE_LAST:
653         case CRYPT_SLOT_ACTIVE:
654                 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
655                 break;
656         case CRYPT_SLOT_INACTIVE:
657                 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
658         case CRYPT_SLOT_INVALID:
659                 r = -EINVAL;
660                 goto out;
661         }
662
663         if (!opt_batch_mode) {
664                 r = verify_keyslot(cd, opt_key_slot,
665                         _("This is the last keyslot. Device will become unusable after purging this key."),
666                         _("Enter any remaining LUKS passphrase: "),
667                         opt_key_file, opt_keyfile_size);
668                 if (r < 0)
669                         goto out;
670         }
671
672         r = crypt_keyslot_destroy(cd, opt_key_slot);
673 out:
674         crypt_free(cd);
675         return r;
676 }
677
678 static int action_luksRemoveKey(int arg __attribute__((unused)))
679 {
680         struct crypt_device *cd = NULL;
681         char *password = NULL;
682         size_t passwordLen;
683         int r;
684
685         if ((r = crypt_init(&cd, action_argv[0])))
686                 goto out;
687
688         crypt_set_confirm_callback(cd, _yesDialog, NULL);
689         crypt_set_timeout(cd, opt_timeout);
690
691         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
692                 goto out;
693
694         r = crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
695                       &password, &passwordLen,
696                       opt_keyfile_size, opt_key_file,
697                       opt_timeout,
698                       opt_batch_mode ? 0 : opt_verify_passphrase,
699                       cd);
700         if(r < 0)
701                 goto out;
702
703         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
704                                          password, passwordLen, 0);
705         if (r < 0)
706                 goto out;
707
708         opt_key_slot = r;
709         log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
710
711         if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
712             !_yesDialog(_("This is the last keyslot. "
713                           "Device will become unusable after purging this key."),
714                         NULL)) {
715                 r = -EPERM;
716                 goto out;
717         }
718
719         r = crypt_keyslot_destroy(cd, opt_key_slot);
720 out:
721         crypt_safe_free(password);
722         crypt_free(cd);
723         return r;
724 }
725
726 static int action_luksAddKey(int arg __attribute__((unused)))
727 {
728         int r = -EINVAL, keysize = 0;
729         char *key = NULL;
730         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
731         struct crypt_device *cd = NULL;
732
733         if ((r = crypt_init(&cd, action_argv[0])))
734                 goto out;
735
736         crypt_set_confirm_callback(cd, _yesDialog, NULL);
737
738         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
739                 goto out;
740
741         keysize = crypt_get_volume_key_size(cd);
742         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
743         crypt_set_timeout(cd, opt_timeout);
744         if (opt_iteration_time)
745                 crypt_set_iterarion_time(cd, opt_iteration_time);
746
747         if (opt_master_key_file) {
748                 r = _read_mk(opt_master_key_file, &key, keysize);
749                 if (r < 0)
750                         goto out;
751                 //FIXME: process keyfile arg
752                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
753                                                     key, keysize, NULL, 0);
754         } else if (opt_key_file || opt_new_key_file) {
755                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
756                                                  opt_key_file, opt_keyfile_size,
757                                                  opt_new_key_file, opt_new_keyfile_size);
758         } else {
759                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
760                                                     NULL, 0, NULL, 0);
761         }
762 out:
763         crypt_free(cd);
764         crypt_safe_free(key);
765         return r;
766 }
767
768 static int _slots_full(struct crypt_device *cd)
769 {
770         int i;
771
772         for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++)
773                 if (crypt_keyslot_status(cd, i) == CRYPT_SLOT_INACTIVE)
774                         return 0;
775         return 1;
776 }
777
778 static int action_luksChangeKey(int arg __attribute__((unused)))
779 {
780         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
781         struct crypt_device *cd = NULL;
782         char *vk = NULL, *password = NULL;
783         size_t passwordLen = 0;
784         size_t vk_size;
785         int new_key_slot, old_key_slot, r;
786
787         if ((r = crypt_init(&cd, action_argv[0])))
788                 goto out;
789
790         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
791                 goto out;
792
793         if (opt_iteration_time)
794                 crypt_set_iterarion_time(cd, opt_iteration_time);
795
796         r = crypt_get_key(_("Enter LUKS passphrase to be changed: "),
797                       &password, &passwordLen,
798                       opt_keyfile_size, opt_key_file, opt_timeout,
799                       opt_batch_mode ? 0 : opt_verify_passphrase, cd);
800         if (r < 0)
801                 goto out;
802
803         vk_size = crypt_get_volume_key_size(cd);
804         vk = crypt_safe_alloc(vk_size);
805         if (!vk) {
806                 r = -ENOMEM;
807                 goto out;
808         }
809
810         r = crypt_volume_key_get(cd, opt_key_slot, vk, &vk_size,
811                                  password, passwordLen);
812         if (r < 0) {
813                 if (opt_key_slot != CRYPT_ANY_SLOT)
814                         log_err(_("No key available with this passphrase.\n"));
815                 goto out;
816         }
817
818         if (opt_key_slot != CRYPT_ANY_SLOT || _slots_full(cd)) {
819                 log_dbg("Key slot %d is going to be overwritten (%s).",
820                         r, opt_key_slot != CRYPT_ANY_SLOT ?
821                         "explicit key slot specified" : "no free key slot");
822                 old_key_slot = r;
823                 new_key_slot = r;
824         } else {
825                 log_dbg("Allocating new key slot.");
826                 old_key_slot = r;
827                 new_key_slot = CRYPT_ANY_SLOT;
828         }
829
830         crypt_safe_free(password);
831         password = NULL;
832         passwordLen = 0;
833         r = crypt_get_key(_("Enter new LUKS passphrase: "),
834                           &password, &passwordLen,
835                           opt_new_keyfile_size, opt_new_key_file,
836                           opt_timeout, opt_batch_mode ? 0 : 1, cd);
837         if (r < 0)
838                 goto out;
839
840         if (new_key_slot == old_key_slot) {
841                 (void)crypt_keyslot_destroy(cd, old_key_slot);
842                 r = crypt_keyslot_add_by_volume_key(cd, new_key_slot,
843                                                     vk, vk_size,
844                                                     password, passwordLen);
845                 if (r >= 0)
846                         log_verbose(_("Key slot %d changed.\n"), r);
847         } else {
848                 r = crypt_keyslot_add_by_volume_key(cd, CRYPT_ANY_SLOT,
849                                                     vk, vk_size,
850                                                     password, passwordLen);
851                 if (r >= 0) {
852                         log_verbose(_("Replaced with key slot %d.\n"), r);
853                         r = crypt_keyslot_destroy(cd, old_key_slot);
854                 }
855         }
856         if (r < 0)
857                 log_err(_("Failed to swap new key slot.\n"));
858 out:
859         crypt_safe_free(vk);
860         crypt_safe_free(password);
861         crypt_free(cd);
862         return r;
863 }
864
865 static int action_isLuks(int arg __attribute__((unused)))
866 {
867         struct crypt_device *cd = NULL;
868         int r;
869
870         if ((r = crypt_init(&cd, action_argv[0])))
871                 goto out;
872
873         crypt_set_log_callback(cd, _quiet_log, NULL);
874         r = crypt_load(cd, CRYPT_LUKS1, NULL);
875 out:
876         crypt_free(cd);
877         return r;
878 }
879
880 static int action_luksUUID(int arg __attribute__((unused)))
881 {
882         struct crypt_device *cd = NULL;
883         const char *existing_uuid = NULL;
884         int r;
885
886         if ((r = crypt_init(&cd, action_argv[0])))
887                 goto out;
888
889         crypt_set_confirm_callback(cd, _yesDialog, NULL);
890
891         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
892                 goto out;
893
894         if (opt_uuid)
895                 r = crypt_set_uuid(cd, opt_uuid);
896         else {
897                 existing_uuid = crypt_get_uuid(cd);
898                 log_std("%s\n", existing_uuid ?: "");
899                 r = existing_uuid ? 0 : 1;
900         }
901 out:
902         crypt_free(cd);
903         return r;
904 }
905
906 static int luksDump_with_volume_key(struct crypt_device *cd)
907 {
908         char *vk = NULL, *password = NULL;
909         size_t passwordLen = 0;
910         size_t vk_size;
911         unsigned i;
912         int r;
913
914         crypt_set_confirm_callback(cd, _yesDialog, NULL);
915         if (!_yesDialog(
916             _("LUKS header dump with volume key is sensitive information\n"
917               "which allows access to encrypted partition without passphrase.\n"
918               "This dump should be always stored encrypted on safe place."),
919               NULL))
920                 return -EPERM;
921
922         vk_size = crypt_get_volume_key_size(cd);
923         vk = crypt_safe_alloc(vk_size);
924         if (!vk)
925                 return -ENOMEM;
926
927         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
928                           opt_keyfile_size, opt_key_file, opt_timeout, 0, cd);
929         if (r < 0)
930                 goto out;
931
932         r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
933                                  password, passwordLen);
934         if (r < 0)
935                 goto out;
936
937         log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
938         log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
939         log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
940         log_std("Payload offset:\t%d\n", (int)crypt_get_data_offset(cd));
941         log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
942         log_std("MK bits:       \t%d\n", (int)vk_size * 8);
943         log_std("MK dump:\t");
944
945         for(i = 0; i < vk_size; i++) {
946                 if (i && !(i % 16))
947                         log_std("\n\t\t");
948                 log_std("%02hhx ", (char)vk[i]);
949         }
950         log_std("\n");
951
952 out:
953         crypt_safe_free(password);
954         crypt_safe_free(vk);
955         return r;
956 }
957
958 static int action_luksDump(int arg __attribute__((unused)))
959 {
960         struct crypt_device *cd = NULL;
961         int r;
962
963         if ((r = crypt_init(&cd, action_argv[0])))
964                 goto out;
965
966         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
967                 goto out;
968
969         if (opt_dump_master_key)
970                 r = luksDump_with_volume_key(cd);
971         else
972                 r = crypt_dump(cd);
973 out:
974         crypt_free(cd);
975         return r;
976 }
977
978 static int action_luksSuspend(int arg __attribute__((unused)))
979 {
980         struct crypt_device *cd = NULL;
981         int r;
982
983         r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device);
984         if (!r)
985                 r = crypt_suspend(cd, action_argv[0]);
986
987         crypt_free(cd);
988         return r;
989 }
990
991 static int action_luksResume(int arg __attribute__((unused)))
992 {
993         struct crypt_device *cd = NULL;
994         int r;
995
996         if ((r = crypt_init_by_name_and_header(&cd, action_argv[0], opt_header_device)))
997                 goto out;
998
999         crypt_set_timeout(cd, opt_timeout);
1000         crypt_set_password_retry(cd, opt_tries);
1001
1002         if (opt_key_file)
1003                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
1004                                             opt_key_file, opt_keyfile_size);
1005         else
1006                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
1007                                                NULL, 0);
1008 out:
1009         crypt_free(cd);
1010         return r;
1011 }
1012
1013 static int action_luksBackup(int arg __attribute__((unused)))
1014 {
1015         struct crypt_device *cd = NULL;
1016         int r;
1017
1018         if (!opt_header_backup_file) {
1019                 log_err(_("Option --header-backup-file is required.\n"));
1020                 return -EINVAL;
1021         }
1022
1023         if ((r = crypt_init(&cd, action_argv[0])))
1024                 goto out;
1025
1026         crypt_set_confirm_callback(cd, _yesDialog, NULL);
1027
1028         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
1029 out:
1030         crypt_free(cd);
1031         return r;
1032 }
1033
1034 static int action_luksRestore(int arg __attribute__((unused)))
1035 {
1036         struct crypt_device *cd = NULL;
1037         int r = 0;
1038
1039         if (!opt_header_backup_file) {
1040                 log_err(_("Option --header-backup-file is required.\n"));
1041                 return -EINVAL;
1042         }
1043
1044         if ((r = crypt_init(&cd, action_argv[0])))
1045                 goto out;
1046
1047         crypt_set_confirm_callback(cd, _yesDialog, NULL);
1048         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
1049 out:
1050         crypt_free(cd);
1051         return r;
1052 }
1053
1054 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
1055                                              int exitcode, const char *error,
1056                                              const char *more)
1057 {
1058         poptPrintUsage(popt_context, stderr, 0);
1059         if (error)
1060                 log_err("%s: %s\n", more, error);
1061         poptFreeContext(popt_context);
1062         exit(exitcode);
1063 }
1064
1065 static void help(poptContext popt_context,
1066                  enum poptCallbackReason reason __attribute__((unused)),
1067                  struct poptOption *key,
1068                  const char *arg __attribute__((unused)),
1069                  void *data __attribute__((unused)))
1070 {
1071         if (key->shortName == '?') {
1072                 struct action_type *action;
1073
1074                 log_std("%s\n",PACKAGE_STRING);
1075
1076                 poptPrintHelp(popt_context, stdout, 0);
1077
1078                 log_std(_("\n"
1079                          "<action> is one of:\n"));
1080
1081                 for(action = action_types; action->type; action++)
1082                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
1083
1084                 log_std(_("\n"
1085                          "<name> is the device to create under %s\n"
1086                          "<device> is the encrypted device\n"
1087                          "<key slot> is the LUKS key slot number to modify\n"
1088                          "<key file> optional key file for the new key for luksAddKey action\n"),
1089                         crypt_get_dir());
1090
1091                 log_std(_("\nDefault compiled-in keyfile parameters:\n"
1092                          "\tMaximum keyfile size: %dkB, "
1093                          "Maximum interactive passphrase length %d (characters)\n"),
1094                          DEFAULT_KEYFILE_SIZE_MAXKB, DEFAULT_PASSPHRASE_SIZE_MAX);
1095
1096                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
1097                          "\tloop-AES: %s, Key %d bits\n"
1098                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
1099                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
1100                          DEFAULT_LOOPAES_CIPHER, DEFAULT_LOOPAES_KEYBITS,
1101                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
1102                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
1103                          DEFAULT_RNG);
1104                 exit(EXIT_SUCCESS);
1105         } else
1106                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1107 }
1108
1109 static void _dbg_version_and_cmd(int argc, const char **argv)
1110 {
1111         int i;
1112
1113         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1114         for (i = 0; i < argc; i++) {
1115                 if (i)
1116                         log_std(" ");
1117                 log_std("%s", argv[i]);
1118         }
1119         log_std("\"\n");
1120 }
1121
1122 static int run_action(struct action_type *action)
1123 {
1124         int r;
1125
1126         log_dbg("Running command %s.", action->type);
1127
1128         if (action->required_memlock)
1129                 crypt_memory_lock(NULL, 1);
1130
1131         r = action->handler(action->arg);
1132
1133         if (action->required_memlock)
1134                 crypt_memory_lock(NULL, 0);
1135
1136         /* Some functions returns keyslot # */
1137         if (r > 0)
1138                 r = 0;
1139
1140         show_status(r);
1141
1142         /* Translate exit code to simple codes */
1143         switch (r) {
1144         case 0:         r = EXIT_SUCCESS; break;
1145         case -EEXIST:
1146         case -EBUSY:    r = 5; break;
1147         case -ENOTBLK:
1148         case -ENODEV:   r = 4; break;
1149         case -ENOMEM:   r = 3; break;
1150         case -EPERM:    r = 2; break;
1151         case -EINVAL:
1152         case -ENOENT:
1153         case -ENOSYS:
1154         default:        r = EXIT_FAILURE;
1155         }
1156         return r;
1157 }
1158
1159 int main(int argc, const char **argv)
1160 {
1161         static char *popt_tmp;
1162         static struct poptOption popt_help_options[] = {
1163                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1164                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1165                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1166                 POPT_TABLEEND
1167         };
1168         static struct poptOption popt_options[] = {
1169                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1170                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1171                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1172                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1173                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1174                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1175                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
1176                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1177                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
1178                 { "dump-master-key",  '\0',  POPT_ARG_NONE, &opt_dump_master_key,       0, N_("Dump volume (master) key instead of keyslots info."), NULL },
1179                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
1180                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1181                 { "new-keyfile-size", '\0',  POPT_ARG_LONG, &opt_new_keyfile_size,      0, N_("Limits the read from newly added keyfile"), N_("bytes") },
1182                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
1183                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
1184                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
1185                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
1186                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
1187                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1188                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1189                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
1190                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1191                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
1192                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
1193                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1194                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1195                 { "shared",            '\0', POPT_ARG_NONE, &opt_shared,                0, N_("Share device with another non-overlapping crypt segment."), NULL },
1196                 { "uuid",              '\0', POPT_ARG_STRING, &opt_uuid,                0, N_("UUID for device to use."), NULL },
1197                 { "allow-discards",    '\0', POPT_ARG_NONE, &opt_allow_discards,        0, N_("Allow discards (aka TRIM) requests for device."), NULL },
1198                 { "header",            '\0', POPT_ARG_STRING, &opt_header_device,       0, N_("Device or file with separated LUKS header."), NULL },
1199                 POPT_TABLEEND
1200         };
1201         poptContext popt_context;
1202         struct action_type *action;
1203         const char *aname;
1204         int r;
1205         const char *null_action_argv[] = {NULL};
1206
1207         crypt_set_log_callback(NULL, _log, NULL);
1208
1209         setlocale(LC_ALL, "");
1210         bindtextdomain(PACKAGE, LOCALEDIR);
1211         textdomain(PACKAGE);
1212
1213         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1214         poptSetOtherOptionHelp(popt_context,
1215                                N_("[OPTION...] <action> <action-specific>]"));
1216
1217         while((r = poptGetNextOpt(popt_context)) > 0) {
1218                 unsigned long long ull_value;
1219                 char *endp;
1220
1221                 errno = 0;
1222                 ull_value = strtoull(popt_tmp, &endp, 0);
1223                 if (*endp || !*popt_tmp ||
1224                     (errno == ERANGE && ull_value == ULLONG_MAX) ||
1225                     (errno != 0 && ull_value == 0))
1226                         r = POPT_ERROR_BADNUMBER;
1227
1228                 switch(r) {
1229                         case 1:
1230                                 opt_size = ull_value;
1231                                 break;
1232                         case 2:
1233                                 opt_offset = ull_value;
1234                                 break;
1235                         case 3:
1236                                 opt_skip = ull_value;
1237                                 opt_skip_valid = 1;
1238                                 break;
1239                 }
1240
1241                 if (r < 0)
1242                         break;
1243         }
1244
1245         if (r < -1)
1246                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1247                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1248         if (opt_version_mode) {
1249                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1250                 poptFreeContext(popt_context);
1251                 exit(EXIT_SUCCESS);
1252         }
1253
1254         if (!(aname = poptGetArg(popt_context)))
1255                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
1256                       poptGetInvocationName(popt_context));
1257         for(action = action_types; action->type; action++)
1258                 if (strcmp(action->type, aname) == 0)
1259                         break;
1260         if (!action->type)
1261                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1262                       poptGetInvocationName(popt_context));
1263
1264         action_argc = 0;
1265         action_argv = poptGetArgs(popt_context);
1266         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1267         if(!action_argv)
1268                 action_argv = null_action_argv;
1269
1270         /* Count args, somewhat unnice, change? */
1271         while(action_argv[action_argc] != NULL)
1272                 action_argc++;
1273
1274         if(action_argc < action->required_action_argc) {
1275                 char buf[128];
1276                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
1277                 usage(popt_context, EXIT_FAILURE, buf,
1278                       poptGetInvocationName(popt_context));
1279         }
1280
1281         /* FIXME: rewrite this from scratch */
1282
1283         if (opt_shared && strcmp(aname, "create")) {
1284                 usage(popt_context, EXIT_FAILURE,
1285                       _("Option --shared is allowed only for create operation.\n"),
1286                       poptGetInvocationName(popt_context));
1287         }
1288
1289         if (opt_allow_discards &&
1290             strcmp(aname, "luksOpen") &&
1291             strcmp(aname, "create") &&
1292             strcmp(aname, "loopaesOpen")) {
1293                 usage(popt_context, EXIT_FAILURE,
1294                       _("Option --allow-discards is allowed only for luksOpen, loopaesOpen and create operation.\n"),
1295                       poptGetInvocationName(popt_context));
1296         }
1297
1298         if (opt_key_size &&
1299            strcmp(aname, "luksFormat") &&
1300            strcmp(aname, "create") &&
1301            strcmp(aname, "loopaesOpen")) {
1302                 usage(popt_context, EXIT_FAILURE,
1303                       _("Option --key-size is allowed only for luksFormat, create and loopaesOpen.\n"
1304                         "To limit read from keyfile use --keyfile-size=(bytes)."),
1305                       poptGetInvocationName(popt_context));
1306         }
1307
1308         if (opt_key_size % 8)
1309                 usage(popt_context, EXIT_FAILURE,
1310                       _("Key size must be a multiple of 8 bits"),
1311                       poptGetInvocationName(popt_context));
1312
1313         if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1314                 opt_key_slot = atoi(action_argv[1]);
1315         if (opt_key_slot != CRYPT_ANY_SLOT &&
1316             (opt_key_slot < 0 || opt_key_slot >= crypt_keyslot_max(CRYPT_LUKS1)))
1317                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1318                       poptGetInvocationName(popt_context));
1319
1320         if ((!strcmp(aname, "luksRemoveKey") ||
1321              !strcmp(aname, "luksFormat")) &&
1322              action_argc > 1) {
1323                 if (opt_key_file)
1324                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1325                 else
1326                         opt_key_file = action_argv[1];
1327         }
1328
1329         if (opt_keyfile_size < 0 || opt_new_keyfile_size < 0 || opt_key_size < 0) {
1330                 usage(popt_context, EXIT_FAILURE,
1331                       _("Negative number for option not permitted."),
1332                       poptGetInvocationName(popt_context));
1333         }
1334
1335         if (opt_random && opt_urandom)
1336                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1337                       poptGetInvocationName(popt_context));
1338         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1339                 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1340                       poptGetInvocationName(popt_context));
1341
1342         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1343                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1344                       poptGetInvocationName(popt_context));
1345
1346         if (opt_skip && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1347                 usage(popt_context, EXIT_FAILURE,
1348                 _("Option --skip is supported only for create and loopaesOpen commands.\n"),
1349                 poptGetInvocationName(popt_context));
1350
1351         if (opt_offset && strcmp(aname, "create") && strcmp(aname, "loopaesOpen"))
1352                 usage(popt_context, EXIT_FAILURE,
1353                 _("Option --offset is supported only for create and loopaesOpen commands.\n"),
1354                 poptGetInvocationName(popt_context));
1355
1356         if (opt_debug) {
1357                 opt_verbose = 1;
1358                 crypt_set_debug_level(-1);
1359                 _dbg_version_and_cmd(argc, argv);
1360         }
1361
1362         r = run_action(action);
1363         poptFreeContext(popt_context);
1364         return r;
1365 }