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