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