14 #include "libcryptsetup.h"
24 static int memory_unsafe = 0;
25 static char *default_backend = NULL;
27 #define at_least_one(a) ({ __typeof__(a) __at_least_one=(a); (__at_least_one)?__at_least_one:1; })
29 static void logger(struct crypt_options *options, int class, char *format, ...) {
33 va_start(argp, format);
35 if (vasprintf(&target, format, argp) > 0)
36 options->icb->log(class, target);
42 static void hexprintICB(struct crypt_options *options, int class, char *d, int n)
45 for(i = 0; i < n; i++)
46 logger(options, class, "%02hhx ", (char)d[i]);
49 static int setup_enter(struct setup_backend *backend, void (*log)(int, char *))
54 * from here we could have sensible data in memory
55 * so protect it from being swapped out
57 r = mlockall(MCL_CURRENT | MCL_FUTURE);
59 perror("mlockall failed");
60 log(CRYPT_LOG_ERROR, "WARNING!!! Possibly insecure memory. Are you root?\n");
77 static int setup_leave(struct setup_backend *backend)
82 /* dangerous, we can't wipe all the memory */
90 * Password processing behaviour matrix of process_key
92 * from binary file: check if there is sufficently large key material
93 * interactive & from fd: hash if requested, otherwise crop or pad with '0'
96 static char *process_key(struct crypt_options *options, char *pass, int passLen) {
97 char *key = safe_alloc(options->key_size);
98 memset(key, 0, options->key_size);
100 /* key is coming from binary file */
101 if (options->key_file && strcmp(options->key_file, "-")) {
102 if(passLen < options->key_size) {
103 set_error("Could not read %d bytes from key file",
108 memcpy(key,pass,options->key_size);
112 /* key is coming from tty, fd or binary stdin */
114 if (hash(NULL, options->hash,
115 key, options->key_size,
121 } else if (passLen > options->key_size) {
122 memcpy(key, pass, options->key_size);
124 memcpy(key, pass, passLen);
130 static int get_device_infos(const char *device, struct device_infos *infos)
134 unsigned long size_small;
139 /* Try to open read-write to check whether it is a read-only device */
140 fd = open(device, O_RDWR);
142 if (errno == EROFS) {
144 fd = open(device, O_RDONLY);
148 fd = open(device, O_RDONLY);
151 set_error("Error opening device: %s",
152 strerror_r(errno, buf, 128));
157 /* If the device can be opened read-write, i.e. readonly is still 0, then
158 * check whether BKROGET says that it is read-only. E.g. read-only loop
159 * devices may be openend read-write but are read-only according to BLKROGET
162 if (ioctl(fd, BLKROGET, &readonly) < 0) {
163 set_error("BLKROGET failed on device: %s",
164 strerror_r(errno, buf, 128));
169 #error BLKROGET not available
173 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
174 size >>= SECTOR_SHIFT;
181 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
182 size = (uint64_t)size_small;
187 # error Need at least the BLKGETSIZE ioctl!
190 set_error("BLKGETSIZE ioctl failed on device: %s",
191 strerror_r(errno, buf, 128));
196 infos->readonly = readonly;
202 static int wipe_device_header(const char *device, int sectors)
205 int size = sectors * SECTOR_SIZE;
209 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
211 set_error("Can't wipe header on device %s", device);
215 buffer = malloc(size);
220 memset(buffer, 0, size);
222 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
230 static int parse_into_name_and_mode(const char *nameAndMode, char *name,
233 /* Token content stringification, see info cpp/stringification */
235 #define xstr(s) str(s)
236 #define scanpattern1 "%" xstr(LUKS_CIPHERNAME_L) "[^-]-%" xstr(LUKS_CIPHERMODE_L) "s"
237 #define scanpattern2 "%" xstr(LUKS_CIPHERNAME_L) "[^-]"
241 if(sscanf(nameAndMode,scanpattern1, name, mode) != 2) {
242 if((r = sscanf(nameAndMode,scanpattern2,name)) == 1) {
243 strncpy(mode,"cbc-plain",10);
246 set_error("no known cipher-spec pattern detected");
259 static int keyslot_is_valid(int keySlotIndex, struct crypt_options *options)
261 if(keySlotIndex >= LUKS_NUMKEYS || keySlotIndex < 0) {
262 logger(options,CRYPT_LOG_ERROR,"Key slot %d is invalid, please pick between 0 and %d.\n", keySlotIndex, LUKS_NUMKEYS - 1);
269 /* Select free keyslot or verifies that the one specified is empty */
270 static int keyslot_from_option(int keySlotOption, struct luks_phdr *hdr, struct crypt_options *options) {
271 if(keySlotOption >= 0) {
272 if(!keyslot_is_valid(keySlotOption, options))
274 else if(hdr->keyblock[keySlotOption].active != LUKS_KEY_DISABLED) {
275 logger(options,CRYPT_LOG_ERROR,"Key slot %d is full, please pick another one", keySlotOption);
278 return keySlotOption;
282 /* Find empty key slot */
283 for(i=0; i<LUKS_NUMKEYS; i++) {
284 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED) break;
286 if(i==LUKS_NUMKEYS) {
287 logger(options,CRYPT_LOG_ERROR,"All slots full");
294 static int __crypt_create_device(int reload, struct setup_backend *backend,
295 struct crypt_options *options)
297 struct crypt_options tmp = {
298 .name = options->name,
300 struct device_infos infos;
303 char *processed_key = NULL;
306 r = backend->status(0, &tmp, NULL);
312 set_error("Device %s already exists.", options->name);
319 if (options->key_size < 0 || options->key_size > 1024) {
320 set_error("Invalid key size");
324 if (get_device_infos(options->device, &infos) < 0)
327 if (!options->size) {
328 options->size = infos.size;
329 if (!options->size) {
330 set_error("Not a block device");
333 if (options->size <= options->offset) {
334 set_error("Invalid offset");
337 options->size -= options->offset;
341 options->flags |= CRYPT_FLAG_READONLY;
343 get_key("Enter passphrase: ", &key, &keyLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags);
345 set_error("Key reading error");
349 processed_key = process_key(options,key,keyLen);
352 if (!processed_key) {
353 const char *error=get_error();
355 char *c_error_handling_sucks = NULL;
356 if (asprintf(&c_error_handling_sucks,"Key processing error: %s",error) > 0)
357 set_error(c_error_handling_sucks);
358 free(c_error_handling_sucks);
360 set_error("Key processing error");
364 r = backend->create(reload, options, processed_key, NULL);
366 safe_free(processed_key);
371 static int __crypt_query_device(int details, struct setup_backend *backend,
372 struct crypt_options *options)
374 int r = backend->status(details, options, NULL);
383 static int __crypt_resize_device(int details, struct setup_backend *backend,
384 struct crypt_options *options)
386 struct crypt_options tmp = {
387 .name = options->name,
389 struct device_infos infos;
393 r = backend->status(1, &tmp, &key);
397 if (get_device_infos(tmp.device, &infos) < 0)
400 if (!options->size) {
401 options->size = infos.size;
402 if (!options->size) {
403 set_error("Not a block device");
406 if (options->size <= tmp.offset) {
407 set_error("Invalid offset");
410 options->size -= tmp.offset;
412 tmp.size = options->size;
415 options->flags |= CRYPT_FLAG_READONLY;
417 r = backend->create(1, &tmp, key, NULL);
424 static int __crypt_remove_device(int arg, struct setup_backend *backend,
425 struct crypt_options *options)
429 r = backend->status(0, options, NULL);
433 set_error("Device busy");
437 return backend->remove(0, options);
440 static int __crypt_luks_format(int arg, struct setup_backend *backend, struct crypt_options *options)
444 struct luks_phdr header;
445 struct luks_masterkey *mk=NULL;
447 char cipherName[LUKS_CIPHERNAME_L];
448 char cipherMode[LUKS_CIPHERMODE_L];
449 unsigned int passwordLen;
450 unsigned int PBKDF2perSecond = 0;
453 if (!LUKS_device_ready(options->device, O_RDWR | O_EXCL))
456 mk = LUKS_generate_masterkey(options->key_size);
457 if(NULL == mk) return -ENOMEM; // FIXME This may be misleading, since we don't know what went wrong
460 #define printoffset(entry) \
461 logger(options, CRYPT_LOG_ERROR, \
462 "offset of " #entry " = %d\n", (char *)(&header.entry)-(char *)(&header))
464 logger(options, CRYPT_LOG_ERROR,
465 "sizeof phdr %d, sizeof key slot %d\n",
466 sizeof(struct luks_phdr),
467 sizeof(header.keyblock[0]));
470 printoffset(version);
471 printoffset(cipherName);
472 printoffset(cipherMode);
473 printoffset(hashSpec);
474 printoffset(payloadOffset);
475 printoffset(keyBytes);
476 printoffset(mkDigest);
477 printoffset(mkDigestSalt);
478 printoffset(mkDigestIterations);
482 r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
485 r = LUKS_generate_phdr(&header, mk, cipherName, cipherMode, options->hash, LUKS_STRIPES, options->align_payload);
488 keyIndex = keyslot_from_option(options->key_slot, &header, options);
489 if(keyIndex == -EINVAL) {
490 r = -EINVAL; goto out;
493 r = LUKS_benchmarkt_iterations(options->hash, &PBKDF2perSecond);
496 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
498 logger(options, CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
500 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
502 r = -EINVAL; goto out;
505 /* Wipe first 8 sectors - fs magic numbers etc. */
506 r = wipe_device_header(options->device, 8);
509 /* Set key, also writes phdr */
510 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk, backend);
515 LUKS_dealloc_masterkey(mk);
520 static int __crypt_luks_open(int arg, struct setup_backend *backend, struct crypt_options *options)
522 struct luks_masterkey *mk=NULL;
523 struct luks_phdr hdr;
526 unsigned int passwordLen;
527 struct device_infos infos;
528 struct crypt_options tmp = {
529 .name = options->name,
531 char *dmCipherSpec = NULL;
532 int r, tries = options->tries;
533 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
535 r = backend->status(0, &tmp, NULL);
537 set_error("Device %s already exists.", options->name);
541 if (!LUKS_device_ready(options->device, O_RDONLY | excl))
544 if (get_device_infos(options->device, &infos) < 0) {
545 set_error("Can't get device information.\n");
550 options->flags |= CRYPT_FLAG_READONLY;
552 if(asprintf(&prompt, "Enter LUKS passphrase for %s: ", options->device) < 0)
558 if(options->passphrase) {
559 passwordLen = strlen(options->passphrase);
560 password = safe_alloc(passwordLen + 1);
561 strncpy(password, options->passphrase, passwordLen + 1);
563 } else if(get_key(prompt, &password, &passwordLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags))
569 r = -EINVAL; goto out;
572 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk, backend);
574 set_error("No key available with this passphrase.\n");
578 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
581 options->offset = hdr.payloadOffset;
582 if (asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode) < 0) {
586 options->cipher = dmCipherSpec;
587 options->key_size = mk->keyLength;
590 options->size = infos.size;
591 if (!options->size) {
592 set_error("Not a block device.\n");
593 r = -ENOTBLK; goto out2;
595 if (options->size <= options->offset) {
596 set_error("Invalid offset");
597 r = -EINVAL; goto out2;
599 options->size -= options->offset;
600 /* FIXME: code allows multiple crypt mapping, cannot use uuid then.
601 * anyway, it is dangerous and can corrupt data. Remove it in next version! */
602 r = backend->create(0, options, mk->key, excl ? hdr.uuid : NULL);
610 LUKS_dealloc_masterkey(mk);
611 if (r == -EPERM && tries > 0)
619 static int __crypt_luks_add_key(int arg, struct setup_backend *backend, struct crypt_options *options)
621 struct luks_masterkey *mk=NULL;
622 struct luks_phdr hdr;
623 char *password=NULL; unsigned int passwordLen;
624 unsigned int keyIndex;
625 unsigned int PBKDF2perSecond = 0;
626 const char *device = options->device;
629 if (!LUKS_device_ready(options->device, O_RDWR))
632 r = LUKS_read_phdr(device, &hdr);
636 keyIndex = keyslot_from_option(options->key_slot, &hdr, options);
637 if(keyIndex == -EINVAL) {
638 r = -EINVAL; goto out;
641 get_key("Enter any LUKS passphrase: ",
646 options->passphrase_fd,
648 options->flags & ~(CRYPT_FLAG_VERIFY | CRYPT_FLAG_VERIFY_IF_POSSIBLE));
651 r = -EINVAL; goto out;
653 r = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
655 options->icb->log(CRYPT_LOG_ERROR,"No key available with this passphrase.\n");
656 r = -EPERM; goto out;
658 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
662 get_key("Enter new passphrase for key slot: ",
666 options->new_key_file,
667 options->passphrase_fd,
671 r = -EINVAL; goto out;
674 r = LUKS_benchmarkt_iterations(hdr.hashSpec, &PBKDF2perSecond);
676 hdr.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000));
678 r = LUKS_set_key(device, keyIndex, password, passwordLen, &hdr, mk, backend);
684 LUKS_dealloc_masterkey(mk);
688 static int luks_remove_helper(int arg, struct setup_backend *backend, struct crypt_options *options, int supply_it)
690 struct luks_masterkey *mk;
691 struct luks_phdr hdr;
693 unsigned int passwordLen;
694 const char *device = options->device;
699 if (!LUKS_device_ready(options->device, O_RDWR))
703 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file,
704 options->passphrase_fd, options->timeout, options->flags);
706 r = -EINVAL; goto out;
709 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
711 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
712 r = -EPERM; goto out;
714 logger(options, CRYPT_LOG_NORMAL,"key slot %d selected for deletion.\n", keyIndex);
719 keyIndex = options->key_slot;
720 if (!keyslot_is_valid(keyIndex, options)) {
721 r = -EINVAL; goto out;
725 last_slot = LUKS_is_last_keyslot(options->device, keyIndex);
726 if(last_slot && !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
727 r = -EINVAL; goto out;
730 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
731 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
732 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
734 r = -EINVAL; goto out;
737 r = LUKS_read_phdr(device, &hdr);
739 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
744 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
746 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk, backend);
748 if (openedIndex >= 0) {
749 LUKS_dealloc_masterkey(mk);
752 if(openedIndex < 0) {
753 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
754 r = -EPERM; goto out;
756 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
758 r = LUKS_del_key(device, keyIndex);
767 static int __crypt_luks_kill_slot(int arg, struct setup_backend *backend, struct crypt_options *options) {
768 return luks_remove_helper(arg, backend, options, 0);
771 static int __crypt_luks_remove_key(int arg, struct setup_backend *backend, struct crypt_options *options) {
772 return luks_remove_helper(arg, backend, options, 1);
776 static int crypt_job(int (*job)(int arg, struct setup_backend *backend,
777 struct crypt_options *options),
778 int arg, struct crypt_options *options)
780 struct setup_backend *backend;
783 backend = get_setup_backend(default_backend);
785 if (setup_enter(backend,options->icb->log) < 0) {
791 set_error("No setup backend available");
796 r = job(arg, backend, options);
798 setup_leave(backend);
800 put_setup_backend(backend);
808 int crypt_create_device(struct crypt_options *options)
810 return crypt_job(__crypt_create_device, 0, options);
813 int crypt_update_device(struct crypt_options *options)
815 return crypt_job(__crypt_create_device, 1, options);
818 int crypt_resize_device(struct crypt_options *options)
820 return crypt_job(__crypt_resize_device, 0, options);
823 int crypt_query_device(struct crypt_options *options)
825 return crypt_job(__crypt_query_device, 1, options);
828 int crypt_remove_device(struct crypt_options *options)
830 return crypt_job(__crypt_remove_device, 0, options);
834 int crypt_luksFormat(struct crypt_options *options)
836 return crypt_job(__crypt_luks_format, 0, options);
839 int crypt_luksOpen(struct crypt_options *options)
841 return crypt_job(__crypt_luks_open, 0, options);
844 int crypt_luksKillSlot(struct crypt_options *options)
846 return crypt_job(__crypt_luks_kill_slot, 0, options);
849 int crypt_luksRemoveKey(struct crypt_options *options)
851 return crypt_job(__crypt_luks_remove_key, 0, options);
854 int crypt_luksAddKey(struct crypt_options *options)
856 return crypt_job(__crypt_luks_add_key, 0, options);
859 int crypt_luksUUID(struct crypt_options *options)
861 struct luks_phdr hdr;
864 r = LUKS_read_phdr(options->device,&hdr);
867 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
868 options->icb->log(CRYPT_LOG_NORMAL,"\n");
872 int crypt_isLuks(struct crypt_options *options)
874 struct luks_phdr hdr;
875 return LUKS_read_phdr(options->device,&hdr);
878 int crypt_luksDump(struct crypt_options *options)
880 struct luks_phdr hdr;
883 r = LUKS_read_phdr(options->device,&hdr);
886 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
887 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
888 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
889 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
890 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
891 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
892 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
893 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
894 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
895 logger(options, CRYPT_LOG_NORMAL, "\n");
896 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
897 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
898 logger(options, CRYPT_LOG_NORMAL, "\n \t");
899 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
900 logger(options, CRYPT_LOG_NORMAL, "\n");
901 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
902 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
903 for(i=0;i<LUKS_NUMKEYS;i++) {
904 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
905 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
906 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
907 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
908 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
909 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
910 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
911 logger(options, CRYPT_LOG_NORMAL, "\n");
913 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
914 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
917 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
923 void crypt_get_error(char *buf, size_t size)
925 const char *error = get_error();
927 if (!buf || size < 1)
930 strncpy(buf, error, size - 1);
931 buf[size - 1] = '\0';
937 void crypt_put_options(struct crypt_options *options)
939 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
940 free((char *)options->device);
941 options->device = NULL;
942 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
944 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
945 free((char *)options->cipher);
946 options->cipher = NULL;
947 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
951 void crypt_set_default_backend(const char *backend)
954 free(default_backend);
956 default_backend = strdup(backend);
958 default_backend = NULL;
961 const char *crypt_get_dir(void)
963 struct setup_backend *backend;
966 backend = get_setup_backend(default_backend);
970 dir = backend->dir();
972 put_setup_backend(backend);
979 // indent-tabs-mode: nil