* Add crypt_get_type(), crypt_resize(), crypt_keyslot_max()
[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
45 static const char **action_argv;
46 static int action_argc;
47
48 static int action_create(int arg);
49 static int action_remove(int arg);
50 static int action_resize(int arg);
51 static int action_status(int arg);
52 static int action_luksFormat(int arg);
53 static int action_luksOpen(int arg);
54 static int action_luksAddKey(int arg);
55 static int action_luksKillSlot(int arg);
56 static int action_luksRemoveKey(int arg);
57 static int action_isLuks(int arg);
58 static int action_luksUUID(int arg);
59 static int action_luksDump(int arg);
60 static int action_luksSuspend(int arg);
61 static int action_luksResume(int arg);
62 static int action_luksBackup(int arg);
63 static int action_luksRestore(int arg);
64
65 static struct action_type {
66         const char *type;
67         int (*handler)(int);
68         int arg;
69         int required_action_argc;
70         int required_memlock;
71         const char *arg_desc;
72         const char *desc;
73 } action_types[] = {
74         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
75         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
76         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
77         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
78         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
79         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
80         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
81         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
82         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
83         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
84         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
85         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
86         { "luksDump",   action_luksDump,        0, 1, 0, N_("<device>"), N_("dump LUKS partition information") },
87         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
88         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
89         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
90         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
91         { NULL, NULL, 0, 0, 0, NULL, NULL }
92 };
93
94 static void clogger(struct crypt_device *cd, int level, const char *file,
95                    int line, const char *format, ...)
96 {
97         va_list argp;
98         char *target = NULL;
99
100         va_start(argp, format);
101
102         if (vasprintf(&target, format, argp) > 0) {
103                 if (level >= 0) {
104                         crypt_log(cd, level, target);
105 #ifdef CRYPT_DEBUG
106                 } else if (opt_debug)
107                         printf("# %s:%d %s\n", file ?: "?", line, target);
108 #else
109                 } else if (opt_debug)
110                         printf("# %s\n", target);
111 #endif
112         }
113
114         va_end(argp);
115         free(target);
116 }
117
118 static int _yesDialog(const char *msg, void *usrptr)
119 {
120         char *answer = NULL;
121         size_t size = 0;
122         int r = 1;
123
124         if(isatty(0) && !opt_batch_mode) {
125                 log_std("\nWARNING!\n========\n");
126                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
127                 if(getline(&answer, &size, stdin) == -1) {
128                         perror("getline");
129                         free(answer);
130                         return 0;
131                 }
132                 if(strcmp(answer, "YES\n"))
133                         r = 0;
134                 free(answer);
135         }
136
137         return r;
138 }
139
140 static void _log(int level, const char *msg, void *usrptr)
141 {
142         switch(level) {
143
144         case CRYPT_LOG_NORMAL:
145                 fputs(msg, stdout);
146                 break;
147         case CRYPT_LOG_VERBOSE:
148                 if (opt_verbose)
149                         fputs(msg, stdout);
150                 break;
151         case CRYPT_LOG_ERROR:
152                 fputs(msg, stderr);
153                 break;
154         default:
155                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
156                 break;
157         }
158 }
159
160 static void show_status(int errcode)
161 {
162         char error[256], *error_;
163
164         if(!opt_verbose)
165                 return;
166
167         if(!errcode) {
168                 log_std(_("Command successful.\n"));
169                 return;
170         }
171
172         crypt_get_error(error, sizeof(error));
173
174         if (!error[0]) {
175                 error_ = strerror_r(-errcode, error, sizeof(error));
176                 if (error_ != error) {
177                         strncpy(error, error_, sizeof(error));
178                         error[sizeof(error) - 1] = '\0';
179                 }
180         }
181
182         log_err(_("Command failed with code %i"), -errcode);
183         if (*error)
184                 log_err(": %s\n", error);
185         else
186                 log_err(".\n");
187 }
188
189 static int action_create(int arg)
190 {
191         struct crypt_device *cd = NULL;
192         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
193         struct crypt_params_plain params = {
194                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
195                 .skip = opt_skip,
196                 .offset = opt_offset,
197         };
198         char *password = NULL;
199         unsigned int passwordLen;
200         int r;
201
202         if (params.hash && !strcmp(params.hash, "plain"))
203                 params.hash = NULL;
204
205         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
206                                       cipher, cipher_mode);
207         if (r < 0) {
208                 log_err("No known cipher specification pattern detected.\n");
209                 goto out;
210         }
211
212         if ((r = crypt_init(&cd, action_argv[1])))
213                 goto out;
214
215         crypt_set_timeout(cd, opt_timeout);
216         crypt_set_password_retry(cd, opt_tries);
217
218         r = crypt_format(cd, CRYPT_PLAIN,
219                          cipher, cipher_mode,
220                          NULL, NULL,
221                          (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8,
222                          &params);
223         if (r < 0)
224                 goto out;
225
226         crypt_get_key(_("Enter passphrase: "),
227                       &password, &passwordLen,
228                       opt_keyfile_size, opt_key_file,
229                       opt_timeout,
230                       opt_batch_mode ? 0 : opt_verify_passphrase,
231                       cd);
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 < 0) ? r : 0;
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 = -EINVAL;
384         crypt_get_key(_("Enter LUKS passphrase: "),
385                       &password, &passwordLen,
386                       opt_keyfile_size, opt_key_file,
387                       opt_timeout,
388                       opt_batch_mode ? 0 : 1, /* always verify */
389                       cd);
390         if(!password)
391                 goto out;
392
393         if (opt_master_key_file) {
394                 r = _read_mk(opt_master_key_file, &key, keysize);
395                 if (r < 0)
396                         goto out;
397         }
398
399         r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
400                          opt_uuid, key, keysize, &params);
401         if (r < 0)
402                 goto out;
403
404         r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
405                                             key, keysize,
406                                             password, passwordLen);
407 out:
408         crypt_free(cd);
409         crypt_safe_free(key);
410         crypt_safe_free(password);
411
412         return (r < 0) ? r : 0;
413 }
414
415 static int action_luksOpen(int arg)
416 {
417         struct crypt_device *cd = NULL;
418         uint32_t flags = 0;
419         int r;
420
421         if ((r = crypt_init(&cd, action_argv[0])))
422                 goto out;
423
424         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
425                 goto out;
426
427         crypt_set_timeout(cd, opt_timeout);
428         crypt_set_password_retry(cd, opt_tries);
429
430         if (opt_iteration_time)
431                 crypt_set_iterarion_time(cd, opt_iteration_time);
432         if (opt_readonly)
433                 flags |= CRYPT_ACTIVATE_READONLY;
434
435         if (opt_key_file) {
436                 crypt_set_password_retry(cd, 1);
437                 r = crypt_activate_by_keyfile(cd, action_argv[1],
438                         CRYPT_ANY_SLOT, opt_key_file, opt_keyfile_size,
439                         flags);
440         } else
441                 r = crypt_activate_by_passphrase(cd, action_argv[1],
442                         CRYPT_ANY_SLOT, NULL, 0, flags);
443 out:
444         crypt_free(cd);
445         return (r < 0) ? r : 0;
446 }
447
448 static int verify_keyslot(struct crypt_device *cd, int key_slot,
449                           char *msg_last, char *msg_pass,
450                           const char *key_file, int keyfile_size)
451 {
452         crypt_keyslot_info ki;
453         char *password = NULL;
454         unsigned int passwordLen, i;
455         int r = -EPERM;
456
457         ki = crypt_keyslot_status(cd, key_slot);
458         if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
459                 return -EPERM;
460
461         crypt_get_key(msg_pass, &password, &passwordLen,
462                       keyfile_size, key_file,
463                       opt_timeout,
464                       opt_batch_mode ? 0 : opt_verify_passphrase,
465                       cd);
466         if(!password)
467                 return -EINVAL;
468
469         if (ki == CRYPT_SLOT_ACTIVE_LAST) {
470                 /* check the last keyslot */
471                 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
472                                                  password, passwordLen, 0);
473         } else {
474                 /* try all other keyslots */
475                 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
476                         if (i == key_slot)
477                                 continue;
478                         ki = crypt_keyslot_status(cd, key_slot);
479                         if (ki == CRYPT_SLOT_ACTIVE)
480                         r = crypt_activate_by_passphrase(cd, NULL, i,
481                                                          password, passwordLen, 0);
482                         if (r == i)
483                                 break;
484                 }
485         }
486
487         if (r < 0)
488                 log_err(_("No key available with this passphrase.\n"));
489
490         crypt_safe_free(password);
491         return r;
492 }
493
494 static int action_luksKillSlot(int arg)
495 {
496         struct crypt_device *cd = NULL;
497         int r;
498
499         if ((r = crypt_init(&cd, action_argv[0])))
500                 goto out;
501
502         crypt_set_confirm_callback(cd, _yesDialog, NULL);
503         crypt_set_timeout(cd, opt_timeout);
504
505         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
506                 goto out;
507
508         switch (crypt_keyslot_status(cd, opt_key_slot)) {
509         case CRYPT_SLOT_ACTIVE_LAST:
510         case CRYPT_SLOT_ACTIVE:
511                 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
512                 break;
513         case CRYPT_SLOT_INACTIVE:
514                 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
515         case CRYPT_SLOT_INVALID:
516                 goto out;
517         }
518
519         if (!opt_batch_mode) {
520                 r = verify_keyslot(cd, opt_key_slot,
521                         _("This is the last keyslot. Device will become unusable after purging this key."),
522                         _("Enter any remaining LUKS passphrase: "),
523                         opt_key_file, opt_keyfile_size);
524                 if (r < 0)
525                         goto out;
526         }
527
528         r = crypt_keyslot_destroy(cd, opt_key_slot);
529 out:
530         crypt_free(cd);
531
532         return (r < 0) ? r : 0;
533 }
534
535 static int action_luksRemoveKey(int arg)
536 {
537         struct crypt_device *cd = NULL;
538         crypt_keyslot_info ki;
539         char *password = NULL;
540         unsigned int passwordLen;
541         int r;
542
543         if ((r = crypt_init(&cd, action_argv[0])))
544                 goto out;
545
546         crypt_set_confirm_callback(cd, _yesDialog, NULL);
547         crypt_set_timeout(cd, opt_timeout);
548
549         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
550                 goto out;
551
552         crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
553                       &password, &passwordLen,
554                       opt_keyfile_size, opt_key_file,
555                       opt_timeout,
556                       opt_batch_mode ? 0 : opt_verify_passphrase,
557                       cd);
558         if(!password) {
559                 r = -EINVAL;
560                 goto out;
561         }
562
563         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
564                                          password, passwordLen, 0);
565         if (r < 0)
566                 goto out;
567
568         opt_key_slot = r;
569         log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
570
571         if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
572             !_yesDialog(_("This is the last keyslot. "
573                           "Device will become unusable after purging this key."),
574                         NULL)) {
575                 r = -EPERM;
576                 goto out;
577         }
578
579         r = crypt_keyslot_destroy(cd, opt_key_slot);
580 out:
581         crypt_safe_free(password);
582         crypt_free(cd);
583
584         return (r < 0) ? r : 0;
585 }
586
587 static int action_luksAddKey(int arg)
588 {
589         int r = -EINVAL, keysize = 0;
590         char *key = NULL;
591         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
592         struct crypt_device *cd = NULL;
593
594         if ((r = crypt_init(&cd, action_argv[0])))
595                 goto out;
596
597         crypt_set_confirm_callback(cd, _yesDialog, NULL);
598
599         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
600                 goto out;
601
602         keysize = crypt_get_volume_key_size(cd);
603         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
604         crypt_set_timeout(cd, opt_timeout);
605         if (opt_iteration_time)
606                 crypt_set_iterarion_time(cd, opt_iteration_time);
607
608         if (opt_master_key_file) {
609                 if (_read_mk(opt_master_key_file, &key, keysize) < 0)
610                         goto out;
611
612                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
613                                                     key, keysize, NULL, 0);
614         } else if (opt_key_file || opt_new_key_file) {
615                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
616                                                  opt_key_file, opt_keyfile_size,
617                                                  opt_new_key_file, opt_new_keyfile_size);
618         } else {
619                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
620                                                     NULL, 0, NULL, 0);
621         }
622 out:
623         crypt_free(cd);
624         crypt_safe_free(key);
625
626         return (r < 0) ? r : 0;
627 }
628
629 static int action_isLuks(int arg)
630 {
631         struct crypt_device *cd = NULL;
632         int r;
633
634         if ((r = crypt_init(&cd, action_argv[0])))
635                 goto out;
636
637         r = crypt_load(cd, CRYPT_LUKS1, NULL);
638 out:
639         crypt_free(cd);
640         return r;
641 }
642
643 static int action_luksUUID(int arg)
644 {
645         struct crypt_device *cd = NULL;
646         const char *existing_uuid = NULL;
647         int r;
648
649         if ((r = crypt_init(&cd, action_argv[0])))
650                 goto out;
651
652         crypt_set_confirm_callback(cd, _yesDialog, NULL);
653
654         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
655                 goto out;
656
657         if (opt_uuid)
658                 r = crypt_set_uuid(cd, opt_uuid);
659         else {
660                 existing_uuid = crypt_get_uuid(cd);
661                 log_std("%s\n", existing_uuid ?: "");
662                 r = existing_uuid ? 0 : 1;
663         }
664 out:
665         crypt_free(cd);
666         return r;
667
668 }
669
670 static int action_luksDump(int arg)
671 {
672         struct crypt_device *cd = NULL;
673         int r;
674
675         if ((r = crypt_init(&cd, action_argv[0])))
676                 goto out;
677
678         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
679                 goto out;
680
681         r = crypt_dump(cd);
682 out:
683         crypt_free(cd);
684         return r;
685 }
686
687 static int action_luksSuspend(int arg)
688 {
689         struct crypt_device *cd = NULL;
690         int r;
691
692         r = crypt_init_by_name(&cd, action_argv[0]);
693         if (!r)
694                 r = crypt_suspend(cd, action_argv[0]);
695
696         crypt_free(cd);
697         return r;
698 }
699
700 static int action_luksResume(int arg)
701 {
702         struct crypt_device *cd = NULL;
703         int r;
704
705         if ((r = crypt_init_by_name(&cd, action_argv[0])))
706                 goto out;
707
708         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
709                 goto out;
710
711         if (opt_key_file)
712                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
713                                             opt_key_file, opt_keyfile_size);
714         else
715                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
716                                                NULL, 0);
717 out:
718         crypt_free(cd);
719         return r;
720 }
721
722 static int action_luksBackup(int arg)
723 {
724         struct crypt_device *cd = NULL;
725         int r;
726
727         if (!opt_header_backup_file) {
728                 log_err(_("Option --header-backup-file is required.\n"));
729                 return -EINVAL;
730         }
731
732         if ((r = crypt_init(&cd, action_argv[0])))
733                 goto out;
734
735         crypt_set_confirm_callback(cd, _yesDialog, NULL);
736
737         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
738 out:
739         crypt_free(cd);
740         return r;
741 }
742
743 static int action_luksRestore(int arg)
744 {
745         struct crypt_device *cd = NULL;
746         int r = 0;
747
748         if (!opt_header_backup_file) {
749                 log_err(_("Option --header-backup-file is required.\n"));
750                 return -EINVAL;
751         }
752
753         if ((r = crypt_init(&cd, action_argv[0])))
754                 goto out;
755
756         crypt_set_confirm_callback(cd, _yesDialog, NULL);
757         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
758 out:
759         crypt_free(cd);
760         return r;
761 }
762
763 static void usage(poptContext popt_context, int exitcode,
764                   const char *error, const char *more)
765 {
766         poptPrintUsage(popt_context, stderr, 0);
767         if (error)
768                 log_err("%s: %s\n", more, error);
769         exit(exitcode);
770 }
771
772 static void help(poptContext popt_context, enum poptCallbackReason reason,
773                  struct poptOption *key, const char * arg, void *data)
774 {
775         if (key->shortName == '?') {
776                 struct action_type *action;
777
778                 log_std("%s\n",PACKAGE_STRING);
779
780                 poptPrintHelp(popt_context, stdout, 0);
781
782                 log_std(_("\n"
783                          "<action> is one of:\n"));
784
785                 for(action = action_types; action->type; action++)
786                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
787                 
788                 log_std(_("\n"
789                          "<name> is the device to create under %s\n"
790                          "<device> is the encrypted device\n"
791                          "<key slot> is the LUKS key slot number to modify\n"
792                          "<key file> optional key file for the new key for luksAddKey action\n"),
793                         crypt_get_dir());
794
795                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
796                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
797                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
798                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
799                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
800                          DEFAULT_RNG);
801                 exit(0);
802         } else
803                 usage(popt_context, 0, NULL, NULL);
804 }
805
806 void set_debug_level(int level);
807
808 static void _dbg_version_and_cmd(int argc, char **argv)
809 {
810         int i;
811
812         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
813         for (i = 0; i < argc; i++) {
814                 if (i)
815                         log_std(" ");
816                 log_std(argv[i]);
817         }
818         log_std("\"\n");
819 }
820
821 static int run_action(struct action_type *action)
822 {
823         int r;
824
825         if (action->required_memlock)
826                 crypt_memory_lock(NULL, 1);
827
828         r = action->handler(action->arg);
829
830         if (action->required_memlock)
831                 crypt_memory_lock(NULL, 0);
832
833         show_status(r);
834
835         return r;
836 }
837
838 int main(int argc, char **argv)
839 {
840         static char *popt_tmp;
841         static struct poptOption popt_help_options[] = {
842                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
843                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
844                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
845                 POPT_TABLEEND
846         };
847         static struct poptOption popt_options[] = {
848                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
849                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
850                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
851                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
852                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
853                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
854                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
855                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
856                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
857                 { "keyfile-size",      'l',  POPT_ARG_INT, &opt_keyfile_size,           0, N_("Limits the read from keyfile"), N_("bytes") },
858                 { "new-keyfile-size", '\0',  POPT_ARG_INT, &opt_new_keyfile_size,       0, N_("Limits the read from newly added keyfile"), N_("bytes") },
859                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
860                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
861                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
862                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
863                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
864                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
865                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
866                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
867                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
868                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
869                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
870                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
871                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
872                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
873                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
874                 POPT_TABLEEND
875         };
876         poptContext popt_context;
877         struct action_type *action;
878         char *aname;
879         int r;
880         const char *null_action_argv[] = {NULL};
881
882         crypt_set_log_callback(NULL, _log, NULL);
883
884         setlocale(LC_ALL, "");
885         bindtextdomain(PACKAGE, LOCALEDIR);
886         textdomain(PACKAGE);
887
888         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
889                                       popt_options, 0);
890         poptSetOtherOptionHelp(popt_context,
891                                N_("[OPTION...] <action> <action-specific>]"));
892
893         while((r = poptGetNextOpt(popt_context)) > 0) {
894                 unsigned long long ull_value;
895                 char *endp;
896
897                 ull_value = strtoull(popt_tmp, &endp, 0);
898                 if (*endp || !*popt_tmp)
899                         r = POPT_ERROR_BADNUMBER;
900
901                 switch(r) {
902                         case 1:
903                                 opt_size = ull_value;
904                                 break;
905                         case 2:
906                                 opt_offset = ull_value;
907                                 break;
908                         case 3:
909                                 opt_skip = ull_value;
910                                 break;
911                 }
912
913                 if (r < 0)
914                         break;
915         }
916
917         if (r < -1)
918                 usage(popt_context, 1, poptStrerror(r),
919                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
920         if (opt_version_mode) {
921                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
922                 exit(0);
923         }
924
925         if (!(aname = (char *)poptGetArg(popt_context)))
926                 usage(popt_context, 1, _("Argument <action> missing."),
927                       poptGetInvocationName(popt_context));
928         for(action = action_types; action->type; action++)
929                 if (strcmp(action->type, aname) == 0)
930                         break;
931         if (!action->type)
932                 usage(popt_context, 1, _("Unknown action."),
933                       poptGetInvocationName(popt_context));
934
935         action_argc = 0;
936         action_argv = poptGetArgs(popt_context);
937         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
938         if(!action_argv)
939                 action_argv = null_action_argv;
940
941         /* Count args, somewhat unnice, change? */
942         while(action_argv[action_argc] != NULL)
943                 action_argc++;
944
945         if(action_argc < action->required_action_argc) {
946                 char buf[128];
947                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
948                 usage(popt_context, 1, buf,
949                       poptGetInvocationName(popt_context));
950         }
951
952         /* FIXME: rewrite this from scratch */
953
954         if (opt_key_size &&
955            strcmp(aname, "luksFormat") &&
956            strcmp(aname, "create")) {
957                 usage(popt_context, 1,
958                       _("Option --key-size is allowed only for luksFormat and create.\n"
959                         "To limit read from keyfile use --keyfile-size=(bytes)."),
960                       poptGetInvocationName(popt_context));
961         }
962
963         if (opt_key_size % 8)
964                 usage(popt_context, 1,
965                       _("Key size must be a multiple of 8 bits"),
966                       poptGetInvocationName(popt_context));
967
968         if (!strcmp(aname, "luksKillSlot"))
969                 opt_key_slot = atoi(action_argv[1]);
970         if (opt_key_slot != CRYPT_ANY_SLOT &&
971             (opt_key_slot < 0 || opt_key_slot > crypt_keyslot_max(CRYPT_LUKS1)))
972                 usage(popt_context, 1, _("Key slot is invalid."),
973                       poptGetInvocationName(popt_context));
974
975         if ((!strcmp(aname, "luksRemoveKey") ||
976              !strcmp(aname, "luksFormat")) &&
977              action_argc > 1) {
978                 if (opt_key_file)
979                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
980                 else
981                         opt_key_file = (char*)action_argv[1];
982         }
983
984         if (opt_random && opt_urandom)
985                 usage(popt_context, 1, _("Only one of --use-[u]random options is allowed."),
986                       poptGetInvocationName(popt_context));
987         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
988                 usage(popt_context, 1, _("Option --use-[u]random is allowed only for luksFormat."),
989                       poptGetInvocationName(popt_context));
990
991         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
992                 usage(popt_context, 1, _("Option --uuid is allowed only for luksFormat and luksUUID."),
993                       poptGetInvocationName(popt_context));
994
995         if ((opt_offset || opt_skip) && strcmp(aname, "create"))
996                 usage(popt_context, 1, _("Options --offset and --skip are supported only for create command.\n"),
997                       poptGetInvocationName(popt_context));
998
999         if (opt_debug) {
1000                 opt_verbose = 1;
1001                 crypt_set_debug_level(-1);
1002                 _dbg_version_and_cmd(argc, argv);
1003         }
1004
1005         return run_action(action);
1006 }