Fix loopaes open parameters.
[platform/upstream/cryptsetup.git] / src / cryptsetup.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdarg.h>
6 #include <inttypes.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <assert.h>
11
12 #include <libcryptsetup.h>
13 #include <popt.h>
14
15 #include "../config.h"
16
17 #include "cryptsetup.h"
18
19 static int opt_verbose = 0;
20 static int opt_debug = 0;
21 static char *opt_cipher = NULL;
22 static char *opt_hash = NULL;
23 static int opt_verify_passphrase = 0;
24 static char *opt_key_file = NULL;
25 static char *opt_master_key_file = NULL;
26 static char *opt_header_backup_file = NULL;
27 static char *opt_uuid = NULL;
28 static unsigned int opt_key_size = 0;
29 static unsigned int opt_keyfile_size = 0;
30 static unsigned int opt_new_keyfile_size = 0;
31 static int opt_key_slot = CRYPT_ANY_SLOT;
32 static uint64_t opt_size = 0;
33 static uint64_t opt_offset = 0;
34 static uint64_t opt_skip = 0;
35 static int opt_readonly = 0;
36 static int opt_iteration_time = 1000;
37 static int opt_batch_mode = 0;
38 static int opt_version_mode = 0;
39 static int opt_timeout = 0;
40 static int opt_tries = 3;
41 static int opt_align_payload = 0;
42 static int opt_random = 0;
43 static int opt_urandom = 0;
44 static int opt_dump_master_key = 0;
45
46 static const char **action_argv;
47 static int action_argc;
48
49 static int action_create(int arg);
50 static int action_remove(int arg);
51 static int action_resize(int arg);
52 static int action_status(int arg);
53 static int action_luksFormat(int arg);
54 static int action_luksOpen(int arg);
55 static int action_luksAddKey(int arg);
56 static int action_luksKillSlot(int arg);
57 static int action_luksRemoveKey(int arg);
58 static int action_luksChangeKey(int arg);
59 static int action_isLuks(int arg);
60 static int action_luksUUID(int arg);
61 static int action_luksDump(int arg);
62 static int action_luksSuspend(int arg);
63 static int action_luksResume(int arg);
64 static int action_luksBackup(int arg);
65 static int action_luksRestore(int arg);
66 static int action_loopaesOpen(int arg);
67
68 static struct action_type {
69         const char *type;
70         int (*handler)(int);
71         int arg;
72         int required_action_argc;
73         int required_memlock;
74         const char *arg_desc;
75         const char *desc;
76 } action_types[] = {
77         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
78         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
79         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
80         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
81         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
82         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
83         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
84         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
85         { "luksChangeKey",action_luksChangeKey, 0, 1, 1, N_("<device> [<key file>]"), N_("changes supplied key or key file of LUKS device") },
86         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
87         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
88         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
89         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
90         { "luksDump",   action_luksDump,        0, 1, 0, N_("<device>"), N_("dump LUKS partition information") },
91         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
92         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
93         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
94         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
95         { "loopaesOpen",action_loopaesOpen,     0, 2, 1, N_("<device> <name> "), N_("open loop-AES device as mapping <name>") },
96         { "loopaesClose",action_remove,         0, 1, 1, N_("<name>"), N_("remove loop-AES mapping") },
97         { NULL, NULL, 0, 0, 0, NULL, NULL }
98 };
99
100 static void clogger(struct crypt_device *cd, int level, const char *file,
101                    int line, const char *format, ...)
102 {
103         va_list argp;
104         char *target = NULL;
105
106         va_start(argp, format);
107
108         if (vasprintf(&target, format, argp) > 0) {
109                 if (level >= 0) {
110                         crypt_log(cd, level, target);
111 #ifdef CRYPT_DEBUG
112                 } else if (opt_debug)
113                         printf("# %s:%d %s\n", file ?: "?", line, target);
114 #else
115                 } else if (opt_debug)
116                         printf("# %s\n", target);
117 #endif
118         }
119
120         va_end(argp);
121         free(target);
122 }
123
124 static int _yesDialog(const char *msg, void *usrptr)
125 {
126         char *answer = NULL;
127         size_t size = 0;
128         int r = 1;
129
130         if(isatty(0) && !opt_batch_mode) {
131                 log_std("\nWARNING!\n========\n");
132                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
133                 if(getline(&answer, &size, stdin) == -1) {
134                         perror("getline");
135                         free(answer);
136                         return 0;
137                 }
138                 if(strcmp(answer, "YES\n"))
139                         r = 0;
140                 free(answer);
141         }
142
143         return r;
144 }
145
146 static void _log(int level, const char *msg, void *usrptr)
147 {
148         switch(level) {
149
150         case CRYPT_LOG_NORMAL:
151                 fputs(msg, stdout);
152                 break;
153         case CRYPT_LOG_VERBOSE:
154                 if (opt_verbose)
155                         fputs(msg, stdout);
156                 break;
157         case CRYPT_LOG_ERROR:
158                 fputs(msg, stderr);
159                 break;
160         default:
161                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
162                 break;
163         }
164 }
165
166 static void show_status(int errcode)
167 {
168         char error[256], *error_;
169
170         if(!opt_verbose)
171                 return;
172
173         if(!errcode) {
174                 log_std(_("Command successful.\n"));
175                 return;
176         }
177
178         crypt_get_error(error, sizeof(error));
179
180         if (!error[0]) {
181                 error_ = strerror_r(-errcode, error, sizeof(error));
182                 if (error_ != error) {
183                         strncpy(error, error_, sizeof(error));
184                         error[sizeof(error) - 1] = '\0';
185                 }
186         }
187
188         log_err(_("Command failed with code %i"), -errcode);
189         if (*error)
190                 log_err(": %s\n", error);
191         else
192                 log_err(".\n");
193 }
194
195 static int action_create(int arg)
196 {
197         struct crypt_device *cd = NULL;
198         char cipher[MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
199         struct crypt_params_plain params = {
200                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
201                 .skip = opt_skip,
202                 .offset = opt_offset,
203         };
204         char *password = NULL;
205         unsigned int passwordLen;
206         unsigned int key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8;
207         int r;
208
209         if (params.hash && !strcmp(params.hash, "plain"))
210                 params.hash = NULL;
211
212         /* FIXME: temporary hack */
213         if (opt_key_file && strcmp(opt_key_file, "-"))
214                 params.hash = NULL;
215
216         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(PLAIN),
217                                       cipher, NULL, cipher_mode);
218         if (r < 0) {
219                 log_err("No known cipher specification pattern detected.\n");
220                 goto out;
221         }
222
223         if ((r = crypt_init(&cd, action_argv[1])))
224                 goto out;
225
226         crypt_set_timeout(cd, opt_timeout);
227         crypt_set_password_retry(cd, opt_tries);
228
229         r = crypt_format(cd, CRYPT_PLAIN,
230                          cipher, cipher_mode,
231                          NULL, NULL,
232                          key_size,
233                          &params);
234         if (r < 0)
235                 goto out;
236
237         if (opt_key_file)
238                 r = crypt_activate_by_keyfile(cd, action_argv[0],
239                         CRYPT_ANY_SLOT, opt_key_file, key_size,
240                         opt_readonly ?  CRYPT_ACTIVATE_READONLY : 0);
241         else {
242                 r = crypt_get_key(_("Enter passphrase: "),
243                                   &password, &passwordLen, 0, NULL,
244                                   opt_timeout,
245                                   opt_batch_mode ? 0 : opt_verify_passphrase,
246                                   cd);
247                 if (r < 0)
248                         goto out;
249
250                 r = crypt_activate_by_passphrase(cd, action_argv[0],
251                         CRYPT_ANY_SLOT, password, passwordLen,
252                          opt_readonly ?  CRYPT_ACTIVATE_READONLY : 0);
253         }
254 out:
255         crypt_free(cd);
256         crypt_safe_free(password);
257
258         return r;
259 }
260
261 static int action_loopaesOpen(int arg)
262 {
263         struct crypt_device *cd = NULL;
264         struct crypt_params_loopaes params = {
265                 .hash = opt_hash ?: NULL, // FIXME
266                 .offset = opt_offset,
267         };
268         unsigned int key_size = (opt_key_size ?: 128) / 8;
269         int r;
270
271         if (!opt_key_file) {
272                 log_err(_("Option --key-file is required.\n"));
273                 return -EINVAL;
274         }
275
276         if ((r = crypt_init(&cd, action_argv[0])))
277                 goto out;
278
279         r = crypt_format(cd, CRYPT_LOOPAES, NULL, NULL, NULL, NULL,
280                          key_size, &params);
281         if (r < 0)
282                 goto out;
283
284         r = crypt_activate_by_keyfile(cd, action_argv[1],
285                 CRYPT_ANY_SLOT, opt_key_file, 0,
286                 opt_readonly ?  CRYPT_ACTIVATE_READONLY : 0);
287 out:
288         crypt_free(cd);
289
290         return r;
291 }
292
293 static int action_remove(int arg)
294 {
295         struct crypt_device *cd = NULL;
296         int r;
297
298         r = crypt_init_by_name(&cd, action_argv[0]);
299         if (r == 0)
300                 r = crypt_deactivate(cd, action_argv[0]);
301
302         crypt_free(cd);
303         return r;
304 }
305
306 static int action_resize(int arg)
307 {
308         struct crypt_device *cd = NULL;
309         int r;
310
311         r = crypt_init_by_name(&cd, action_argv[0]);
312         if (r == 0)
313                 r = crypt_resize(cd, action_argv[0], opt_size);
314
315         crypt_free(cd);
316         return r;
317 }
318
319 static int action_status(int arg)
320 {
321         crypt_status_info ci;
322         struct crypt_active_device cad;
323         struct crypt_device *cd = NULL;
324         char *backing_file;
325         const char *device;
326         int r = 0;
327
328         ci = crypt_status(NULL, action_argv[0]);
329         switch (ci) {
330         case CRYPT_INVALID:
331                 r = -ENODEV;
332                 break;
333         case CRYPT_INACTIVE:
334                 log_std("%s/%s is inactive.\n", crypt_get_dir(), action_argv[0]);
335                 break;
336         case CRYPT_ACTIVE:
337         case CRYPT_BUSY:
338                 log_std("%s/%s is active%s.\n", crypt_get_dir(), action_argv[0],
339                         ci == CRYPT_BUSY ? " and is in use" : "");
340                 r = crypt_init_by_name(&cd, action_argv[0]);
341                 if (r < 0 || !crypt_get_type(cd))
342                         goto out;
343
344                 log_std("  type:    %s\n", crypt_get_type(cd));
345
346                 r = crypt_get_active_device(cd, action_argv[0], &cad);
347                 if (r < 0)
348                         goto out;
349
350                 log_std("  cipher:  %s-%s\n", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
351                 log_std("  keysize: %d bits\n", crypt_get_volume_key_size(cd) * 8);
352                 device = crypt_get_device_name(cd);
353                 log_std("  device:  %s\n", device);
354                 if (crypt_loop_device(device)) {
355                         backing_file = crypt_loop_backing_file(device);
356                         log_std("  loop:    %s\n", backing_file);
357                         free(backing_file);
358                 }
359                 log_std("  offset:  %" PRIu64 " sectors\n", cad.offset);
360                 log_std("  size:    %" PRIu64 " sectors\n", cad.size);
361                 if (cad.iv_offset)
362                         log_std("  skipped: %" PRIu64 " sectors\n", cad.iv_offset);
363                 log_std("  mode:    %s\n", cad.flags & CRYPT_ACTIVATE_READONLY ?
364                                            "readonly" : "read/write");
365         }
366 out:
367         crypt_free(cd);
368         return r;
369 }
370
371 static int _read_mk(const char *file, char **key, int keysize)
372 {
373         int fd;
374
375         *key = crypt_safe_alloc(keysize);
376         if (!*key)
377                 return -ENOMEM;
378
379         fd = open(file, O_RDONLY);
380         if (fd == -1) {
381                 log_err("Cannot read keyfile %s.\n", file);
382                 goto fail;
383         }
384         if ((read(fd, *key, keysize) != keysize)) {
385                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
386                 close(fd);
387                 goto fail;
388         }
389         close(fd);
390         return 0;
391 fail:
392         crypt_safe_free(*key);
393         *key = NULL;
394         return -EINVAL;
395 }
396
397 static int action_luksFormat(int arg)
398 {
399         int r = -EINVAL, keysize;
400         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
401         char *password = NULL;
402         unsigned int passwordLen;
403         struct crypt_device *cd = NULL;
404         struct crypt_params_luks1 params = {
405                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
406                 .data_alignment = opt_align_payload,
407         };
408
409         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
410                 log_err(_("memory allocation error in action_luksFormat"));
411                 r = -ENOMEM;
412                 goto out;
413         }
414         r = _yesDialog(msg, NULL) ? 0 : -EINVAL;
415         free(msg);
416         if (r < 0)
417                 goto out;
418
419         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
420                                       cipher, NULL, cipher_mode);
421         if (r < 0) {
422                 log_err("No known cipher specification pattern detected.\n");
423                 goto out;
424         }
425
426         if ((r = crypt_init(&cd, action_argv[0])))
427                 goto out;
428
429         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
430
431         crypt_set_password_verify(cd, 1);
432         crypt_set_timeout(cd, opt_timeout);
433         if (opt_iteration_time)
434                 crypt_set_iterarion_time(cd, opt_iteration_time);
435
436         if (opt_random)
437                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
438         else if (opt_urandom)
439                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
440
441         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
442                           opt_keyfile_size, opt_key_file, opt_timeout,
443                           opt_batch_mode ? 0 : 1 /* always verify */, cd);
444         if (r < 0)
445                 goto out;
446
447         if (opt_master_key_file) {
448                 r = _read_mk(opt_master_key_file, &key, keysize);
449                 if (r < 0)
450                         goto out;
451         }
452
453         r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
454                          opt_uuid, key, keysize, &params);
455         if (r < 0)
456                 goto out;
457
458         r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
459                                             key, keysize,
460                                             password, passwordLen);
461 out:
462         crypt_free(cd);
463         crypt_safe_free(key);
464         crypt_safe_free(password);
465
466         return r;
467 }
468
469 static int action_luksOpen(int arg)
470 {
471         struct crypt_device *cd = NULL;
472         uint32_t flags = 0;
473         int r;
474
475         if ((r = crypt_init(&cd, action_argv[0])))
476                 goto out;
477
478         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
479                 goto out;
480
481         crypt_set_timeout(cd, opt_timeout);
482         crypt_set_password_retry(cd, opt_tries);
483
484         if (opt_iteration_time)
485                 crypt_set_iterarion_time(cd, opt_iteration_time);
486         if (opt_readonly)
487                 flags |= CRYPT_ACTIVATE_READONLY;
488
489         if (opt_key_file) {
490                 crypt_set_password_retry(cd, 1);
491                 r = crypt_activate_by_keyfile(cd, action_argv[1],
492                         CRYPT_ANY_SLOT, opt_key_file, opt_keyfile_size,
493                         flags);
494         } else
495                 r = crypt_activate_by_passphrase(cd, action_argv[1],
496                         CRYPT_ANY_SLOT, NULL, 0, flags);
497 out:
498         crypt_free(cd);
499         return r;
500 }
501
502 static int verify_keyslot(struct crypt_device *cd, int key_slot,
503                           char *msg_last, char *msg_pass,
504                           const char *key_file, int keyfile_size)
505 {
506         crypt_keyslot_info ki;
507         char *password = NULL;
508         unsigned int passwordLen, i;
509         int r;
510
511         ki = crypt_keyslot_status(cd, key_slot);
512         if (ki == CRYPT_SLOT_ACTIVE_LAST && msg_last && !_yesDialog(msg_last, NULL))
513                 return -EPERM;
514
515         r = crypt_get_key(msg_pass, &password, &passwordLen,
516                           keyfile_size, key_file, opt_timeout,
517                           opt_batch_mode ? 0 : opt_verify_passphrase, cd);
518         if(r < 0)
519                 goto out;
520
521         if (ki == CRYPT_SLOT_ACTIVE_LAST) {
522                 /* check the last keyslot */
523                 r = crypt_activate_by_passphrase(cd, NULL, key_slot,
524                                                  password, passwordLen, 0);
525         } else {
526                 /* try all other keyslots */
527                 for (i = 0; i < crypt_keyslot_max(CRYPT_LUKS1); i++) {
528                         if (i == key_slot)
529                                 continue;
530                         ki = crypt_keyslot_status(cd, key_slot);
531                         if (ki == CRYPT_SLOT_ACTIVE)
532                         r = crypt_activate_by_passphrase(cd, NULL, i,
533                                                          password, passwordLen, 0);
534                         if (r == i)
535                                 break;
536                 }
537         }
538
539         if (r < 0)
540                 log_err(_("No key available with this passphrase.\n"));
541 out:
542         crypt_safe_free(password);
543         return r;
544 }
545
546 static int action_luksKillSlot(int arg)
547 {
548         struct crypt_device *cd = NULL;
549         int r;
550
551         if ((r = crypt_init(&cd, action_argv[0])))
552                 goto out;
553
554         crypt_set_confirm_callback(cd, _yesDialog, NULL);
555         crypt_set_timeout(cd, opt_timeout);
556
557         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
558                 goto out;
559
560         switch (crypt_keyslot_status(cd, opt_key_slot)) {
561         case CRYPT_SLOT_ACTIVE_LAST:
562         case CRYPT_SLOT_ACTIVE:
563                 log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
564                 break;
565         case CRYPT_SLOT_INACTIVE:
566                 log_err(_("Key %d not active. Can't wipe.\n"), opt_key_slot);
567         case CRYPT_SLOT_INVALID:
568                 goto out;
569         }
570
571         if (!opt_batch_mode) {
572                 r = verify_keyslot(cd, opt_key_slot,
573                         _("This is the last keyslot. Device will become unusable after purging this key."),
574                         _("Enter any remaining LUKS passphrase: "),
575                         opt_key_file, opt_keyfile_size);
576                 if (r < 0)
577                         goto out;
578         }
579
580         r = crypt_keyslot_destroy(cd, opt_key_slot);
581 out:
582         crypt_free(cd);
583         return r;
584 }
585
586 static int action_luksRemoveKey(int arg)
587 {
588         struct crypt_device *cd = NULL;
589         char *password = NULL;
590         unsigned int passwordLen;
591         int r;
592
593         if ((r = crypt_init(&cd, action_argv[0])))
594                 goto out;
595
596         crypt_set_confirm_callback(cd, _yesDialog, NULL);
597         crypt_set_timeout(cd, opt_timeout);
598
599         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
600                 goto out;
601
602         r = crypt_get_key(_("Enter LUKS passphrase to be deleted: "),
603                       &password, &passwordLen,
604                       opt_keyfile_size, opt_key_file,
605                       opt_timeout,
606                       opt_batch_mode ? 0 : opt_verify_passphrase,
607                       cd);
608         if(r < 0)
609                 goto out;
610
611         r = crypt_activate_by_passphrase(cd, NULL, CRYPT_ANY_SLOT,
612                                          password, passwordLen, 0);
613         if (r < 0)
614                 goto out;
615
616         opt_key_slot = r;
617         log_verbose(_("Key slot %d selected for deletion.\n"), opt_key_slot);
618
619         if (crypt_keyslot_status(cd, opt_key_slot) == CRYPT_SLOT_ACTIVE_LAST &&
620             !_yesDialog(_("This is the last keyslot. "
621                           "Device will become unusable after purging this key."),
622                         NULL)) {
623                 r = -EPERM;
624                 goto out;
625         }
626
627         r = crypt_keyslot_destroy(cd, opt_key_slot);
628 out:
629         crypt_safe_free(password);
630         crypt_free(cd);
631         return r;
632 }
633
634 static int action_luksAddKey(int arg)
635 {
636         int r = -EINVAL, keysize = 0;
637         char *key = NULL;
638         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
639         struct crypt_device *cd = NULL;
640
641         if ((r = crypt_init(&cd, action_argv[0])))
642                 goto out;
643
644         crypt_set_confirm_callback(cd, _yesDialog, NULL);
645
646         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
647                 goto out;
648
649         keysize = crypt_get_volume_key_size(cd);
650         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
651         crypt_set_timeout(cd, opt_timeout);
652         if (opt_iteration_time)
653                 crypt_set_iterarion_time(cd, opt_iteration_time);
654
655         if (opt_master_key_file) {
656                 r = _read_mk(opt_master_key_file, &key, keysize);
657                 if (r < 0)
658                         goto out;
659                 //FIXME: process keyfile arg
660                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
661                                                     key, keysize, NULL, 0);
662         } else if (opt_key_file || opt_new_key_file) {
663                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
664                                                  opt_key_file, opt_keyfile_size,
665                                                  opt_new_key_file, opt_new_keyfile_size);
666         } else {
667                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
668                                                     NULL, 0, NULL, 0);
669         }
670 out:
671         crypt_free(cd);
672         crypt_safe_free(key);
673         return r;
674 }
675
676 static int _slots_full(struct crypt_device *cd)
677 {
678         int i;
679
680         for (i = 0; i < crypt_keyslot_max(crypt_get_type(cd)); i++)
681                 if (crypt_keyslot_status(cd, i) == CRYPT_SLOT_INACTIVE)
682                         return 0;
683         return 1;
684 }
685
686 static int action_luksChangeKey(int arg)
687 {
688         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
689         struct crypt_device *cd = NULL;
690         char *vk = NULL, *password = NULL;
691         unsigned int passwordLen = 0;
692         size_t vk_size;
693         int new_key_slot, old_key_slot, r;
694
695         if ((r = crypt_init(&cd, action_argv[0])))
696                 goto out;
697
698         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
699                 goto out;
700
701         r = crypt_get_key(_("Enter LUKS passphrase to be changed: "),
702                       &password, &passwordLen,
703                       opt_keyfile_size, opt_key_file, opt_timeout,
704                       opt_batch_mode ? 0 : opt_verify_passphrase, cd);
705         if (r < 0)
706                 goto out;
707
708         vk_size = crypt_get_volume_key_size(cd);
709         vk = crypt_safe_alloc(vk_size);
710         if (!vk) {
711                 r = -ENOMEM;
712                 goto out;
713         }
714
715         r = crypt_volume_key_get(cd, opt_key_slot, vk, &vk_size,
716                                  password, passwordLen);
717         if (r < 0) {
718                 if (opt_key_slot != CRYPT_ANY_SLOT)
719                         log_err(_("No key available with this passphrase.\n"));
720                 goto out;
721         }
722
723         if (opt_key_slot != CRYPT_ANY_SLOT || _slots_full(cd)) {
724                 log_dbg("Key slot %d is going to be overwritten (%s).",
725                         r, opt_key_slot != CRYPT_ANY_SLOT ?
726                         "explicit key slot specified" : "no free key slot");
727                 old_key_slot = r;
728                 new_key_slot = r;
729         } else {
730                 log_dbg("Allocating new key slot.");
731                 old_key_slot = r;
732                 new_key_slot = CRYPT_ANY_SLOT;
733         }
734
735         crypt_safe_free(password);
736         password = NULL;
737         passwordLen = 0;
738         r = crypt_get_key(_("Enter new LUKS passphrase: "),
739                           &password, &passwordLen,
740                           opt_new_keyfile_size, opt_new_key_file,
741                           opt_timeout, opt_batch_mode ? 0 : 1, cd);
742         if (r < 0)
743                 goto out;
744
745         if (new_key_slot == old_key_slot) {
746                 (void)crypt_keyslot_destroy(cd, old_key_slot);
747                 r = crypt_keyslot_add_by_volume_key(cd, new_key_slot,
748                                                     vk, vk_size,
749                                                     password, passwordLen);
750                 if (r >= 0)
751                         log_verbose(_("Key slot %d changed.\n"), r);
752         } else {
753                 r = crypt_keyslot_add_by_volume_key(cd, CRYPT_ANY_SLOT,
754                                                     vk, vk_size,
755                                                     password, passwordLen);
756                 if (r >= 0) {
757                         log_verbose(_("Replaced with key slot %d.\n"), r);
758                         r = crypt_keyslot_destroy(cd, old_key_slot);
759                 }
760         }
761         if (r < 0)
762                 log_err(_("Failed to swap new key slot.\n"));
763 out:
764         crypt_safe_free(vk);
765         crypt_safe_free(password);
766         crypt_free(cd);
767         return r;
768 }
769
770 static int action_isLuks(int arg)
771 {
772         struct crypt_device *cd = NULL;
773         int r;
774
775         if ((r = crypt_init(&cd, action_argv[0])))
776                 goto out;
777
778         r = crypt_load(cd, CRYPT_LUKS1, NULL);
779 out:
780         crypt_free(cd);
781         return r;
782 }
783
784 static int action_luksUUID(int arg)
785 {
786         struct crypt_device *cd = NULL;
787         const char *existing_uuid = NULL;
788         int r;
789
790         if ((r = crypt_init(&cd, action_argv[0])))
791                 goto out;
792
793         crypt_set_confirm_callback(cd, _yesDialog, NULL);
794
795         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
796                 goto out;
797
798         if (opt_uuid)
799                 r = crypt_set_uuid(cd, opt_uuid);
800         else {
801                 existing_uuid = crypt_get_uuid(cd);
802                 log_std("%s\n", existing_uuid ?: "");
803                 r = existing_uuid ? 0 : 1;
804         }
805 out:
806         crypt_free(cd);
807         return r;
808 }
809
810 static int luksDump_with_volume_key(struct crypt_device *cd)
811 {
812         char *vk = NULL, *password = NULL;
813         unsigned int passwordLen = 0;
814         size_t vk_size;
815         int i, r;
816
817         crypt_set_confirm_callback(cd, _yesDialog, NULL);
818         if (!_yesDialog(
819             _("LUKS header dump with volume key is sensitive information\n"
820               "which allows access to encrypted partition without passphrase.\n"
821               "This dump should be always stored encrypted on safe place."),
822               NULL))
823                 return -EPERM;
824
825         vk_size = crypt_get_volume_key_size(cd);
826         vk = crypt_safe_alloc(vk_size);
827         if (!vk)
828                 return -ENOMEM;
829
830         r = crypt_get_key(_("Enter LUKS passphrase: "), &password, &passwordLen,
831                           opt_keyfile_size, opt_key_file, opt_timeout, 0, cd);
832         if (r < 0)
833                 goto out;
834
835         r = crypt_volume_key_get(cd, CRYPT_ANY_SLOT, vk, &vk_size,
836                                  password, passwordLen);
837         if (r < 0)
838                 goto out;
839
840         log_std("LUKS header information for %s\n", crypt_get_device_name(cd));
841         log_std("Cipher name:   \t%s\n", crypt_get_cipher(cd));
842         log_std("Cipher mode:   \t%s\n", crypt_get_cipher_mode(cd));
843         log_std("Payload offset:\t%d\n", crypt_get_data_offset(cd));
844         log_std("UUID:          \t%s\n", crypt_get_uuid(cd));
845         log_std("MK bits:       \t%d\n", vk_size * 8);
846         log_std("MK dump:\t");
847
848         for(i = 0; i < vk_size; i++) {
849                 if (i && !(i % 16))
850                         log_std("\n\t\t");
851                 log_std("%02hhx ", (char)vk[i]);
852         }
853         log_std("\n");
854
855 out:
856         crypt_safe_free(password);
857         crypt_safe_free(vk);
858         return r;
859 }
860
861 static int action_luksDump(int arg)
862 {
863         struct crypt_device *cd = NULL;
864         int r;
865
866         if ((r = crypt_init(&cd, action_argv[0])))
867                 goto out;
868
869         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
870                 goto out;
871
872         if (opt_dump_master_key)
873                 r = luksDump_with_volume_key(cd);
874         else
875                 r = crypt_dump(cd);
876 out:
877         crypt_free(cd);
878         return r;
879 }
880
881 static int action_luksSuspend(int arg)
882 {
883         struct crypt_device *cd = NULL;
884         int r;
885
886         r = crypt_init_by_name(&cd, action_argv[0]);
887         if (!r)
888                 r = crypt_suspend(cd, action_argv[0]);
889
890         crypt_free(cd);
891         return r;
892 }
893
894 static int action_luksResume(int arg)
895 {
896         struct crypt_device *cd = NULL;
897         int r;
898
899         if ((r = crypt_init_by_name(&cd, action_argv[0])))
900                 goto out;
901
902         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
903                 goto out;
904
905         if (opt_key_file)
906                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
907                                             opt_key_file, opt_keyfile_size);
908         else
909                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
910                                                NULL, 0);
911 out:
912         crypt_free(cd);
913         return r;
914 }
915
916 static int action_luksBackup(int arg)
917 {
918         struct crypt_device *cd = NULL;
919         int r;
920
921         if (!opt_header_backup_file) {
922                 log_err(_("Option --header-backup-file is required.\n"));
923                 return -EINVAL;
924         }
925
926         if ((r = crypt_init(&cd, action_argv[0])))
927                 goto out;
928
929         crypt_set_confirm_callback(cd, _yesDialog, NULL);
930
931         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
932 out:
933         crypt_free(cd);
934         return r;
935 }
936
937 static int action_luksRestore(int arg)
938 {
939         struct crypt_device *cd = NULL;
940         int r = 0;
941
942         if (!opt_header_backup_file) {
943                 log_err(_("Option --header-backup-file is required.\n"));
944                 return -EINVAL;
945         }
946
947         if ((r = crypt_init(&cd, action_argv[0])))
948                 goto out;
949
950         crypt_set_confirm_callback(cd, _yesDialog, NULL);
951         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
952 out:
953         crypt_free(cd);
954         return r;
955 }
956
957 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
958                                              int exitcode, const char *error,
959                                              const char *more)
960 {
961         poptPrintUsage(popt_context, stderr, 0);
962         if (error)
963                 log_err("%s: %s\n", more, error);
964         exit(exitcode);
965 }
966
967 static void help(poptContext popt_context, enum poptCallbackReason reason,
968                  struct poptOption *key, const char * arg, void *data)
969 {
970         if (key->shortName == '?') {
971                 struct action_type *action;
972
973                 log_std("%s\n",PACKAGE_STRING);
974
975                 poptPrintHelp(popt_context, stdout, 0);
976
977                 log_std(_("\n"
978                          "<action> is one of:\n"));
979
980                 for(action = action_types; action->type; action++)
981                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
982
983                 log_std(_("\n"
984                          "<name> is the device to create under %s\n"
985                          "<device> is the encrypted device\n"
986                          "<key slot> is the LUKS key slot number to modify\n"
987                          "<key file> optional key file for the new key for luksAddKey action\n"),
988                         crypt_get_dir());
989
990                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
991                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
992                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
993                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
994                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
995                          DEFAULT_RNG);
996                 exit(EXIT_SUCCESS);
997         } else
998                 usage(popt_context, EXIT_SUCCESS, NULL, NULL);
999 }
1000
1001 static void _dbg_version_and_cmd(int argc, char **argv)
1002 {
1003         int i;
1004
1005         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1006         for (i = 0; i < argc; i++) {
1007                 if (i)
1008                         log_std(" ");
1009                 log_std(argv[i]);
1010         }
1011         log_std("\"\n");
1012 }
1013
1014 static int run_action(struct action_type *action)
1015 {
1016         int r;
1017
1018         log_dbg("Running command %s.", action->type);
1019
1020         if (action->required_memlock)
1021                 crypt_memory_lock(NULL, 1);
1022
1023         r = action->handler(action->arg);
1024
1025         if (action->required_memlock)
1026                 crypt_memory_lock(NULL, 0);
1027
1028         /* Some functions returns keyslot # */
1029         if (r > 0)
1030                 r = 0;
1031
1032         show_status(r);
1033
1034         /* Translate exit code to simple codes */
1035         switch (r) {
1036         case 0:         r = EXIT_SUCCESS; break;
1037         case -EEXIST:
1038         case -EBUSY:    r = 5; break;
1039         case -ENOTBLK:
1040         case -ENODEV:   r = 4; break;
1041         case -ENOMEM:   r = 3; break;
1042         case -EPERM:    r = 2; break;
1043         case -EINVAL:
1044         case -ENOENT:
1045         case -ENOSYS:
1046         default:        r = EXIT_FAILURE;
1047         }
1048         return r;
1049 }
1050
1051 int main(int argc, char **argv)
1052 {
1053         static char *popt_tmp;
1054         static struct poptOption popt_help_options[] = {
1055                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1056                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1057                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1058                 POPT_TABLEEND
1059         };
1060         static struct poptOption popt_options[] = {
1061                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1062                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1063                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1064                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1065                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1066                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1067                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
1068                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1069                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
1070                 { "dump-master-key",  '\0',  POPT_ARG_NONE, &opt_dump_master_key,       0, N_("Dump volume (master) key instead of keyslots info."), NULL },
1071                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
1072                 { "keyfile-size",      'l',  POPT_ARG_INT, &opt_keyfile_size,           0, N_("Limits the read from keyfile"), N_("bytes") },
1073                 { "new-keyfile-size", '\0',  POPT_ARG_INT, &opt_new_keyfile_size,       0, N_("Limits the read from newly added keyfile"), N_("bytes") },
1074                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
1075                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
1076                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
1077                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
1078                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
1079                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1080                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1081                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
1082                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1083                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
1084                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
1085                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1086                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1087                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
1088                 POPT_TABLEEND
1089         };
1090         poptContext popt_context;
1091         struct action_type *action;
1092         char *aname;
1093         int r;
1094         const char *null_action_argv[] = {NULL};
1095
1096         crypt_set_log_callback(NULL, _log, NULL);
1097
1098         setlocale(LC_ALL, "");
1099         bindtextdomain(PACKAGE, LOCALEDIR);
1100         textdomain(PACKAGE);
1101
1102         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
1103                                       popt_options, 0);
1104         poptSetOtherOptionHelp(popt_context,
1105                                N_("[OPTION...] <action> <action-specific>]"));
1106
1107         while((r = poptGetNextOpt(popt_context)) > 0) {
1108                 unsigned long long ull_value;
1109                 char *endp;
1110
1111                 ull_value = strtoull(popt_tmp, &endp, 0);
1112                 if (*endp || !*popt_tmp)
1113                         r = POPT_ERROR_BADNUMBER;
1114
1115                 switch(r) {
1116                         case 1:
1117                                 opt_size = ull_value;
1118                                 break;
1119                         case 2:
1120                                 opt_offset = ull_value;
1121                                 break;
1122                         case 3:
1123                                 opt_skip = ull_value;
1124                                 break;
1125                 }
1126
1127                 if (r < 0)
1128                         break;
1129         }
1130
1131         if (r < -1)
1132                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1133                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1134         if (opt_version_mode) {
1135                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1136                 exit(EXIT_SUCCESS);
1137         }
1138
1139         if (!(aname = (char *)poptGetArg(popt_context)))
1140                 usage(popt_context, EXIT_FAILURE, _("Argument <action> missing."),
1141                       poptGetInvocationName(popt_context));
1142         for(action = action_types; action->type; action++)
1143                 if (strcmp(action->type, aname) == 0)
1144                         break;
1145         if (!action->type)
1146                 usage(popt_context, EXIT_FAILURE, _("Unknown action."),
1147                       poptGetInvocationName(popt_context));
1148
1149         action_argc = 0;
1150         action_argv = poptGetArgs(popt_context);
1151         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
1152         if(!action_argv)
1153                 action_argv = null_action_argv;
1154
1155         /* Count args, somewhat unnice, change? */
1156         while(action_argv[action_argc] != NULL)
1157                 action_argc++;
1158
1159         if(action_argc < action->required_action_argc) {
1160                 char buf[128];
1161                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
1162                 usage(popt_context, EXIT_FAILURE, buf,
1163                       poptGetInvocationName(popt_context));
1164         }
1165
1166         /* FIXME: rewrite this from scratch */
1167
1168         if (opt_key_size &&
1169            strcmp(aname, "luksFormat") &&
1170            strcmp(aname, "create") &&
1171            strcmp(aname, "loopaesOpen")) {
1172                 usage(popt_context, EXIT_FAILURE,
1173                       _("Option --key-size is allowed only for luksFormat, create and loopaesOpen.\n"
1174                         "To limit read from keyfile use --keyfile-size=(bytes)."),
1175                       poptGetInvocationName(popt_context));
1176         }
1177
1178         if (opt_key_size % 8)
1179                 usage(popt_context, EXIT_FAILURE,
1180                       _("Key size must be a multiple of 8 bits"),
1181                       poptGetInvocationName(popt_context));
1182
1183         if (!strcmp(aname, "luksKillSlot") && action_argc > 1)
1184                 opt_key_slot = atoi(action_argv[1]);
1185         if (opt_key_slot != CRYPT_ANY_SLOT &&
1186             (opt_key_slot < 0 || opt_key_slot > crypt_keyslot_max(CRYPT_LUKS1)))
1187                 usage(popt_context, EXIT_FAILURE, _("Key slot is invalid."),
1188                       poptGetInvocationName(popt_context));
1189
1190         if ((!strcmp(aname, "luksRemoveKey") ||
1191              !strcmp(aname, "luksFormat")) &&
1192              action_argc > 1) {
1193                 if (opt_key_file)
1194                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
1195                 else
1196                         opt_key_file = (char*)action_argv[1];
1197         }
1198
1199         if (opt_random && opt_urandom)
1200                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1201                       poptGetInvocationName(popt_context));
1202         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
1203                 usage(popt_context, EXIT_FAILURE, _("Option --use-[u]random is allowed only for luksFormat."),
1204                       poptGetInvocationName(popt_context));
1205
1206         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
1207                 usage(popt_context, EXIT_FAILURE, _("Option --uuid is allowed only for luksFormat and luksUUID."),
1208                       poptGetInvocationName(popt_context));
1209
1210         if ((opt_offset || opt_skip) && strcmp(aname, "create"))
1211                 usage(popt_context, EXIT_FAILURE, _("Options --offset and --skip are supported only for create command.\n"),
1212                       poptGetInvocationName(popt_context));
1213
1214         if (opt_debug) {
1215                 opt_verbose = 1;
1216                 crypt_set_debug_level(-1);
1217                 _dbg_version_and_cmd(argc, argv);
1218         }
1219
1220         return run_action(action);
1221 }