Fix create command to properly handle keyfile size.
[platform/upstream/cryptsetup.git] / src / cryptsetup.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdarg.h>
6 #include <inttypes.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <assert.h>
11
12 #include <libcryptsetup.h>
13 #include <popt.h>
14
15 #include "../config.h"
16
17 #include "cryptsetup.h"
18
19 static int opt_verbose = 0;
20 static int opt_debug = 0;
21 static char *opt_cipher = NULL;
22 static char *opt_hash = NULL;
23 static int opt_verify_passphrase = 0;
24 static char *opt_key_file = NULL;
25 static char *opt_master_key_file = NULL;
26 static char *opt_header_backup_file = NULL;
27 static char *opt_uuid = NULL;
28 static unsigned int opt_key_size = 0;
29 static unsigned int opt_keyfile_size = 0;
30 static unsigned int opt_new_keyfile_size = 0;
31 static int opt_key_slot = CRYPT_ANY_SLOT;
32 static uint64_t opt_size = 0;
33 static uint64_t opt_offset = 0;
34 static uint64_t opt_skip = 0;
35 static int opt_readonly = 0;
36 static int opt_iteration_time = 1000;
37 static int opt_batch_mode = 0;
38 static int opt_version_mode = 0;
39 static int opt_timeout = 0;
40 static int opt_tries = 3;
41 static int opt_align_payload = 0;
42 static int opt_random = 0;
43 static int opt_urandom = 0;
44 static int opt_dump_master_key = 0;
45
46 static const char **action_argv;
47 static int action_argc;
48
49 static int action_create(int arg);
50 static int action_remove(int arg);
51 static int action_resize(int arg);
52 static int action_status(int arg);
53 static int action_luksFormat(int arg);
54 static int action_luksOpen(int arg);
55 static int action_luksAddKey(int arg);
56 static int action_luksKillSlot(int arg);
57 static int action_luksRemoveKey(int arg);
58 static int action_isLuks(int arg);
59 static int action_luksUUID(int arg);
60 static int action_luksDump(int arg);
61 static int action_luksSuspend(int arg);
62 static int action_luksResume(int arg);
63 static int action_luksBackup(int arg);
64 static int action_luksRestore(int arg);
65
66 static struct action_type {
67         const char *type;
68         int (*handler)(int);
69         int arg;
70         int required_action_argc;
71         int required_memlock;
72         const char *arg_desc;
73         const char *desc;
74 } action_types[] = {
75         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
76         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
77         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
78         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
79         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
80         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
81         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
82         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
83         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
84         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
85         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
86         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
87         { "luksDump",   action_luksDump,        0, 1, 0, N_("<device>"), N_("dump LUKS partition information") },
88         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
89         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
90         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
91         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
92         { NULL, NULL, 0, 0, 0, NULL, NULL }
93 };
94
95 static void clogger(struct crypt_device *cd, int level, const char *file,
96                    int line, const char *format, ...)
97 {
98         va_list argp;
99         char *target = NULL;
100
101         va_start(argp, format);
102
103         if (vasprintf(&target, format, argp) > 0) {
104                 if (level >= 0) {
105                         crypt_log(cd, level, target);
106 #ifdef CRYPT_DEBUG
107                 } else if (opt_debug)
108                         printf("# %s:%d %s\n", file ?: "?", line, target);
109 #else
110                 } else if (opt_debug)
111                         printf("# %s\n", target);
112 #endif
113         }
114
115         va_end(argp);
116         free(target);
117 }
118
119 static int _yesDialog(const char *msg, void *usrptr)
120 {
121         char *answer = NULL;
122         size_t size = 0;
123         int r = 1;
124
125         if(isatty(0) && !opt_batch_mode) {
126                 log_std("\nWARNING!\n========\n");
127                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
128                 if(getline(&answer, &size, stdin) == -1) {
129                         perror("getline");
130                         free(answer);
131                         return 0;
132                 }
133                 if(strcmp(answer, "YES\n"))
134                         r = 0;
135                 free(answer);
136         }
137
138         return r;
139 }
140
141 static void _log(int level, const char *msg, void *usrptr)
142 {
143         switch(level) {
144
145         case CRYPT_LOG_NORMAL:
146                 fputs(msg, stdout);
147                 break;
148         case CRYPT_LOG_VERBOSE:
149                 if (opt_verbose)
150                         fputs(msg, stdout);
151                 break;
152         case CRYPT_LOG_ERROR:
153                 fputs(msg, stderr);
154                 break;
155         default:
156                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
157                 break;
158         }
159 }
160
161 static void show_status(int errcode)
162 {
163         char error[256], *error_;
164
165         if(!opt_verbose)
166                 return;
167
168         if(!errcode) {
169                 log_std(_("Command successful.\n"));
170                 return;
171         }
172
173         crypt_get_error(error, sizeof(error));
174
175         if (!error[0]) {
176                 error_ = strerror_r(-errcode, error, sizeof(error));
177                 if (error_ != error) {
178                         strncpy(error, error_, sizeof(error));
179                         error[sizeof(error) - 1] = '\0';
180                 }
181         }
182
183         log_err(_("Command failed with code %i"), -errcode);
184         if (*error)
185                 log_err(": %s\n", error);
186         else
187                 log_err(".\n");
188 }
189
190 static int action_create(int arg)
191 {
192         struct crypt_device *cd = NULL;
193         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
194         struct crypt_params_plain params = {
195                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
196                 .skip = opt_skip,
197                 .offset = opt_offset,
198         };
199         char *password = NULL;
200         unsigned int passwordLen;
201         unsigned int key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8;
202         int r;
203
204         if (params.hash && !strcmp(params.hash, "plain"))
205                 params.hash = NULL;
206
207         if (opt_key_file)
208                 params.hash = NULL;
209
210         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
211                                       cipher, cipher_mode);
212         if (r < 0) {
213                 log_err("No known cipher specification pattern detected.\n");
214                 goto out;
215         }
216
217         if ((r = crypt_init(&cd, action_argv[1])))
218                 goto out;
219
220         crypt_set_timeout(cd, opt_timeout);
221         crypt_set_password_retry(cd, opt_tries);
222
223         r = crypt_format(cd, CRYPT_PLAIN,
224                          cipher, cipher_mode,
225                          NULL, NULL,
226                          key_size,
227                          &params);
228         if (r < 0)
229                 goto out;
230
231         if (opt_key_file)
232                 r = crypt_activate_by_keyfile(cd, action_argv[0],
233                         CRYPT_ANY_SLOT, opt_key_file, key_size,
234                         opt_readonly ?  CRYPT_ACTIVATE_READONLY : 0);
235         else {
236                 r = crypt_get_key(_("Enter passphrase: "),
237                                   &password, &passwordLen, 0, NULL,
238                                   opt_timeout,
239                                   opt_batch_mode ? 0 : opt_verify_passphrase,
240                                   cd);
241                 if (r < 0)
242                         goto out;
243
244                 r = crypt_activate_by_passphrase(cd, action_argv[0],
245                         CRYPT_ANY_SLOT, password, passwordLen,
246                          opt_readonly ?  CRYPT_ACTIVATE_READONLY : 0);
247         }
248 out:
249         crypt_free(cd);
250         crypt_safe_free(password);
251
252         return r;
253 }
254
255 static int action_remove(int arg)
256 {
257         struct crypt_device *cd = NULL;
258         int r;
259
260         r = crypt_init_by_name(&cd, action_argv[0]);
261         if (r == 0)
262                 r = crypt_deactivate(cd, action_argv[0]);
263
264         crypt_free(cd);
265         return r;
266 }
267
268 static int action_resize(int arg)
269 {
270         struct crypt_device *cd = NULL;
271         int r;
272
273         r = crypt_init_by_name(&cd, action_argv[0]);
274         if (r == 0)
275                 r = crypt_resize(cd, action_argv[0], opt_size);
276
277         crypt_free(cd);
278         return r;
279 }
280
281 static int action_status(int arg)
282 {
283         crypt_status_info ci;
284         struct crypt_active_device cad;
285         struct crypt_device *cd = NULL;
286         int r = 0;
287
288         ci = crypt_status(NULL, action_argv[0]);
289         switch (ci) {
290         case CRYPT_INVALID:
291                 r = -ENODEV;
292                 break;
293         case CRYPT_INACTIVE:
294                 log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
295                 break;
296         case CRYPT_ACTIVE:
297         case CRYPT_BUSY:
298                 log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
299                         ci == CRYPT_BUSY ? " and is in use" : "");
300                 r = crypt_init_by_name(&cd, action_argv[0]);
301                 if (r < 0 || !crypt_get_type(cd))
302                         goto out;
303
304                 log_std("  type:  %s\n", crypt_get_type(cd));
305
306                 r = crypt_get_active_device(cd, action_argv[0], &cad);
307                 if (r < 0)
308                         goto out;
309
310                 log_std("  cipher:  %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
311                 log_std("  keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
312                 log_std("  device:  %s\n", crypt_get_device_name(cd));
313                 log_std("  offset:  %" PRIu64 " sectors\n", cad.offset);
314                 log_std("  size:    %" PRIu64 " sectors\n", cad.size);
315                 if (cad.iv_offset)
316                         log_std("  skipped: %" PRIu64 " sectors\n", cad.iv_offset);
317                 log_std("  mode:    %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
318                                            "readonly" : "read/write");
319         }
320 out:
321         crypt_free(cd);
322         return r;
323 }
324
325 static int _read_mk(const char *file, char **key, int keysize)
326 {
327         int fd;
328
329         *key = crypt_safe_alloc(keysize);
330         if (!*key)
331                 return -ENOMEM;
332
333         fd = open(file, O_RDONLY);
334         if (fd == -1) {
335                 log_err("Cannot read keyfile %s.\n", file);
336                 goto fail;
337         }
338         if ((read(fd, *key, keysize) != keysize)) {
339                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
340                 close(fd);
341                 goto fail;
342         }
343         close(fd);
344         return 0;
345 fail:
346         crypt_safe_free(*key);
347         *key = NULL;
348         return -EINVAL;
349 }
350
351 static int action_luksFormat(int arg)
352 {
353         int r = -EINVAL, keysize;
354         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
355         char *password = NULL;
356         unsigned int passwordLen;
357         struct crypt_device *cd = NULL;
358         struct crypt_params_luks1 params = {
359                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
360                 .data_alignment = opt_align_payload,
361         };
362
363         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
364                 log_err(_("memory allocation error in action_luksFormat"));
365                 r = -ENOMEM;
366                 goto out;
367         }
368         r = _yesDialog(msg, NULL) ? 0 : -EINVAL;
369         free(msg);
370         if (r < 0)
371                 goto out;
372
373         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
374                                       cipher, cipher_mode);
375         if (r < 0) {
376                 log_err("No known cipher specification pattern detected.\n");
377                 goto out;
378         }
379
380         if ((r = crypt_init(&cd, action_argv[0])))
381                 goto out;
382
383         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
384
385         crypt_set_password_verify(cd, 1);
386         crypt_set_timeout(cd, opt_timeout);
387         if (opt_iteration_time)
388                 crypt_set_iterarion_time(cd, opt_iteration_time);
389
390         if (opt_random)
391                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
392         else if (opt_urandom)
393                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
394
395         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
396                           opt_keyfile_size, opt_key_file, opt_timeout,
397                           opt_batch_mode ? 0 : 1 /* always verify */, cd);
398         if (r < 0)
399                 goto out;
400
401         if (opt_master_key_file) {
402                 r = _read_mk(opt_master_key_file, &key, keysize);
403                 if (r < 0)
404                         goto out;
405         }
406
407         r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
408                          opt_uuid, key, keysize, &params);
409         if (r < 0)
410                 goto out;
411
412         r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
413                                             key, keysize,
414                                             password, passwordLen);
415 out:
416         crypt_free(cd);
417         crypt_safe_free(key);
418         crypt_safe_free(password);
419
420         return r;
421 }
422
423 static int action_luksOpen(int arg)
424 {
425         struct crypt_device *cd = NULL;
426         uint32_t flags = 0;
427         int r;
428
429         if ((r = crypt_init(&cd, action_argv[0])))
430                 goto out;
431
432         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
433                 goto out;
434
435         crypt_set_timeout(cd, opt_timeout);
436         crypt_set_password_retry(cd, opt_tries);
437
438         if (opt_iteration_time)
439                 crypt_set_iterarion_time(cd, opt_iteration_time);
440         if (opt_readonly)
441                 flags |= CRYPT_ACTIVATE_READONLY;
442
443         if (opt_key_file) {
444                 crypt_set_password_retry(cd, 1);
445                 r = crypt_activate_by_keyfile(cd, action_argv[1],
446                         CRYPT_ANY_SLOT, opt_key_file, opt_keyfile_size,
447                         flags);
448         } else
449                 r = crypt_activate_by_passphrase(cd, action_argv[1],
450                         CRYPT_ANY_SLOT, NULL, 0, flags);
451 out:
452         crypt_free(cd);
453         return r;
454 }
455
456 static int verify_keyslot(struct crypt_device *cd, int key_slot,
457                           char *msg_last, char *msg_pass,
458                           const char *key_file, int keyfile_size)
459 {
460         crypt_keyslot_info ki;
461         char *password = NULL;
462         unsigned int passwordLen, i;
463         int r;
464
465         ki = crypt_keyslot_status(cd, key_slot);
466         if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
467                 return -EPERM;
468
469         r = crypt_get_key(msg_pass, &password, &passwordLen,
470                           keyfile_size, key_file, opt_timeout,
471                           opt_batch_mode ? 0 : opt_verify_passphrase, cd);
472         if(r < 0)
473                 goto out;
474
475         if (ki == CRYPT_SLOT_ACTIVE_LAST) {
476                 /* check the last keyslot */
477                 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
478                                                  password, passwordLen, 0);
479         } else {
480                 /* try all other keyslots */
481                 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
482                         if (i == key_slot)
483                                 continue;
484                         ki = crypt_keyslot_status(cd, key_slot);
485                         if (ki == CRYPT_SLOT_ACTIVE)
486                         r = crypt_activate_by_passphrase(cd, NULL, i,
487                                                          password, passwordLen, 0);
488                         if (r == i)
489                                 break;
490                 }
491         }
492
493         if (r < 0)
494                 log_err(_("No key available with this passphrase.\n"));
495 out:
496         crypt_safe_free(password);
497         return r;
498 }
499
500 static int action_luksKillSlot(int arg)
501 {
502         struct crypt_device *cd = NULL;
503         int r;
504
505         if ((r = crypt_init(&cd, action_argv[0])))
506                 goto out;
507
508         crypt_set_confirm_callback(cd, _yesDialog, NULL);
509         crypt_set_timeout(cd, opt_timeout);
510
511         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
512                 goto out;
513
514         switch (crypt_keyslot_status(cd, opt_key_slot)) {
515         case CRYPT_SLOT_ACTIVE_LAST:
516         case CRYPT_SLOT_ACTIVE:
517                 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
518                 break;
519         case CRYPT_SLOT_INACTIVE:
520                 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
521         case CRYPT_SLOT_INVALID:
522                 goto out;
523         }
524
525         if (!opt_batch_mode) {
526                 r = verify_keyslot(cd, opt_key_slot,
527                         _("This is the last keyslot. Device will become unusable after purging this key."),
528                         _("Enter any remaining LUKS passphrase: "),
529                         opt_key_file, opt_keyfile_size);
530                 if (r < 0)
531                         goto out;
532         }
533
534         r = crypt_keyslot_destroy(cd, opt_key_slot);
535 out:
536         crypt_free(cd);
537         return r;
538 }
539
540 static int action_luksRemoveKey(int arg)
541 {
542         struct crypt_device *cd = NULL;
543         char *password = NULL;
544         unsigned int passwordLen;
545         int r;
546
547         if ((r = crypt_init(&cd, action_argv[0])))
548                 goto out;
549
550         crypt_set_confirm_callback(cd, _yesDialog, NULL);
551         crypt_set_timeout(cd, opt_timeout);
552
553         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
554                 goto out;
555
556         r = crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
557                       &password, &passwordLen,
558                       opt_keyfile_size, opt_key_file,
559                       opt_timeout,
560                       opt_batch_mode ? 0 : opt_verify_passphrase,
561                       cd);
562         if(r < 0)
563                 goto out;
564
565         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
566                                          password, passwordLen, 0);
567         if (r < 0)
568                 goto out;
569
570         opt_key_slot = r;
571         log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
572
573         if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
574             !_yesDialog(_("This is the last keyslot. "
575                           "Device will become unusable after purging this key."),
576                         NULL)) {
577                 r = -EPERM;
578                 goto out;
579         }
580
581         r = crypt_keyslot_destroy(cd, opt_key_slot);
582 out:
583         crypt_safe_free(password);
584         crypt_free(cd);
585         return r;
586 }
587
588 static int action_luksAddKey(int arg)
589 {
590         int r = -EINVAL, keysize = 0;
591         char *key = NULL;
592         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
593         struct crypt_device *cd = NULL;
594
595         if ((r = crypt_init(&cd, action_argv[0])))
596                 goto out;
597
598         crypt_set_confirm_callback(cd, _yesDialog, NULL);
599
600         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
601                 goto out;
602
603         keysize = crypt_get_volume_key_size(cd);
604         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
605         crypt_set_timeout(cd, opt_timeout);
606         if (opt_iteration_time)
607                 crypt_set_iterarion_time(cd, opt_iteration_time);
608
609         if (opt_master_key_file) {
610                 if (_read_mk(opt_master_key_file, &key, keysize) < 0)
611                         goto out;
612
613                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
614                                                     key, keysize, NULL, 0);
615         } else if (opt_key_file || opt_new_key_file) {
616                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
617                                                  opt_key_file, opt_keyfile_size,
618                                                  opt_new_key_file, opt_new_keyfile_size);
619         } else {
620                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
621                                                     NULL, 0, NULL, 0);
622         }
623 out:
624         crypt_free(cd);
625         crypt_safe_free(key);
626         return r;
627 }
628
629 static int action_isLuks(int arg)
630 {
631         struct crypt_device *cd = NULL;
632         int r;
633
634         if ((r = crypt_init(&cd, action_argv[0])))
635                 goto out;
636
637         r = crypt_load(cd, CRYPT_LUKS1, NULL);
638 out:
639         crypt_free(cd);
640         return r;
641 }
642
643 static int action_luksUUID(int arg)
644 {
645         struct crypt_device *cd = NULL;
646         const char *existing_uuid = NULL;
647         int r;
648
649         if ((r = crypt_init(&cd, action_argv[0])))
650                 goto out;
651
652         crypt_set_confirm_callback(cd, _yesDialog, NULL);
653
654         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
655                 goto out;
656
657         if (opt_uuid)
658                 r = crypt_set_uuid(cd, opt_uuid);
659         else {
660                 existing_uuid = crypt_get_uuid(cd);
661                 log_std("%s\n", existing_uuid ?: "");
662                 r = existing_uuid ? 0 : 1;
663         }
664 out:
665         crypt_free(cd);
666         return r;
667 }
668
669 static int luksDump_with_volume_key(struct crypt_device *cd)
670 {
671         char *vk = NULL, *password = NULL;
672         unsigned int passwordLen = 0;
673         size_t vk_size;
674         int i, r;
675
676         crypt_set_confirm_callback(cd, _yesDialog, NULL);
677         if (!_yesDialog(
678             _("LUKS header dump with volume key is sensitive information\n"
679               "which allows access to encrypted partition without passphrase.\n"
680               "This dump should be always stored encrypted on safe place."),
681               NULL))
682                 return -EPERM;
683
684         vk_size = crypt_get_volume_key_size(cd);
685         vk = crypt_safe_alloc(vk_size);
686         if (!vk)
687                 return -ENOMEM;
688
689         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
690                           opt_keyfile_size, opt_key_file, opt_timeout, 0, cd);
691         if (r < 0)
692                 goto out;
693
694         r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
695                                  password, passwordLen);
696         if (r < 0)
697                 goto out;
698
699         log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
700         log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
701         log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
702         log_std("Payload offset:\t%d\n", crypt_get_data_offset(cd));
703         log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
704         log_std("MK bits:       \t%d\n", vk_size * 8);
705         log_std("MK dump:\t");
706
707         for(i = 0; i < vk_size; i++) {
708                 if (i && !(i % 16))
709                         log_std("\n\t\t");
710                 log_std("%02hhx ", (char)vk[i]);
711         }
712         log_std("\n");
713
714 out:
715         crypt_safe_free(password);
716         crypt_safe_free(vk);
717         return r;
718 }
719
720 static int action_luksDump(int arg)
721 {
722         struct crypt_device *cd = NULL;
723         int r;
724
725         if ((r = crypt_init(&cd, action_argv[0])))
726                 goto out;
727
728         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
729                 goto out;
730
731         if (opt_dump_master_key)
732                 r = luksDump_with_volume_key(cd);
733         else
734                 r = crypt_dump(cd);
735 out:
736         crypt_free(cd);
737         return r;
738 }
739
740 static int action_luksSuspend(int arg)
741 {
742         struct crypt_device *cd = NULL;
743         int r;
744
745         r = crypt_init_by_name(&cd, action_argv[0]);
746         if (!r)
747                 r = crypt_suspend(cd, action_argv[0]);
748
749         crypt_free(cd);
750         return r;
751 }
752
753 static int action_luksResume(int arg)
754 {
755         struct crypt_device *cd = NULL;
756         int r;
757
758         if ((r = crypt_init_by_name(&cd, action_argv[0])))
759                 goto out;
760
761         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
762                 goto out;
763
764         if (opt_key_file)
765                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
766                                             opt_key_file, opt_keyfile_size);
767         else
768                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
769                                                NULL, 0);
770 out:
771         crypt_free(cd);
772         return r;
773 }
774
775 static int action_luksBackup(int arg)
776 {
777         struct crypt_device *cd = NULL;
778         int r;
779
780         if (!opt_header_backup_file) {
781                 log_err(_("Option --header-backup-file is required.\n"));
782                 return -EINVAL;
783         }
784
785         if ((r = crypt_init(&cd, action_argv[0])))
786                 goto out;
787
788         crypt_set_confirm_callback(cd, _yesDialog, NULL);
789
790         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
791 out:
792         crypt_free(cd);
793         return r;
794 }
795
796 static int action_luksRestore(int arg)
797 {
798         struct crypt_device *cd = NULL;
799         int r = 0;
800
801         if (!opt_header_backup_file) {
802                 log_err(_("Option --header-backup-file is required.\n"));
803                 return -EINVAL;
804         }
805
806         if ((r = crypt_init(&cd, action_argv[0])))
807                 goto out;
808
809         crypt_set_confirm_callback(cd, _yesDialog, NULL);
810         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
811 out:
812         crypt_free(cd);
813         return r;
814 }
815
816 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
817                                              int exitcode, const char *error,
818                                              const char *more)
819 {
820         poptPrintUsage(popt_context, stderr, 0);
821         if (error)
822                 log_err("%s: %s\n", more, error);
823         exit(exitcode);
824 }
825
826 static void help(poptContext popt_context, enum poptCallbackReason reason,
827                  struct poptOption *key, const char * arg, void *data)
828 {
829         if (key->shortName == '?') {
830                 struct action_type *action;
831
832                 log_std("%s\n",PACKAGE_STRING);
833
834                 poptPrintHelp(popt_context, stdout, 0);
835
836                 log_std(_("\n"
837                          "<action> is one of:\n"));
838
839                 for(action = action_types; action->type; action++)
840                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
841
842                 log_std(_("\n"
843                          "<name> is the device to create under %s\n"
844                          "<device> is the encrypted device\n"
845                          "<key slot> is the LUKS key slot number to modify\n"
846                          "<key file> optional key file for the new key for luksAddKey action\n"),
847                         crypt_get_dir());
848
849                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
850                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
851                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
852                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
853                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
854                          DEFAULT_RNG);
855                 exit(EXIT_SUCCESS);
856         } else
857                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
858 }
859
860 static void _dbg_version_and_cmd(int argc, char **argv)
861 {
862         int i;
863
864         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
865         for (i = 0; i < argc; i++) {
866                 if (i)
867                         log_std(" ");
868                 log_std(argv[i]);
869         }
870         log_std("\"\n");
871 }
872
873 static int run_action(struct action_type *action)
874 {
875         int r;
876
877         if (action->required_memlock)
878                 crypt_memory_lock(NULL, 1);
879
880         r = action->handler(action->arg);
881
882         if (action->required_memlock)
883                 crypt_memory_lock(NULL, 0);
884
885         /* Some functions returns keyslot # */
886         if (r > 0)
887                 r = 0;
888
889         show_status(r);
890
891         /* Translate exit code to simple codes */
892         switch (r) {
893         case 0:         r = EXIT_SUCCESS; break;
894         case -EEXIST:
895         case -EBUSY:    r = 5; break;
896         case -ENOTBLK:
897         case -ENODEV:   r = 4; break;
898         case -ENOMEM:   r = 3; break;
899         case -EPERM:    r = 2; break;
900         case -EINVAL:
901         case -ENOENT:
902         case -ENOSYS:
903         default:        r = EXIT_FAILURE;
904         }
905         return r;
906 }
907
908 int main(int argc, char **argv)
909 {
910         static char *popt_tmp;
911         static struct poptOption popt_help_options[] = {
912                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
913                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
914                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
915                 POPT_TABLEEND
916         };
917         static struct poptOption popt_options[] = {
918                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
919                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
920                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
921                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
922                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
923                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
924                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
925                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
926                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
927                 { "dump-master-key",  '\0',  POPT_ARG_NONE, &opt_dump_master_key,       0, N_("Dump volume (master) key instead of keyslots info."), NULL },
928                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
929                 { "keyfile-size",      'l',  POPT_ARG_INT, &opt_keyfile_size,           0, N_("Limits the read from keyfile"), N_("bytes") },
930                 { "new-keyfile-size", '\0',  POPT_ARG_INT, &opt_new_keyfile_size,       0, N_("Limits the read from newly added keyfile"), N_("bytes") },
931                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
932                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
933                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
934                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
935                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
936                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
937                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
938                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
939                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
940                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
941                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
942                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
943                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
944                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
945                 POPT_TABLEEND
946         };
947         poptContext popt_context;
948         struct action_type *action;
949         char *aname;
950         int r;
951         const char *null_action_argv[] = {NULL};
952
953         crypt_set_log_callback(NULL, _log, NULL);
954
955         setlocale(LC_ALL, "");
956         bindtextdomain(PACKAGE, LOCALEDIR);
957         textdomain(PACKAGE);
958
959         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
960                                       popt_options, 0);
961         poptSetOtherOptionHelp(popt_context,
962                                N_("[OPTION...] <action> <action-specific>]"));
963
964         while((r = poptGetNextOpt(popt_context)) > 0) {
965                 unsigned long long ull_value;
966                 char *endp;
967
968                 ull_value = strtoull(popt_tmp, &endp, 0);
969                 if (*endp || !*popt_tmp)
970                         r = POPT_ERROR_BADNUMBER;
971
972                 switch(r) {
973                         case 1:
974                                 opt_size = ull_value;
975                                 break;
976                         case 2:
977                                 opt_offset = ull_value;
978                                 break;
979                         case 3:
980                                 opt_skip = ull_value;
981                                 break;
982                 }
983
984                 if (r < 0)
985                         break;
986         }
987
988         if (r < -1)
989                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
990                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
991         if (opt_version_mode) {
992                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
993                 exit(EXIT_SUCCESS);
994         }
995
996         if (!(aname = (char *)poptGetArg(popt_context)))
997                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
998                       poptGetInvocationName(popt_context));
999         for(action = action_types; action->type; action++)
1000                 if (strcmp(action->type, aname) == 0)
1001                         break;
1002         if (!action->type)
1003                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1004                       poptGetInvocationName(popt_context));
1005
1006         action_argc = 0;
1007         action_argv = poptGetArgs(popt_context);
1008         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1009         if(!action_argv)
1010                 action_argv = null_action_argv;
1011
1012         /* Count args, somewhat unnice, change? */
1013         while(action_argv[action_argc] != NULL)
1014                 action_argc++;
1015
1016         if(action_argc < action->required_action_argc) {
1017                 char buf[128];
1018                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
1019                 usage(popt_context, EXIT_FAILURE, buf,
1020                       poptGetInvocationName(popt_context));
1021         }
1022
1023         /* FIXME: rewrite this from scratch */
1024
1025         if (opt_key_size &&
1026            strcmp(aname, "luksFormat") &&
1027            strcmp(aname, "create")) {
1028                 usage(popt_context, EXIT_FAILURE,
1029                       _("Option --key-size is allowed only for luksFormat and create.\n"
1030                         "To limit read from keyfile use --keyfile-size=(bytes)."),
1031                       poptGetInvocationName(popt_context));
1032         }
1033
1034         if (opt_key_size % 8)
1035                 usage(popt_context, EXIT_FAILURE,
1036                       _("Key size must be a multiple of 8 bits"),
1037                       poptGetInvocationName(popt_context));
1038
1039         if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1040                 opt_key_slot = atoi(action_argv[1]);
1041         if (opt_key_slot != CRYPT_ANY_SLOT &&
1042             (opt_key_slot < 0 || opt_key_slot > crypt_keyslot_max(CRYPT_LUKS1)))
1043                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1044                       poptGetInvocationName(popt_context));
1045
1046         if ((!strcmp(aname, "luksRemoveKey") ||
1047              !strcmp(aname, "luksFormat")) &&
1048              action_argc > 1) {
1049                 if (opt_key_file)
1050                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1051                 else
1052                         opt_key_file = (char*)action_argv[1];
1053         }
1054
1055         if (opt_random && opt_urandom)
1056                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1057                       poptGetInvocationName(popt_context));
1058         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1059                 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1060                       poptGetInvocationName(popt_context));
1061
1062         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1063                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1064                       poptGetInvocationName(popt_context));
1065
1066         if ((opt_offset || opt_skip) && strcmp(aname, "create"))
1067                 usage(popt_context, EXIT_FAILURE, _("Options --offset and --skip are supported only for create command.\n"),
1068                       poptGetInvocationName(popt_context));
1069
1070         if (opt_debug) {
1071                 opt_verbose = 1;
1072                 crypt_set_debug_level(-1);
1073                 _dbg_version_and_cmd(argc, argv);
1074         }
1075
1076         return run_action(action);
1077 }