Fix luksFormat to properly use key file with --master-key-file switch.
[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_non_exclusive = 0;
43 static int opt_random = 0;
44 static int opt_urandom = 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_luksDelKey(int arg);
57 static int action_luksKillSlot(int arg);
58 static int action_luksRemoveKey(int arg);
59 static int action_isLuks(int arg);
60 static int action_luksUUID(int arg);
61 static int action_luksDump(int arg);
62 static int action_luksSuspend(int arg);
63 static int action_luksResume(int arg);
64 static int action_luksBackup(int arg);
65 static int action_luksRestore(int arg);
66
67 static struct action_type {
68         const char *type;
69         int (*handler)(int);
70         int arg;
71         int required_action_argc;
72         int required_memlock;
73         const char *arg_desc;
74         const char *desc;
75 } action_types[] = {
76         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
77         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
78         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
79         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
80         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
81         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
82         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
83         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
84         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
85         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
86         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
87         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
88         { "luksDump",   action_luksDump,        0, 1, 0, N_("<device>"), N_("dump LUKS partition information") },
89         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
90         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
91         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
92         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
93         { "luksDelKey", action_luksDelKey,      0, 2, 1, N_("<device> <key slot>"), N_("identical to luksKillSlot - DEPRECATED - see man page") },
94         { "reload",     action_create,          1, 2, 1, N_("<name> <device>"), N_("modify active device - DEPRECATED - see man page") },
95         { NULL, NULL, 0, 0, 0, NULL, NULL }
96 };
97
98 static void clogger(struct crypt_device *cd, int level, const char *file,
99                    int line, const char *format, ...)
100 {
101         va_list argp;
102         char *target = NULL;
103
104         va_start(argp, format);
105
106         if (vasprintf(&target, format, argp) > 0) {
107                 if (level >= 0) {
108                         crypt_log(cd, level, target);
109 #ifdef CRYPT_DEBUG
110                 } else if (opt_debug)
111                         printf("# %s:%d %s\n", file ?: "?", line, target);
112 #else
113                 } else if (opt_debug)
114                         printf("# %s\n", target);
115 #endif
116         }
117
118         va_end(argp);
119         free(target);
120 }
121
122 /* Interface Callbacks */
123 static int yesDialog(char *msg)
124 {
125         char *answer = NULL;
126         size_t size = 0;
127         int r = 1;
128
129         if(isatty(0) && !opt_batch_mode) {
130                 log_std("\nWARNING!\n========\n");
131                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
132                 if(getline(&answer, &size, stdin) == -1) {
133                         perror("getline");
134                         free(answer);
135                         return 0;
136                 }
137                 if(strcmp(answer, "YES\n"))
138                         r = 0;
139                 free(answer);
140         }
141
142         return r;
143 }
144
145 static void cmdLineLog(int level, char *msg) {
146         switch(level) {
147
148         case CRYPT_LOG_NORMAL:
149                 fputs(msg, stdout);
150                 break;
151         case CRYPT_LOG_VERBOSE:
152                 if (opt_verbose)
153                         fputs(msg, stdout);
154                 break;
155         case CRYPT_LOG_ERROR:
156                 fputs(msg, stderr);
157                 break;
158         default:
159                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
160                 break;
161         }
162 }
163
164 static struct interface_callbacks cmd_icb = {
165         .yesDialog = yesDialog,
166         .log = cmdLineLog,
167 };
168
169 static void _log(int level, const char *msg, void *usrptr)
170 {
171         cmdLineLog(level, (char *)msg);
172 }
173
174 static int _yesDialog(const char *msg, void *usrptr)
175 {
176         return yesDialog((char*)msg);
177 }
178
179 /* End ICBs */
180
181 static void show_status(int errcode)
182 {
183         char error[256], *error_;
184
185         if(!opt_verbose)
186                 return;
187
188         if(!errcode) {
189                 log_std(_("Command successful.\n"));
190                 return;
191         }
192
193         crypt_get_error(error, sizeof(error));
194
195         if (!error[0]) {
196                 error_ = strerror_r(-errcode, error, sizeof(error));
197                 if (error_ != error) {
198                         strncpy(error, error_, sizeof(error));
199                         error[sizeof(error) - 1] = '\0';
200                 }
201         }
202
203         log_err(_("Command failed with code %i"), -errcode);
204         if (*error)
205                 log_err(": %s\n", error);
206         else
207                 log_err(".\n");
208 }
209
210 static int action_create(int reload)
211 {
212         struct crypt_options options = {
213                 .name = action_argv[0],
214                 .device = action_argv[1],
215                 .cipher = opt_cipher ? opt_cipher : DEFAULT_CIPHER(PLAIN),
216                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
217                 .key_file = opt_key_file,
218                 .key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8,
219                 .key_slot = opt_key_slot,
220                 .flags = 0,
221                 .size = opt_size,
222                 .offset = opt_offset,
223                 .skip = opt_skip,
224                 .timeout = opt_timeout,
225                 .tries = opt_tries,
226                 .icb = &cmd_icb,
227         };
228         int r;
229
230         if(reload) 
231                 log_err(_("The reload action is deprecated. Please use \"dmsetup reload\" in case you really need this functionality.\nWARNING: do not use reload to touch LUKS devices. If that is the case, hit Ctrl-C now.\n"));
232
233         if (options.hash && strcmp(options.hash, "plain") == 0)
234                 options.hash = NULL;
235         if (opt_verify_passphrase)
236                 options.flags |= CRYPT_FLAG_VERIFY;
237         if (opt_readonly)
238                 options.flags |= CRYPT_FLAG_READONLY;
239
240         if (reload)
241                 r = crypt_update_device(&options);
242         else
243                 r = crypt_create_device(&options);
244
245         return r;
246 }
247
248 static int action_remove(int arg)
249 {
250         struct crypt_options options = {
251                 .name = action_argv[0],
252                 .icb = &cmd_icb,
253         };
254
255         return crypt_remove_device(&options);
256 }
257
258 static int action_resize(int arg)
259 {
260         struct crypt_options options = {
261                 .name = action_argv[0],
262                 .size = opt_size,
263                 .icb = &cmd_icb,
264         };
265
266         return crypt_resize_device(&options);
267 }
268
269 static int action_status(int arg)
270 {
271         struct crypt_options options = {
272                 .name = action_argv[0],
273                 .icb = &cmd_icb,
274         };
275         int r;
276
277         r = crypt_query_device(&options);
278         if (r < 0)
279                 return r;
280
281         if (r == 0) {
282                 /* inactive */
283                 log_std("%s/%s is inactive.\n", crypt_get_dir(), options.name);
284                 r = 1;
285         } else {
286                 /* active */
287                 log_std("%s/%s is active:\n", crypt_get_dir(), options.name);
288                 log_std("  cipher:  %s\n", options.cipher);
289                 log_std("  keysize: %d bits\n", options.key_size * 8);
290                 log_std("  device:  %s\n", options.device ?: "");
291                 log_std("  offset:  %" PRIu64 " sectors\n", options.offset);
292                 log_std("  size:    %" PRIu64 " sectors\n", options.size);
293                 if (options.skip)
294                         log_std("  skipped: %" PRIu64 " sectors\n", options.skip);
295                 log_std("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
296                                            ? "readonly" : "read/write");
297                 crypt_put_options(&options);
298                 r = 0;
299         }
300         return r;
301 }
302
303 static int _read_mk(const char *file, char **key, int keysize)
304 {
305         int fd;
306
307         *key = crypt_safe_alloc(keysize);
308         if (!*key)
309                 return -ENOMEM;
310
311         fd = open(file, O_RDONLY);
312         if (fd == -1) {
313                 log_err("Cannot read keyfile %s.\n", file);
314                 goto fail;
315         }
316         if ((read(fd, *key, keysize) != keysize)) {
317                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
318                 close(fd);
319                 goto fail;
320         }
321         close(fd);
322         return 0;
323 fail:
324         crypt_safe_free(*key);
325         *key = NULL;
326         return -EINVAL;
327 }
328
329 static int action_luksFormat(int arg)
330 {
331         int r = -EINVAL, keysize;
332         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
333         const char *key_file = NULL;
334         char *password = NULL;
335         unsigned int passwordLen;
336         struct crypt_device *cd = NULL;
337         struct crypt_params_luks1 params = {
338                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
339                 .data_alignment = opt_align_payload,
340         };
341
342         if (action_argc > 1) {
343                 key_file = action_argv[1];
344                 if (opt_key_file)
345                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
346         } else
347                 key_file = opt_key_file;
348
349         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
350                 log_err(_("memory allocation error in action_luksFormat"));
351                 r = -ENOMEM;
352                 goto out;
353         }
354         r = yesDialog(msg) ? 0 : -EINVAL;
355         free(msg);
356         if (r < 0)
357                 goto out;
358
359         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
360                                       cipher, cipher_mode);
361         if (r < 0) {
362                 log_err("No known cipher specification pattern detected.\n");
363                 goto out;
364         }
365
366         if ((r = crypt_init(&cd, action_argv[0])))
367                 goto out;
368
369         crypt_set_log_callback(cd, _log, NULL);
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, 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         crypt_set_log_callback(cd, _log, NULL);
425
426         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
427                 goto out;
428
429         crypt_set_timeout(cd, opt_timeout);
430         crypt_set_password_retry(cd, opt_tries);
431
432         if (opt_iteration_time)
433                 crypt_set_iterarion_time(cd, opt_iteration_time);
434         if (opt_readonly)
435                 flags |= CRYPT_ACTIVATE_READONLY;
436
437         if (opt_non_exclusive)
438                 log_err(_("Obsolete option --non-exclusive is ignored.\n"));
439
440         if (opt_key_file) {
441                 crypt_set_password_retry(cd, 1);
442                 r = crypt_activate_by_keyfile(cd, action_argv[1],
443                         CRYPT_ANY_SLOT, opt_key_file, opt_keyfile_size,
444                         flags);
445         } else
446                 r = crypt_activate_by_passphrase(cd, action_argv[1],
447                         CRYPT_ANY_SLOT, NULL, 0, flags);
448 out:
449         crypt_free(cd);
450         return (r < 0) ? r : 0;
451 }
452
453 /* FIXME: keyslot operation needs better get_key() implementation. Use old API for now */
454 static int action_luksDelKey(int arg)
455 {
456         log_err("luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
457         return action_luksKillSlot(arg);
458 }
459
460 static int action_luksKillSlot(int arg)
461 {
462         struct crypt_options options = {
463                 .device = action_argv[0],
464                 .key_slot = atoi(action_argv[1]),
465                 .key_file = opt_key_file,
466                 .timeout = opt_timeout,
467                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
468                 .icb = &cmd_icb,
469         };
470
471         return crypt_luksKillSlot(&options);
472 }
473
474 static int action_luksRemoveKey(int arg)
475 {
476         struct crypt_options options = {
477                 .device = action_argv[0],
478                 .new_key_file = action_argc>1?action_argv[1]:NULL,
479                 .key_file = opt_key_file,
480                 .timeout = opt_timeout,
481                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
482                 .icb = &cmd_icb,
483         };
484
485         return crypt_luksRemoveKey(&options);
486 }
487
488 static int action_luksAddKey(int arg)
489 {
490         int r = -EINVAL, keysize = 0;
491         char *key = NULL;
492         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
493         struct crypt_device *cd = NULL;
494
495         if ((r = crypt_init(&cd, action_argv[0])))
496                 goto out;
497
498         crypt_set_log_callback(cd, _log, NULL);
499         crypt_set_confirm_callback(cd, _yesDialog, NULL);
500
501         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
502                 goto out;
503
504         keysize = crypt_get_volume_key_size(cd);
505         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
506         crypt_set_timeout(cd, opt_timeout);
507         if (opt_iteration_time)
508                 crypt_set_iterarion_time(cd, opt_iteration_time);
509
510         if (opt_master_key_file) {
511                 if (_read_mk(opt_master_key_file, &key, keysize) < 0)
512                         goto out;
513
514                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
515                                                     key, keysize, NULL, 0);
516         } else if (opt_key_file || opt_new_key_file) {
517                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
518                                                  opt_key_file, opt_keyfile_size,
519                                                  opt_new_key_file, opt_new_keyfile_size);
520         } else {
521                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
522                                                     NULL, 0, NULL, 0);
523         }
524 out:
525         crypt_free(cd);
526         crypt_safe_free(key);
527
528         return (r < 0) ? r : 0;
529 }
530
531 static int action_isLuks(int arg)
532 {
533         struct crypt_options options = {
534                 .device = action_argv[0],
535                 .icb = &cmd_icb,
536         };
537
538         return crypt_isLuks(&options);
539 }
540
541 static int action_luksUUID(int arg)
542 {
543         struct crypt_device *cd = NULL;
544         const char *existing_uuid = NULL;
545         int r;
546
547         if ((r = crypt_init(&cd, action_argv[0])))
548                 goto out;
549
550         crypt_set_log_callback(cd, _log, NULL);
551         crypt_set_confirm_callback(cd, _yesDialog, NULL);
552
553         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
554                 goto out;
555
556         if (opt_uuid)
557                 r = crypt_set_uuid(cd, opt_uuid);
558         else {
559                 existing_uuid = crypt_get_uuid(cd);
560                 log_std("%s\n", existing_uuid ?: "");
561                 r = existing_uuid ? 0 : 1;
562         }
563 out:
564         crypt_free(cd);
565         return r;
566
567 }
568
569 static int action_luksDump(int arg)
570 {
571         struct crypt_options options = {
572                 .device = action_argv[0],
573                 .icb = &cmd_icb,
574         };
575
576         return crypt_luksDump(&options);
577 }
578
579 static int action_luksSuspend(int arg)
580 {
581         struct crypt_device *cd = NULL;
582         int r;
583
584         r = crypt_init_by_name(&cd, action_argv[0]);
585         if (!r)
586                 r = crypt_suspend(cd, action_argv[0]);
587
588         crypt_free(cd);
589         return r;
590 }
591
592 static int action_luksResume(int arg)
593 {
594         struct crypt_device *cd = NULL;
595         int r;
596
597         if ((r = crypt_init_by_name(&cd, action_argv[0])))
598                 goto out;
599
600         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
601                 goto out;
602
603         if (opt_key_file)
604                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
605                                             opt_key_file, opt_keyfile_size);
606         else
607                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
608                                                NULL, 0);
609 out:
610         crypt_free(cd);
611         return r;
612 }
613
614 static int action_luksBackup(int arg)
615 {
616         struct crypt_device *cd = NULL;
617         int r;
618
619         if (!opt_header_backup_file) {
620                 log_err(_("Option --header-backup-file is required.\n"));
621                 return -EINVAL;
622         }
623
624         if ((r = crypt_init(&cd, action_argv[0])))
625                 goto out;
626
627         crypt_set_log_callback(cd, _log, NULL);
628         crypt_set_confirm_callback(cd, _yesDialog, NULL);
629
630         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
631 out:
632         crypt_free(cd);
633         return r;
634 }
635
636 static int action_luksRestore(int arg)
637 {
638         struct crypt_device *cd = NULL;
639         int r = 0;
640
641         if (!opt_header_backup_file) {
642                 log_err(_("Option --header-backup-file is required.\n"));
643                 return -EINVAL;
644         }
645
646         if ((r = crypt_init(&cd, action_argv[0])))
647                 goto out;
648
649         crypt_set_log_callback(cd, _log, NULL);
650         crypt_set_confirm_callback(cd, _yesDialog, NULL);
651         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
652 out:
653         crypt_free(cd);
654         return r;
655 }
656
657 static void usage(poptContext popt_context, int exitcode,
658                   const char *error, const char *more)
659 {
660         poptPrintUsage(popt_context, stderr, 0);
661         if (error)
662                 log_err("%s: %s\n", more, error);
663         exit(exitcode);
664 }
665
666 static void help(poptContext popt_context, enum poptCallbackReason reason,
667                  struct poptOption *key, const char * arg, void *data)
668 {
669         if (key->shortName == '?') {
670                 struct action_type *action;
671
672                 log_std("%s\n",PACKAGE_STRING);
673
674                 poptPrintHelp(popt_context, stdout, 0);
675
676                 log_std(_("\n"
677                          "<action> is one of:\n"));
678
679                 for(action = action_types; action->type; action++)
680                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
681                 
682                 log_std(_("\n"
683                          "<name> is the device to create under %s\n"
684                          "<device> is the encrypted device\n"
685                          "<key slot> is the LUKS key slot number to modify\n"
686                          "<key file> optional key file for the new key for luksAddKey action\n"),
687                         crypt_get_dir());
688
689                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
690                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
691                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
692                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
693                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
694                          DEFAULT_RNG);
695                 exit(0);
696         } else
697                 usage(popt_context, 0, NULL, NULL);
698 }
699
700 void set_debug_level(int level);
701
702 static void _dbg_version_and_cmd(int argc, char **argv)
703 {
704         int i;
705
706         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
707         for (i = 0; i < argc; i++) {
708                 if (i)
709                         log_std(" ");
710                 log_std(argv[i]);
711         }
712         log_std("\"\n");
713 }
714
715 static int run_action(struct action_type *action)
716 {
717         int r;
718
719         if (action->required_memlock)
720                 crypt_memory_lock(NULL, 1);
721
722         r = action->handler(action->arg);
723
724         if (action->required_memlock)
725                 crypt_memory_lock(NULL, 0);
726
727         show_status(r);
728
729         return r;
730 }
731
732 int main(int argc, char **argv)
733 {
734         static char *popt_tmp;
735         static struct poptOption popt_help_options[] = {
736                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
737                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
738                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
739                 POPT_TABLEEND
740         };
741         static struct poptOption popt_options[] = {
742                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
743                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
744                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
745                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
746                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
747                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
748                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
749                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
750                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
751                 { "keyfile-size",      'l',  POPT_ARG_INT, &opt_keyfile_size,           0, N_("Limits the read from keyfile"), N_("bytes") },
752                 { "new-keyfile-size", '\0',  POPT_ARG_INT, &opt_new_keyfile_size,       0, N_("Limits the read from newly added keyfile"), N_("bytes") },
753                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
754                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
755                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
756                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
757                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
758                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
759                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
760                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
761                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
762                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
763                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
764                 { "non-exclusive",     '\0', POPT_ARG_NONE, &opt_non_exclusive,         0, N_("(Obsoleted, see man page.)"), NULL },
765                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
766                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
767                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
768                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
769                 POPT_TABLEEND
770         };
771         poptContext popt_context;
772         struct action_type *action;
773         char *aname;
774         int r;
775         const char *null_action_argv[] = {NULL};
776
777         crypt_set_log_callback(NULL, _log, NULL);
778
779         setlocale(LC_ALL, "");
780         bindtextdomain(PACKAGE, LOCALEDIR);
781         textdomain(PACKAGE);
782
783         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
784                                       popt_options, 0);
785         poptSetOtherOptionHelp(popt_context,
786                                N_("[OPTION...] <action> <action-specific>]"));
787
788         while((r = poptGetNextOpt(popt_context)) > 0) {
789                 unsigned long long ull_value;
790                 char *endp;
791
792                 ull_value = strtoull(popt_tmp, &endp, 0);
793                 if (*endp || !*popt_tmp)
794                         r = POPT_ERROR_BADNUMBER;
795
796                 switch(r) {
797                         case 1:
798                                 opt_size = ull_value;
799                                 break;
800                         case 2:
801                                 opt_offset = ull_value;
802                                 break;
803                         case 3:
804                                 opt_skip = ull_value;
805                                 break;
806                 }
807
808                 if (r < 0)
809                         break;
810         }
811
812         if (r < -1)
813                 usage(popt_context, 1, poptStrerror(r),
814                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
815         if (opt_version_mode) {
816                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
817                 exit(0);
818         }
819
820         if (!(aname = (char *)poptGetArg(popt_context)))
821                 usage(popt_context, 1, _("Argument <action> missing."),
822                       poptGetInvocationName(popt_context));
823         for(action = action_types; action->type; action++)
824                 if (strcmp(action->type, aname) == 0)
825                         break;
826         if (!action->type)
827                 usage(popt_context, 1, _("Unknown action."),
828                       poptGetInvocationName(popt_context));
829
830         if (opt_key_size &&
831            strcmp(aname, "luksFormat") &&
832            strcmp(aname, "create")) {
833                 usage(popt_context, 1,
834                       _("Option --key-size is allowed only for luksFormat and create.\n"
835                         "To limit read from keyfile use --keyfile-size=(bytes)."),
836                       poptGetInvocationName(popt_context));
837         }
838
839         if (opt_key_size % 8)
840                 usage(popt_context, 1,
841                       _("Key size must be a multiple of 8 bits"),
842                       poptGetInvocationName(popt_context));
843
844         /* FIXME: use per format define here */
845         if (opt_key_slot != CRYPT_ANY_SLOT &&
846            (opt_key_slot < 0 || opt_key_slot > 8)) {
847                 usage(popt_context, 1, _("Key slot is invalid."),
848                       poptGetInvocationName(popt_context));
849         }
850
851         if (opt_random && opt_urandom)
852                 usage(popt_context, 1, _("Only one of --use-[u]random options is allowed."),
853                       poptGetInvocationName(popt_context));
854         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
855                 usage(popt_context, 1, _("Option --use-[u]random is allowed only for luksFormat."),
856                       poptGetInvocationName(popt_context));
857
858         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
859                 usage(popt_context, 1, _("Option --uuid is allowed only for luksFormat and luksUUID."),
860                       poptGetInvocationName(popt_context));
861
862         if ((opt_offset || opt_skip) && strcmp(aname, "create"))
863                 usage(popt_context, 1, _("Options --offset and --skip are supported only for create command.\n"),
864                       poptGetInvocationName(popt_context));
865
866         action_argc = 0;
867         action_argv = poptGetArgs(popt_context);
868         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
869         if(!action_argv) 
870                 action_argv = null_action_argv;
871
872         /* Count args, somewhat unnice, change? */
873         while(action_argv[action_argc] != NULL)
874                 action_argc++;
875
876         if(action_argc < action->required_action_argc) {
877                 char buf[128];
878                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
879                 usage(popt_context, 1, buf,
880                       poptGetInvocationName(popt_context));
881         }
882
883         if (opt_debug) {
884                 opt_verbose = 1;
885                 crypt_set_debug_level(-1);
886                 _dbg_version_and_cmd(argc, argv);
887         }
888
889         return run_action(action);
890 }