Print error when getline() fails (thanks to Ivan Stankovic)
[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         char *answer = NULL;
83         size_t size = 0;
84         int r = 1;
85
86         if(isatty(0) && !opt_batch_mode) {
87                 fprintf(stderr, "\nWARNING!\n========\n");
88                 fprintf(stderr, "%s\n\nAre you sure? (Type uppercase yes): ", msg);
89                 if(getline(&answer, &size, stdin) == -1) {
90                         perror("getline");
91                         free(answer);
92                         return 0;
93                 }
94                 if(strcmp(answer, "YES\n"))
95                         r = 0;
96                 free(answer);
97         }
98
99         return r;
100 }
101
102 static void cmdLineLog(int class, char *msg) {
103     switch(class) {
104
105     case CRYPT_LOG_NORMAL:
106             fputs(msg, stdout);
107             break;
108     case CRYPT_LOG_ERROR:
109             fputs(msg, stderr);
110             break;
111     default:
112             fprintf(stderr, "Internal error on logging class for msg: %s", msg);
113             break;
114     }
115 }
116
117 static struct interface_callbacks cmd_icb = {
118         .yesDialog = yesDialog,
119         .log = cmdLineLog,
120 };
121
122 /* End ICBs */
123
124 static void show_status(int errcode)
125 {
126         char error[256];
127
128         if(!errcode) {
129                 fprintf(stderr, _("Command successful.\n"));
130                 return;
131         }
132
133         crypt_get_error(error, sizeof(error));
134         if (!opt_verbose) {
135                 char *error_ = strerror_r(errcode, error, sizeof(error));
136                 if (error_ != error) {
137                         strncpy(error, error_, sizeof(error));
138                         error[sizeof error - 1] = '\0';
139                 }
140         }
141
142         fprintf(stderr, _("Command failed"));
143         if (*error)
144                 fprintf(stderr, ": %s\n", error);
145         else
146                 fputs(".\n", stderr);
147         return;
148 }
149
150 static int action_create(int reload)
151 {
152         struct crypt_options options = {
153                 .name = action_argv[0],
154                 .device = action_argv[1],
155                 .cipher = opt_cipher?opt_cipher:DEFAULT_CIPHER,
156                 .hash = opt_hash,
157                 .key_file = opt_key_file,
158                 .key_size = ((opt_key_size)?opt_key_size:DEFAULT_KEY_SIZE)/8,
159                 .key_slot = opt_key_slot,
160                 .passphrase_fd = 0,     /* stdin */
161                 .flags = 0,
162                 .size = opt_size,
163                 .offset = opt_offset,
164                 .skip = opt_skip,
165                 .timeout = opt_timeout,
166                 .tries = opt_tries,
167                 .icb = &cmd_icb,
168         };
169         int r;
170
171         if(reload) 
172                 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"));
173
174         if (options.hash && strcmp(options.hash, "plain") == 0)
175                 options.hash = NULL;
176         if (opt_verify_passphrase)
177                 options.flags |= CRYPT_FLAG_VERIFY;
178         if (opt_readonly)
179                 options.flags |= CRYPT_FLAG_READONLY;
180
181         if (reload)
182                 r = crypt_update_device(&options);
183         else
184                 r = crypt_create_device(&options);
185         if (r < 0)
186                 show_status(-r);
187         return r;
188 }
189
190 static int action_remove(int arg)
191 {
192         struct crypt_options options = {
193                 .name = action_argv[0],
194                 .icb = &cmd_icb,
195         };
196         int r;
197
198         r = crypt_remove_device(&options);
199         if (r < 0)
200                 show_status(-r);
201         return r;
202 }
203
204 static int action_resize(int arg)
205 {
206         struct crypt_options options = {
207                 .name = action_argv[0],
208                 .size = opt_size,
209                 .icb = &cmd_icb,
210         };
211         int r;
212
213         r = crypt_resize_device(&options);
214         if (r < 0)
215                 show_status(-r);
216         return r;
217 }
218
219 static int action_status(int arg)
220 {
221         struct crypt_options options = {
222                 .name = action_argv[0],
223                 .icb = &cmd_icb,
224         };
225         int r;
226
227         r = crypt_query_device(&options);
228         
229         if (r < 0) {
230                 /* error */
231                 show_status(-r);
232         } else if (r == 0) {
233                 /* inactive */
234                 printf("%s/%s is inactive.\n", crypt_get_dir(), options.name);
235                 r = 1;
236         } else {
237                 /* active */
238                 printf("%s/%s is active:\n", crypt_get_dir(), options.name);
239                 printf("  cipher:  %s\n", options.cipher);
240                 printf("  keysize: %d bits\n", options.key_size * 8);
241                 printf("  device:  %s\n", options.device);
242                 printf("  offset:  %" PRIu64 " sectors\n", options.offset);
243                 printf("  size:    %" PRIu64 " sectors\n", options.size);
244                 if (options.skip)
245                         printf("  skipped: %" PRIu64 " sectors\n", options.skip);
246                 printf("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
247                                            ? "readonly" : "read/write");
248                 crypt_put_options(&options);
249                 r = 0;
250         }
251         return r;
252 }
253
254 static int action_luksFormat(int arg)
255 {
256         struct crypt_options options = {
257                 .key_size = (opt_key_size != 0 ? opt_key_size : DEFAULT_LUKS_KEY_SIZE) / 8,
258                 .key_slot = opt_key_slot,
259                 .device = action_argv[0],
260                 .cipher = opt_cipher?opt_cipher:DEFAULT_LUKS_CIPHER,
261                 .new_key_file = action_argc > 1 ? action_argv[1] : NULL,
262                 .flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE :  0),
263                 .iteration_time = opt_iteration_time,
264                 .timeout = opt_timeout,
265                 .align_payload = opt_align_payload,
266                 .icb = &cmd_icb,
267         };
268
269         int r = 0; char *msg = NULL;
270
271         /* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
272         if (opt_offset || opt_skip) {
273                 fprintf(stderr,"Options --offset and --skip are not supported for luksFormat.\n"); 
274                 return -EINVAL;
275         }
276
277         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), options.device) == -1) {
278                 fputs(_("memory allocation error in action_luksFormat"), stderr);
279         } else {
280                 r = yesDialog(msg) ? crypt_luksFormat(&options) : -EINVAL;
281                 free(msg);
282                 show_status(-r);
283         }
284         return r;
285 }
286
287 static int action_luksOpen(int arg)
288 {
289         struct crypt_options options = {
290                 .name = action_argv[1],
291                 .device = action_argv[0],
292                 .key_file = opt_key_file,
293                 .timeout = opt_timeout,
294                 .tries = opt_tries,
295                 .icb = &cmd_icb,
296         };
297         int r; 
298
299         opt_verbose = 1;
300         options.flags = 0;
301         if (opt_readonly)
302                 options.flags |= CRYPT_FLAG_READONLY;
303         if (opt_non_exclusive)
304                 options.flags |= CRYPT_FLAG_NON_EXCLUSIVE_ACCESS;
305         r = crypt_luksOpen(&options);
306         show_status(-r);
307         return r;
308 }
309
310 static int action_luksDelKey(int arg)
311 {
312     fprintf(stderr,"luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
313     return action_luksKillSlot(arg);
314 }
315
316 static int action_luksKillSlot(int arg)
317 {
318         struct crypt_options options = {
319                 .device = action_argv[0],
320                 .key_slot = atoi(action_argv[1]),
321                 .key_file = opt_key_file,
322                 .timeout = opt_timeout,
323                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
324                 .icb = &cmd_icb,
325         };
326         int r; 
327
328         opt_verbose = 1;
329         r = crypt_luksKillSlot(&options);
330         show_status(-r);
331         return r;
332 }
333
334 static int action_luksRemoveKey(int arg)
335 {
336         struct crypt_options options = {
337                 .device = action_argv[0],
338                 .new_key_file = action_argc>1?action_argv[1]:NULL,
339                 .key_file = opt_key_file,
340                 .timeout = opt_timeout,
341                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
342                 .icb = &cmd_icb,
343         };
344         int r; 
345
346         opt_verbose = 1;
347         r = crypt_luksRemoveKey(&options);
348         show_status(-r);
349         return r;
350 }
351
352 static int action_luksAddKey(int arg)
353 {
354         struct crypt_options options = {
355                 .device = action_argv[0],
356                 .new_key_file = action_argc>1?action_argv[1]:NULL,
357                 .key_file = opt_key_file,
358                 .key_slot = opt_key_slot,
359                 .flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE : 0),
360                 .iteration_time = opt_iteration_time,
361                 .timeout = opt_timeout,
362                 .icb = &cmd_icb,
363         };
364         int r; 
365
366         opt_verbose = 1;
367         r = crypt_luksAddKey(&options);
368         show_status(-r);
369         return r;
370 }
371
372 static int action_isLuks(int arg)
373 {
374         struct crypt_options options = {
375                 .device = action_argv[0],
376                 .icb = &cmd_icb,
377         };
378         return crypt_isLuks(&options);
379 }
380
381 static int action_luksUUID(int arg)
382 {
383         struct crypt_options options = {
384                 .device = action_argv[0],
385                 .icb = &cmd_icb,
386         };
387         int r;
388
389         r = crypt_luksUUID(&options);
390         if (r < 0)
391                 show_status(-r);
392         return r;
393 }
394
395 static int action_luksDump(int arg)
396 {
397         struct crypt_options options = {
398                 .device = action_argv[0],
399                 .icb = &cmd_icb,
400         };
401         int r; 
402
403         r = crypt_luksDump(&options);
404         if (r < 0)
405                 show_status(-r);
406         return r;
407 }
408
409 static void usage(poptContext popt_context, int exitcode,
410                   const char *error, const char *more)
411 {
412         poptPrintUsage(popt_context, stderr, 0);
413         if (error)
414                 fprintf(stderr, "%s: %s\n", more, error);
415         exit(exitcode);
416 }
417
418 static void help(poptContext popt_context, enum poptCallbackReason reason,
419                  struct poptOption *key, const char * arg, void *data)
420 {
421         if (key->shortName == '?') {
422                 struct action_type *action;
423
424                 fprintf(stdout, "%s\n",PACKAGE_STRING);
425
426                 poptPrintHelp(popt_context, stdout, 0);
427
428                 printf(_("\n"
429                          "<action> is one of:\n"));
430
431                 for(action = action_types; action->type; action++)
432                         printf("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
433                 
434                 printf(_("\n"
435                          "<name> is the device to create under %s\n"
436                          "<device> is the encrypted device\n"
437                          "<key slot> is the LUKS key slot number to modify\n"
438                          "<key file> optional key file for the new key for luksAddKey action\n"),
439                         crypt_get_dir());
440                 exit(0);
441         } else
442                 usage(popt_context, 0, NULL, NULL);
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         return action->handler(action->arg);
556 }
557
558 // Local Variables:
559 // c-basic-offset: 8
560 // indent-tabs-mode: nil
561 // End: