* Add log macros and make logging modre consitent.
[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 <inttypes.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <assert.h>
10
11 #include <libcryptsetup.h>
12 #include <popt.h>
13
14 #include "../config.h"
15
16 #include "cryptsetup.h"
17
18 static int opt_verbose = 0;
19 static int opt_debug = 0;
20 static char *opt_cipher = NULL;
21 static char *opt_hash = NULL;
22 static int opt_verify_passphrase = 0;
23 static char *opt_key_file = NULL;
24 static unsigned int opt_key_size = 0;
25 static int opt_key_slot = -1;
26 static uint64_t opt_size = 0;
27 static uint64_t opt_offset = 0;
28 static uint64_t opt_skip = 0;
29 static int opt_readonly = 0;
30 static int opt_iteration_time = 1000;
31 static int opt_batch_mode = 0;
32 static int opt_version_mode = 0;
33 static int opt_timeout = 0;
34 static int opt_tries = 3;
35 static int opt_align_payload = 0;
36 static int opt_non_exclusive = 0;
37
38 static const char **action_argv;
39 static int action_argc;
40
41 static int action_create(int arg);
42 static int action_remove(int arg);
43 static int action_resize(int arg);
44 static int action_status(int arg);
45 static int action_luksFormat(int arg);
46 static int action_luksOpen(int arg);
47 static int action_luksAddKey(int arg);
48 static int action_luksDelKey(int arg);
49 static int action_luksKillSlot(int arg);
50 static int action_luksRemoveKey(int arg);
51 static int action_isLuks(int arg);
52 static int action_luksUUID(int arg);
53 static int action_luksDump(int arg);
54
55 static struct action_type {
56         const char *type;
57         int (*handler)(int);
58         int arg;
59         int required_action_argc;
60         int required_dm_backend;
61         int required_memlock;
62         int show_status;
63         const char *arg_desc;
64         const char *desc;
65 } action_types[] = {
66         { "create",     action_create,          0, 2, 1, 1, 1, N_("<name> <device>"),N_("create device") },
67         { "remove",     action_remove,          0, 1, 1, 0, 1, N_("<name>"), N_("remove device") },
68         { "resize",     action_resize,          0, 1, 1, 1, 1, N_("<name>"), N_("resize active device") },
69         { "status",     action_status,          0, 1, 1, 0, 1, N_("<name>"), N_("show device status") },
70         { "luksFormat", action_luksFormat,      0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
71         { "luksOpen",   action_luksOpen,        0, 2, 1, 1, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
72         { "luksAddKey", action_luksAddKey,      0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
73         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
74         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
75         { "luksUUID",   action_luksUUID,        0, 1, 0, 0, 1, N_("<device>"), N_("print UUID of LUKS device") },
76         { "isLuks",     action_isLuks,          0, 1, 0, 0, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
77         { "luksClose",  action_remove,          0, 1, 1, 0, 1, N_("<name>"), N_("remove LUKS mapping") },
78         { "luksDump",   action_luksDump,        0, 1, 0, 0, 1, N_("<device>"), N_("dump LUKS partition information") },
79         { "luksDelKey", action_luksDelKey,      0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("identical to luksKillSlot - DEPRECATED - see man page") },
80         { "reload",     action_create,          1, 2, 1, 1, 1, N_("<name> <device>"), N_("modify active device - DEPRECATED - see man page") },
81         { NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL }
82 };
83
84 /* Interface Callbacks */
85 static int yesDialog(char *msg)
86 {
87         char *answer = NULL;
88         size_t size = 0;
89         int r = 1;
90
91         if(isatty(0) && !opt_batch_mode) {
92                 log_std("\nWARNING!\n========\n");
93                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
94                 if(getline(&answer, &size, stdin) == -1) {
95                         perror("getline");
96                         free(answer);
97                         return 0;
98                 }
99                 if(strcmp(answer, "YES\n"))
100                         r = 0;
101                 free(answer);
102         }
103
104         return r;
105 }
106
107 static void cmdLineLog(int class, char *msg) {
108     switch(class) {
109
110     case CRYPT_LOG_NORMAL:
111             fputs(msg, stdout);
112             break;
113     case CRYPT_LOG_ERROR:
114             fputs(msg, stderr);
115             break;
116     default:
117             fprintf(stderr, "Internal error on logging class for msg: %s", msg);
118             break;
119     }
120 }
121
122 static struct interface_callbacks cmd_icb = {
123         .yesDialog = yesDialog,
124         .log = cmdLineLog,
125 };
126
127 /* End ICBs */
128
129 static void show_status(int errcode)
130 {
131         char error[256];
132
133         if(!errcode && opt_verbose) {
134                 log_std(_("Command successful.\n"));
135                 return;
136         }
137
138         crypt_get_error(error, sizeof(error));
139
140         if (!opt_verbose) {
141                 char *error_ = strerror_r(errcode, error, sizeof(error));
142                 if (error_ != error) {
143                         strncpy(error, error_, sizeof(error));
144                         error[sizeof error - 1] = '\0';
145                 }
146         }
147
148         log_err(_("Command failed"));
149         if (*error)
150                 log_err(": %s\n", error);
151         else
152                 log_err(".\n");
153         return;
154 }
155
156 static int action_create(int reload)
157 {
158         struct crypt_options options = {
159                 .name = action_argv[0],
160                 .device = action_argv[1],
161                 .cipher = opt_cipher?opt_cipher:DEFAULT_CIPHER,
162                 .hash = opt_hash ?: DEFAULT_HASH,
163                 .key_file = opt_key_file,
164                 .key_size = ((opt_key_size)?opt_key_size:DEFAULT_KEY_SIZE)/8,
165                 .key_slot = opt_key_slot,
166                 .passphrase_fd = 0,     /* stdin */
167                 .flags = 0,
168                 .size = opt_size,
169                 .offset = opt_offset,
170                 .skip = opt_skip,
171                 .timeout = opt_timeout,
172                 .tries = opt_tries,
173                 .icb = &cmd_icb,
174         };
175         int r;
176
177         if(reload) 
178                 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"));
179
180         if (options.hash && strcmp(options.hash, "plain") == 0)
181                 options.hash = NULL;
182         if (opt_verify_passphrase)
183                 options.flags |= CRYPT_FLAG_VERIFY;
184         if (opt_readonly)
185                 options.flags |= CRYPT_FLAG_READONLY;
186
187         if (reload)
188                 r = crypt_update_device(&options);
189         else
190                 r = crypt_create_device(&options);
191
192         return r;
193 }
194
195 static int action_remove(int arg)
196 {
197         struct crypt_options options = {
198                 .name = action_argv[0],
199                 .icb = &cmd_icb,
200         };
201
202         return crypt_remove_device(&options);
203 }
204
205 static int action_resize(int arg)
206 {
207         struct crypt_options options = {
208                 .name = action_argv[0],
209                 .size = opt_size,
210                 .icb = &cmd_icb,
211         };
212
213         return crypt_resize_device(&options);
214 }
215
216 static int action_status(int arg)
217 {
218         struct crypt_options options = {
219                 .name = action_argv[0],
220                 .icb = &cmd_icb,
221         };
222         int r;
223
224         r = crypt_query_device(&options);
225         if (r < 0)
226                 return r;
227
228         if (r == 0) {
229                 /* inactive */
230                 log_std("%s/%s is inactive.\n", crypt_get_dir(), options.name);
231                 r = 1;
232         } else {
233                 /* active */
234                 log_std("%s/%s is active:\n", crypt_get_dir(), options.name);
235                 log_std("  cipher:  %s\n", options.cipher);
236                 log_std("  keysize: %d bits\n", options.key_size * 8);
237                 log_std("  device:  %s\n", options.device);
238                 log_std("  offset:  %" PRIu64 " sectors\n", options.offset);
239                 log_std("  size:    %" PRIu64 " sectors\n", options.size);
240                 if (options.skip)
241                         log_std("  skipped: %" PRIu64 " sectors\n", options.skip);
242                 log_std("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
243                                            ? "readonly" : "read/write");
244                 crypt_put_options(&options);
245                 r = 0;
246         }
247         return r;
248 }
249
250 static int action_luksFormat(int arg)
251 {
252         struct crypt_options options = {
253                 .key_size = (opt_key_size ?: DEFAULT_LUKS_KEY_SIZE) / 8,
254                 .key_slot = opt_key_slot,
255                 .device = action_argv[0],
256                 .cipher = opt_cipher ?: DEFAULT_LUKS_CIPHER,
257                 .hash = opt_hash ?: DEFAULT_LUKS_HASH,
258                 .new_key_file = action_argc > 1 ? action_argv[1] : NULL,
259                 .flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE :  0),
260                 .iteration_time = opt_iteration_time,
261                 .timeout = opt_timeout,
262                 .align_payload = opt_align_payload,
263                 .icb = &cmd_icb,
264         };
265         int r = 0; char *msg = NULL;
266
267         /* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
268         if (opt_offset || opt_skip) {
269                 fprintf(stderr,"Options --offset and --skip are not supported for luksFormat.\n"); 
270                 return -EINVAL;
271         }
272
273         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), options.device) == -1) {
274                 fputs(_("memory allocation error in action_luksFormat"), stderr);
275                 return -ENOMEM;
276         }
277         r = yesDialog(msg);
278         free(msg);
279
280         if (!r)
281                 return -EINVAL;
282
283         return crypt_luksFormat(&options);
284 }
285
286 static int action_luksOpen(int arg)
287 {
288         struct crypt_options options = {
289                 .name = action_argv[1],
290                 .device = action_argv[0],
291                 .key_file = opt_key_file,
292                 .key_size = opt_key_file ? (opt_key_size / 8) : 0, /* limit bytes read from keyfile */
293                 .timeout = opt_timeout,
294                 .tries = opt_key_file ? 1 : opt_tries, /* verify is usefull only for tty */
295                 .icb = &cmd_icb,
296         };
297
298         if (opt_readonly)
299                 options.flags |= CRYPT_FLAG_READONLY;
300         if (opt_non_exclusive)
301                 options.flags |= CRYPT_FLAG_NON_EXCLUSIVE_ACCESS;
302         return crypt_luksOpen(&options);
303 }
304
305 static int action_luksDelKey(int arg)
306 {
307     fprintf(stderr,"luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
308     return action_luksKillSlot(arg);
309 }
310
311 static int action_luksKillSlot(int arg)
312 {
313         struct crypt_options options = {
314                 .device = action_argv[0],
315                 .key_slot = atoi(action_argv[1]),
316                 .key_file = opt_key_file,
317                 .timeout = opt_timeout,
318                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
319                 .icb = &cmd_icb,
320         };
321
322         return crypt_luksKillSlot(&options);
323 }
324
325 static int action_luksRemoveKey(int arg)
326 {
327         struct crypt_options options = {
328                 .device = action_argv[0],
329                 .new_key_file = action_argc>1?action_argv[1]:NULL,
330                 .key_file = opt_key_file,
331                 .timeout = opt_timeout,
332                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
333                 .icb = &cmd_icb,
334         };
335
336         return crypt_luksRemoveKey(&options);
337 }
338
339 static int action_luksAddKey(int arg)
340 {
341         struct crypt_options options = {
342                 .device = action_argv[0],
343                 .new_key_file = action_argc>1?action_argv[1]:NULL,
344                 .key_file = opt_key_file,
345                 .key_slot = opt_key_slot,
346                 .flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE : 0),
347                 .iteration_time = opt_iteration_time,
348                 .timeout = opt_timeout,
349                 .icb = &cmd_icb,
350         };
351
352         return crypt_luksAddKey(&options);
353 }
354
355 static int action_isLuks(int arg)
356 {
357         struct crypt_options options = {
358                 .device = action_argv[0],
359                 .icb = &cmd_icb,
360         };
361
362         return crypt_isLuks(&options);
363 }
364
365 static int action_luksUUID(int arg)
366 {
367         struct crypt_options options = {
368                 .device = action_argv[0],
369                 .icb = &cmd_icb,
370         };
371
372         return crypt_luksUUID(&options);
373 }
374
375 static int action_luksDump(int arg)
376 {
377         struct crypt_options options = {
378                 .device = action_argv[0],
379                 .icb = &cmd_icb,
380         };
381
382         return crypt_luksDump(&options);
383 }
384
385 static void usage(poptContext popt_context, int exitcode,
386                   const char *error, const char *more)
387 {
388         poptPrintUsage(popt_context, stderr, 0);
389         if (error)
390                 log_err("%s: %s\n", more, error);
391         exit(exitcode);
392 }
393
394 static void help(poptContext popt_context, enum poptCallbackReason reason,
395                  struct poptOption *key, const char * arg, void *data)
396 {
397         if (key->shortName == '?') {
398                 struct action_type *action;
399
400                 log_std("%s\n",PACKAGE_STRING);
401
402                 poptPrintHelp(popt_context, stdout, 0);
403
404                 log_std(_("\n"
405                          "<action> is one of:\n"));
406
407                 for(action = action_types; action->type; action++)
408                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
409
410                 log_std(_("\n"
411                          "<name> is the device to create under %s\n"
412                          "<device> is the encrypted device\n"
413                          "<key slot> is the LUKS key slot number to modify\n"
414                          "<key file> optional key file for the new key for luksAddKey action\n"),
415                         crypt_get_dir());
416                 exit(0);
417         } else
418                 usage(popt_context, 0, NULL, NULL);
419 }
420
421 void set_debug_level(int level);
422
423 static void _dbg_version_and_cmd(int argc, char **argv)
424 {
425         int i;
426
427         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
428         for (i = 0; i < argc; i++) {
429                 if (i)
430                         log_std(" ");
431                 log_std(argv[i]);
432         }
433         log_std("\"\n");
434 }
435
436 static int run_action(struct action_type *action)
437 {
438         int r;
439
440         if (dm_init(NULL, action->required_dm_backend) < 1) {
441                 log_err("Cannot communicate with device-mapper. Is dm_mod kernel module loaded?\n");
442                 return -ENOSYS;
443         }
444
445         if (action->required_memlock)
446                 memlock_inc(NULL);
447
448         r = action->handler(action->arg);
449
450         if (action->required_memlock)
451                 memlock_dec(NULL);
452
453         if (action->required_dm_backend)
454                 dm_exit();
455
456         if (r < 0 && (opt_verbose || action->show_status))
457                 show_status(-r);
458
459         return r;
460 }
461
462 int main(int argc, char **argv)
463 {
464         static char *popt_tmp;
465         static struct poptOption popt_help_options[] = {
466                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
467                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
468                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
469                 POPT_TABLEEND
470         };
471         static struct poptOption popt_options[] = {
472                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE,                      popt_help_options,      0, N_("Help options:"),                                                   NULL },
473                 { "verbose",           'v',  POPT_ARG_NONE,                               &opt_verbose,           0, N_("Shows more detailed error messages"),                              NULL },
474                 { "debug",             '\0', POPT_ARG_NONE,                               &opt_debug,             0, N_("Show debug messsgages"),                                           NULL },
475                 { "cipher",            'c',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_cipher,            0, N_("The cipher used to encrypt the disk (see /proc/crypto)"),          NULL },
476                 { "hash",              'h',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_hash,              0, N_("The hash used to create the encryption key from the passphrase"),  NULL },
477                 { "verify-passphrase", 'y',  POPT_ARG_NONE,                               &opt_verify_passphrase, 0, N_("Verifies the passphrase by asking for it twice"),                  NULL },
478                 { "key-file",          'd',  POPT_ARG_STRING,                             &opt_key_file,          0, N_("Read the key from a file (can be /dev/random)"),                   NULL },
479                 { "key-size",          's',  POPT_ARG_INT    | POPT_ARGFLAG_SHOW_DEFAULT, &opt_key_size,          0, N_("The size of the encryption key"),                                  N_("BITS") },
480                 { "key-slot",          'S',  POPT_ARG_INT,                                &opt_key_slot,          0, N_("Slot number for new key (default is first free)"),      NULL },
481                 { "size",              'b',  POPT_ARG_STRING,                             &popt_tmp,              1, N_("The size of the device"),                                          N_("SECTORS") },
482                 { "offset",            'o',  POPT_ARG_STRING,                             &popt_tmp,              2, N_("The start offset in the backend device"),                          N_("SECTORS") },
483                 { "skip",              'p',  POPT_ARG_STRING,                             &popt_tmp,              3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
484                 { "readonly",          'r',  POPT_ARG_NONE,                               &opt_readonly,          0, N_("Create a readonly mapping"),                                       NULL },
485                 { "iter-time",         'i',  POPT_ARG_INT,                                &opt_iteration_time,    0, N_("PBKDF2 iteration time for LUKS (in ms)"),
486                   N_("msecs") },
487                 { "batch-mode",        'q',  POPT_ARG_NONE,                               &opt_batch_mode,        0, N_("Do not ask for confirmation"),                                     NULL },
488                 { "version",        '\0',  POPT_ARG_NONE,                                 &opt_version_mode,        0, N_("Print package version"),                                     NULL },
489                 { "timeout",           't',  POPT_ARG_INT,                                &opt_timeout,           0, N_("Timeout for interactive passphrase prompt (in seconds)"),          N_("secs") },
490                 { "tries",             'T',  POPT_ARG_INT,                                &opt_tries,             0, N_("How often the input of the passphrase canbe retried"),            NULL },
491                 { "align-payload",     '\0',  POPT_ARG_INT,                               &opt_align_payload,     0, N_("Align payload at <n> sector boundaries - for luksFormat"),         N_("SECTORS") },
492                 { "non-exclusive",     '\0',  POPT_ARG_NONE,                              &opt_non_exclusive,     0, N_("Allows non-exclusive access for luksOpen, WARNING see manpage."),        NULL },
493                 POPT_TABLEEND
494         };
495         poptContext popt_context;
496         struct action_type *action;
497         char *aname;
498         int r;
499         const char *null_action_argv[] = {NULL};
500
501         set_default_log(cmdLineLog);
502
503         setlocale(LC_ALL, "");
504         bindtextdomain(PACKAGE, LOCALEDIR);
505         textdomain(PACKAGE);
506
507         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
508                                       popt_options, 0);
509         poptSetOtherOptionHelp(popt_context,
510                                N_("[OPTION...] <action> <action-specific>]"));
511
512         while((r = poptGetNextOpt(popt_context)) > 0) {
513                 unsigned long long ull_value;
514                 char *endp;
515
516                 ull_value = strtoull(popt_tmp, &endp, 0);
517                 if (*endp || !*popt_tmp)
518                         r = POPT_ERROR_BADNUMBER;
519
520                 switch(r) {
521                         case 1:
522                                 opt_size = ull_value;
523                                 break;
524                         case 2:
525                                 opt_offset = ull_value;
526                                 break;
527                         case 3:
528                                 opt_skip = ull_value;
529                                 break;
530                 }
531
532                 if (r < 0)
533                         break;
534         }
535
536         if (r < -1)
537                 usage(popt_context, 1, poptStrerror(r),
538                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
539         if (opt_version_mode) {
540                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
541                 exit(0);
542         }
543
544         if (opt_key_size % 8)
545                 usage(popt_context, 1,
546                       _("Key size must be a multiple of 8 bits"),
547                       poptGetInvocationName(popt_context));
548
549         if (!(aname = (char *)poptGetArg(popt_context)))
550                 usage(popt_context, 1, _("Argument <action> missing."),
551                       poptGetInvocationName(popt_context));
552         for(action = action_types; action->type; action++)
553                 if (strcmp(action->type, aname) == 0)
554                         break;
555         if (!action->type)
556                 usage(popt_context, 1, _("Unknown action."),
557                       poptGetInvocationName(popt_context));
558
559         action_argc = 0;
560         action_argv = poptGetArgs(popt_context);
561         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
562         if(!action_argv) 
563                 action_argv = null_action_argv;
564
565         /* Count args, somewhat unnice, change? */
566         while(action_argv[action_argc] != NULL)
567                 action_argc++;
568
569         if(action_argc < action->required_action_argc) {
570                 char buf[128];
571                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
572                 usage(popt_context, 1, buf,
573                       poptGetInvocationName(popt_context));
574         }
575
576         if (opt_debug) {
577                 opt_verbose = 1;
578                 crypt_set_debug_level(-1);
579                 _dbg_version_and_cmd(argc, argv);
580         }
581
582         return run_action(action);
583 }