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