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