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