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