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