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