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