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