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