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