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