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