839ead0578aa15e05a0ca485f358871a787fcbbc
[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                 return -EINVAL;
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                 crypt_safe_free(*key);
320                 return -EINVAL;
321         }
322         close(fd);
323         return 0;
324 }
325
326 static int action_luksFormat(int arg)
327 {
328         int r = -EINVAL, keysize;
329         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
330         const char *key_file = NULL;
331         char *password = NULL;
332         unsigned int passwordLen;
333         struct crypt_device *cd = NULL;
334         struct crypt_params_luks1 params = {
335                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
336                 .data_alignment = opt_align_payload,
337         };
338
339         /* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
340         if (opt_offset || opt_skip) {
341                 log_err("Options --offset and --skip are not supported for luksFormat.\n");
342                 r = -EINVAL;
343                 goto out;;
344         }
345
346         if (action_argc > 1) {
347                 key_file = action_argv[1];
348                 if (opt_key_file)
349                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
350         } else
351                 key_file = opt_key_file;
352
353         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
354                 log_err(_("memory allocation error in action_luksFormat"));
355                 r = -ENOMEM;
356                 goto out;
357         }
358         r = yesDialog(msg);
359         free(msg);
360
361         if (!r) {
362                 r = -EINVAL;
363                 goto out;
364         }
365
366         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
367                                       cipher, cipher_mode);
368         if (r < 0) {
369                 log_err("No known cipher specification pattern detected.\n");
370                 goto out;
371         }
372
373         if ((r = crypt_init(&cd, action_argv[0])))
374                 goto out;
375
376         crypt_set_log_callback(cd, _log, NULL);
377
378         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
379
380         crypt_set_password_verify(cd, 1);
381         crypt_set_timeout(cd, opt_timeout);
382         if (opt_iteration_time)
383                 crypt_set_iterarion_time(cd, opt_iteration_time);
384
385         if (opt_random)
386                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
387         else if (opt_urandom)
388                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
389
390         if (opt_master_key_file) {
391                 r = _read_mk(opt_master_key_file, &key, keysize);
392                 if (r < 0)
393                         goto out;
394
395                 r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
396                                  opt_uuid, key, keysize, &params);
397                 if (r < 0)
398                         goto out;
399
400                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
401                                                     key, keysize, NULL, 0);
402         } else {
403                 crypt_get_key(_("Enter LUKS passphrase: "),
404                               &password, &passwordLen,
405                               opt_keyfile_size, key_file,
406                               opt_timeout,
407                               opt_batch_mode ? 0 : 1, /* always verify */
408                               cd);
409
410                 if(!password) {
411                         r = -EINVAL;
412                         goto out;
413                 }
414
415                 r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
416                                  opt_uuid, NULL, keysize, &params);
417                 if (r < 0)
418                         goto out;
419
420                 /* Add keyslot using internally stored volume key generated during format */
421                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
422                                                     NULL, 0, password, passwordLen);
423         }
424 out:
425         crypt_free(cd);
426         crypt_safe_free(key);
427         crypt_safe_free(password);
428
429         return (r < 0) ? r : 0;
430 }
431
432 static int action_luksOpen(int arg)
433 {
434         struct crypt_device *cd = NULL;
435         uint32_t flags = 0;
436         int r;
437
438         if ((r = crypt_init(&cd, action_argv[0])))
439                 goto out;
440
441         crypt_set_log_callback(cd, _log, NULL);
442
443         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
444                 goto out;
445
446         crypt_set_timeout(cd, opt_timeout);
447         crypt_set_password_retry(cd, opt_tries);
448
449         if (opt_iteration_time)
450                 crypt_set_iterarion_time(cd, opt_iteration_time);
451         if (opt_readonly)
452                 flags |= CRYPT_ACTIVATE_READONLY;
453
454         if (opt_non_exclusive)
455                 log_err(_("Obsolete option --non-exclusive is ignored.\n"));
456
457         if (opt_key_file) {
458                 crypt_set_password_retry(cd, 1);
459                 r = crypt_activate_by_keyfile(cd, action_argv[1],
460                         CRYPT_ANY_SLOT, opt_key_file, opt_keyfile_size,
461                         flags);
462         } else
463                 r = crypt_activate_by_passphrase(cd, action_argv[1],
464                         CRYPT_ANY_SLOT, NULL, 0, flags);
465 out:
466         crypt_free(cd);
467         return (r < 0) ? r : 0;
468 }
469
470 /* FIXME: keyslot operation needs better get_key() implementation. Use old API for now */
471 static int action_luksDelKey(int arg)
472 {
473         log_err("luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
474         return action_luksKillSlot(arg);
475 }
476
477 static int action_luksKillSlot(int arg)
478 {
479         struct crypt_options options = {
480                 .device = action_argv[0],
481                 .key_slot = atoi(action_argv[1]),
482                 .key_file = opt_key_file,
483                 .timeout = opt_timeout,
484                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
485                 .icb = &cmd_icb,
486         };
487
488         return crypt_luksKillSlot(&options);
489 }
490
491 static int action_luksRemoveKey(int arg)
492 {
493         struct crypt_options options = {
494                 .device = action_argv[0],
495                 .new_key_file = action_argc>1?action_argv[1]:NULL,
496                 .key_file = opt_key_file,
497                 .timeout = opt_timeout,
498                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
499                 .icb = &cmd_icb,
500         };
501
502         return crypt_luksRemoveKey(&options);
503 }
504
505 static int action_luksAddKey(int arg)
506 {
507         int r = -EINVAL, keysize = 0;
508         char *key = NULL;
509         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
510         struct crypt_device *cd = NULL;
511
512         if ((r = crypt_init(&cd, action_argv[0])))
513                 goto out;
514
515         crypt_set_log_callback(cd, _log, NULL);
516         crypt_set_confirm_callback(cd, _yesDialog, NULL);
517
518         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
519                 goto out;
520
521         keysize = crypt_get_volume_key_size(cd);
522         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
523         crypt_set_timeout(cd, opt_timeout);
524         if (opt_iteration_time)
525                 crypt_set_iterarion_time(cd, opt_iteration_time);
526
527         if (opt_master_key_file) {
528                 if (_read_mk(opt_master_key_file, &key, keysize) < 0)
529                         goto out;
530
531                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
532                                                     key, keysize, NULL, 0);
533         } else if (opt_key_file || opt_new_key_file) {
534                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
535                                                  opt_key_file, opt_keyfile_size,
536                                                  opt_new_key_file, opt_new_keyfile_size);
537         } else {
538                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
539                                                     NULL, 0, NULL, 0);
540         }
541 out:
542         crypt_free(cd);
543         crypt_safe_free(key);
544
545         return (r < 0) ? r : 0;
546 }
547
548 static int action_isLuks(int arg)
549 {
550         struct crypt_options options = {
551                 .device = action_argv[0],
552                 .icb = &cmd_icb,
553         };
554
555         return crypt_isLuks(&options);
556 }
557
558 static int action_luksUUID(int arg)
559 {
560         struct crypt_device *cd = NULL;
561         const char *existing_uuid = NULL;
562         int r;
563
564         if ((r = crypt_init(&cd, action_argv[0])))
565                 goto out;
566
567         crypt_set_log_callback(cd, _log, NULL);
568         crypt_set_confirm_callback(cd, _yesDialog, NULL);
569
570         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
571                 goto out;
572
573         if (opt_uuid)
574                 r = crypt_set_uuid(cd, opt_uuid);
575         else {
576                 existing_uuid = crypt_get_uuid(cd);
577                 log_std("%s\n", existing_uuid ?: "");
578                 r = existing_uuid ? 0 : 1;
579         }
580 out:
581         crypt_free(cd);
582         return r;
583
584 }
585
586 static int action_luksDump(int arg)
587 {
588         struct crypt_options options = {
589                 .device = action_argv[0],
590                 .icb = &cmd_icb,
591         };
592
593         return crypt_luksDump(&options);
594 }
595
596 static int action_luksSuspend(int arg)
597 {
598         struct crypt_device *cd = NULL;
599         int r;
600
601         r = crypt_init_by_name(&cd, action_argv[0]);
602         if (!r)
603                 r = crypt_suspend(cd, action_argv[0]);
604
605         crypt_free(cd);
606         return r;
607 }
608
609 static int action_luksResume(int arg)
610 {
611         struct crypt_device *cd = NULL;
612         int r;
613
614         if ((r = crypt_init_by_name(&cd, action_argv[0])))
615                 goto out;
616
617         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
618                 goto out;
619
620         if (opt_key_file)
621                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
622                                             opt_key_file, opt_keyfile_size);
623         else
624                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
625                                                NULL, 0);
626 out:
627         crypt_free(cd);
628         return r;
629 }
630
631 static int action_luksBackup(int arg)
632 {
633         struct crypt_device *cd = NULL;
634         int r;
635
636         if (!opt_header_backup_file) {
637                 log_err(_("Option --header-backup-file is required.\n"));
638                 return -EINVAL;
639         }
640
641         if ((r = crypt_init(&cd, action_argv[0])))
642                 goto out;
643
644         crypt_set_log_callback(cd, _log, NULL);
645         crypt_set_confirm_callback(cd, _yesDialog, NULL);
646
647         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
648 out:
649         crypt_free(cd);
650         return r;
651 }
652
653 static int action_luksRestore(int arg)
654 {
655         struct crypt_device *cd = NULL;
656         int r = 0;
657
658         if (!opt_header_backup_file) {
659                 log_err(_("Option --header-backup-file is required.\n"));
660                 return -EINVAL;
661         }
662
663         if ((r = crypt_init(&cd, action_argv[0])))
664                 goto out;
665
666         crypt_set_log_callback(cd, _log, NULL);
667         crypt_set_confirm_callback(cd, _yesDialog, NULL);
668         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
669 out:
670         crypt_free(cd);
671         return r;
672 }
673
674 static void usage(poptContext popt_context, int exitcode,
675                   const char *error, const char *more)
676 {
677         poptPrintUsage(popt_context, stderr, 0);
678         if (error)
679                 log_err("%s: %s\n", more, error);
680         exit(exitcode);
681 }
682
683 static void help(poptContext popt_context, enum poptCallbackReason reason,
684                  struct poptOption *key, const char * arg, void *data)
685 {
686         if (key->shortName == '?') {
687                 struct action_type *action;
688
689                 log_std("%s\n",PACKAGE_STRING);
690
691                 poptPrintHelp(popt_context, stdout, 0);
692
693                 log_std(_("\n"
694                          "<action> is one of:\n"));
695
696                 for(action = action_types; action->type; action++)
697                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
698                 
699                 log_std(_("\n"
700                          "<name> is the device to create under %s\n"
701                          "<device> is the encrypted device\n"
702                          "<key slot> is the LUKS key slot number to modify\n"
703                          "<key file> optional key file for the new key for luksAddKey action\n"),
704                         crypt_get_dir());
705
706                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
707                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
708                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
709                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
710                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
711                          DEFAULT_RNG);
712                 exit(0);
713         } else
714                 usage(popt_context, 0, NULL, NULL);
715 }
716
717 void set_debug_level(int level);
718
719 static void _dbg_version_and_cmd(int argc, char **argv)
720 {
721         int i;
722
723         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
724         for (i = 0; i < argc; i++) {
725                 if (i)
726                         log_std(" ");
727                 log_std(argv[i]);
728         }
729         log_std("\"\n");
730 }
731
732 static int run_action(struct action_type *action)
733 {
734         int r;
735
736         if (action->required_memlock)
737                 crypt_memory_lock(NULL, 1);
738
739         r = action->handler(action->arg);
740
741         if (action->required_memlock)
742                 crypt_memory_lock(NULL, 0);
743
744         show_status(r);
745
746         return r;
747 }
748
749 int main(int argc, char **argv)
750 {
751         static char *popt_tmp;
752         static struct poptOption popt_help_options[] = {
753                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
754                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
755                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
756                 POPT_TABLEEND
757         };
758         static struct poptOption popt_options[] = {
759                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
760                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
761                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
762                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
763                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
764                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
765                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
766                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
767                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
768                 { "keyfile-size",      'l',  POPT_ARG_INT, &opt_keyfile_size,           0, N_("Limits the read from keyfile"), N_("bytes") },
769                 { "new-keyfile-size", '\0',  POPT_ARG_INT, &opt_new_keyfile_size,       0, N_("Limits the read from newly added keyfile"), N_("bytes") },
770                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
771                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
772                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
773                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
774                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
775                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
776                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
777                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
778                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
779                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
780                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
781                 { "non-exclusive",     '\0', POPT_ARG_NONE, &opt_non_exclusive,         0, N_("(Obsoleted, see man page.)"), NULL },
782                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
783                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
784                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
785                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
786                 POPT_TABLEEND
787         };
788         poptContext popt_context;
789         struct action_type *action;
790         char *aname;
791         int r;
792         const char *null_action_argv[] = {NULL};
793
794         crypt_set_log_callback(NULL, _log, NULL);
795
796         setlocale(LC_ALL, "");
797         bindtextdomain(PACKAGE, LOCALEDIR);
798         textdomain(PACKAGE);
799
800         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
801                                       popt_options, 0);
802         poptSetOtherOptionHelp(popt_context,
803                                N_("[OPTION...] <action> <action-specific>]"));
804
805         while((r = poptGetNextOpt(popt_context)) > 0) {
806                 unsigned long long ull_value;
807                 char *endp;
808
809                 ull_value = strtoull(popt_tmp, &endp, 0);
810                 if (*endp || !*popt_tmp)
811                         r = POPT_ERROR_BADNUMBER;
812
813                 switch(r) {
814                         case 1:
815                                 opt_size = ull_value;
816                                 break;
817                         case 2:
818                                 opt_offset = ull_value;
819                                 break;
820                         case 3:
821                                 opt_skip = ull_value;
822                                 break;
823                 }
824
825                 if (r < 0)
826                         break;
827         }
828
829         if (r < -1)
830                 usage(popt_context, 1, poptStrerror(r),
831                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
832         if (opt_version_mode) {
833                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
834                 exit(0);
835         }
836
837         if (!(aname = (char *)poptGetArg(popt_context)))
838                 usage(popt_context, 1, _("Argument <action> missing."),
839                       poptGetInvocationName(popt_context));
840         for(action = action_types; action->type; action++)
841                 if (strcmp(action->type, aname) == 0)
842                         break;
843         if (!action->type)
844                 usage(popt_context, 1, _("Unknown action."),
845                       poptGetInvocationName(popt_context));
846
847         if (opt_key_size &&
848            strcmp(aname, "luksFormat") &&
849            strcmp(aname, "create")) {
850                 usage(popt_context, 1,
851                       _("Option --key-size is allowed only for luksFormat and create.\n"
852                         "To limit read from keyfile use --keyfile-size=(bytes)."),
853                       poptGetInvocationName(popt_context));
854         }
855
856         if (opt_key_size % 8)
857                 usage(popt_context, 1,
858                       _("Key size must be a multiple of 8 bits"),
859                       poptGetInvocationName(popt_context));
860
861         /* FIXME: use per format define here */
862         if (opt_key_slot != CRYPT_ANY_SLOT &&
863            (opt_key_slot < 0 || opt_key_slot > 8)) {
864                 usage(popt_context, 1, _("Key slot is invalid."),
865                       poptGetInvocationName(popt_context));
866         }
867
868         if (opt_random && opt_urandom)
869                 usage(popt_context, 1, _("Only one of --use-[u]random options is allowed."),
870                       poptGetInvocationName(popt_context));
871         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
872                 usage(popt_context, 1, _("Option --use-[u]random is allowed only for luksFormat."),
873                       poptGetInvocationName(popt_context));
874
875         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
876                 usage(popt_context, 1, _("Option --uuid is allowed only for luksFormat and luksUUID."),
877                       poptGetInvocationName(popt_context));
878
879         action_argc = 0;
880         action_argv = poptGetArgs(popt_context);
881         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
882         if(!action_argv) 
883                 action_argv = null_action_argv;
884
885         /* Count args, somewhat unnice, change? */
886         while(action_argv[action_argc] != NULL)
887                 action_argc++;
888
889         if(action_argc < action->required_action_argc) {
890                 char buf[128];
891                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
892                 usage(popt_context, 1, buf,
893                       poptGetInvocationName(popt_context));
894         }
895
896         if (opt_debug) {
897                 opt_verbose = 1;
898                 crypt_set_debug_level(-1);
899                 _dbg_version_and_cmd(argc, argv);
900         }
901
902         return run_action(action);
903 }