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