14 #include "libcryptsetup.h"
24 static int memory_unsafe = 0;
26 #define at_least_one(a) ({ __typeof__(a) __at_least_one=(a); (__at_least_one)?__at_least_one:1; })
28 static void logger(struct crypt_options *options, int class, char *format, ...) {
32 va_start(argp, format);
34 if (vasprintf(&target, format, argp) > 0)
35 options->icb->log(class, target);
41 static void hexprintICB(struct crypt_options *options, int class, char *d, int n)
44 for(i = 0; i < n; i++)
45 logger(options, class, "%02hhx ", (char)d[i]);
48 static int setup_enter(void (*log)(int, char *))
53 * from here we could have sensible data in memory
54 * so protect it from being swapped out
56 r = mlockall(MCL_CURRENT | MCL_FUTURE);
58 perror("mlockall failed");
59 log(CRYPT_LOG_ERROR, "WARNING!!! Possibly insecure memory. Are you root?\n");
68 static int setup_leave(void)
70 /* dangerous, we can't wipe all the memory */
78 * Password processing behaviour matrix of process_key
80 * from binary file: check if there is sufficently large key material
81 * interactive & from fd: hash if requested, otherwise crop or pad with '0'
84 static char *process_key(struct crypt_options *options, char *pass, int passLen) {
85 char *key = safe_alloc(options->key_size);
86 memset(key, 0, options->key_size);
88 /* key is coming from binary file */
89 if (options->key_file && strcmp(options->key_file, "-")) {
90 if(passLen < options->key_size) {
91 set_error("Could not read %d bytes from key file",
96 memcpy(key,pass,options->key_size);
100 /* key is coming from tty, fd or binary stdin */
102 if (hash(NULL, options->hash,
103 key, options->key_size,
109 } else if (passLen > options->key_size) {
110 memcpy(key, pass, options->key_size);
112 memcpy(key, pass, passLen);
118 static int get_device_infos(const char *device, struct device_infos *infos)
122 unsigned long size_small;
127 /* Try to open read-write to check whether it is a read-only device */
128 fd = open(device, O_RDWR);
130 if (errno == EROFS) {
132 fd = open(device, O_RDONLY);
136 fd = open(device, O_RDONLY);
139 set_error("Error opening device: %s",
140 strerror_r(errno, buf, 128));
145 /* If the device can be opened read-write, i.e. readonly is still 0, then
146 * check whether BKROGET says that it is read-only. E.g. read-only loop
147 * devices may be openend read-write but are read-only according to BLKROGET
150 if (ioctl(fd, BLKROGET, &readonly) < 0) {
151 set_error("BLKROGET failed on device: %s",
152 strerror_r(errno, buf, 128));
157 #error BLKROGET not available
161 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
162 size >>= SECTOR_SHIFT;
169 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
170 size = (uint64_t)size_small;
175 # error Need at least the BLKGETSIZE ioctl!
178 set_error("BLKGETSIZE ioctl failed on device: %s",
179 strerror_r(errno, buf, 128));
184 infos->readonly = readonly;
190 static int wipe_device_header(const char *device, int sectors)
193 int size = sectors * SECTOR_SIZE;
197 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
199 set_error("Can't wipe header on device %s", device);
203 buffer = malloc(size);
208 memset(buffer, 0, size);
210 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
218 static int parse_into_name_and_mode(const char *nameAndMode, char *name,
221 /* Token content stringification, see info cpp/stringification */
223 #define xstr(s) str(s)
224 #define scanpattern1 "%" xstr(LUKS_CIPHERNAME_L) "[^-]-%" xstr(LUKS_CIPHERMODE_L) "s"
225 #define scanpattern2 "%" xstr(LUKS_CIPHERNAME_L) "[^-]"
229 if(sscanf(nameAndMode,scanpattern1, name, mode) != 2) {
230 if((r = sscanf(nameAndMode,scanpattern2,name)) == 1) {
231 strncpy(mode,"cbc-plain",10);
234 set_error("no known cipher-spec pattern detected");
247 static int keyslot_is_valid(int keySlotIndex, struct crypt_options *options)
249 if(keySlotIndex >= LUKS_NUMKEYS || keySlotIndex < 0) {
250 logger(options,CRYPT_LOG_ERROR,"Key slot %d is invalid, please pick between 0 and %d.\n", keySlotIndex, LUKS_NUMKEYS - 1);
257 /* Select free keyslot or verifies that the one specified is empty */
258 static int keyslot_from_option(int keySlotOption, struct luks_phdr *hdr, struct crypt_options *options) {
259 if(keySlotOption >= 0) {
260 if(!keyslot_is_valid(keySlotOption, options))
262 else if(hdr->keyblock[keySlotOption].active != LUKS_KEY_DISABLED) {
263 logger(options,CRYPT_LOG_ERROR,"Key slot %d is full, please pick another one", keySlotOption);
266 return keySlotOption;
270 /* Find empty key slot */
271 for(i=0; i<LUKS_NUMKEYS; i++) {
272 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED) break;
274 if(i==LUKS_NUMKEYS) {
275 logger(options,CRYPT_LOG_ERROR,"All slots full");
282 static int __crypt_create_device(int reload, struct crypt_options *options)
284 struct device_infos infos;
287 char *processed_key = NULL;
290 r = dm_status_device(options->name);
296 set_error("Device %s already exists.", options->name);
303 if (options->key_size < 0 || options->key_size > 1024) {
304 set_error("Invalid key size");
308 if (get_device_infos(options->device, &infos) < 0)
311 if (!options->size) {
312 options->size = infos.size;
313 if (!options->size) {
314 set_error("Not a block device");
317 if (options->size <= options->offset) {
318 set_error("Invalid offset");
321 options->size -= options->offset;
325 options->flags |= CRYPT_FLAG_READONLY;
327 get_key("Enter passphrase: ", &key, &keyLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags);
329 set_error("Key reading error");
333 processed_key = process_key(options,key,keyLen);
336 if (!processed_key) {
337 const char *error=get_error();
339 char *c_error_handling_sucks = NULL;
340 if (asprintf(&c_error_handling_sucks,"Key processing error: %s",error) > 0)
341 set_error(c_error_handling_sucks);
342 free(c_error_handling_sucks);
344 set_error("Key processing error");
348 r = dm_create_device(options->name, options->device, options->cipher,
349 NULL, options->size, options->skip, options->offset,
350 options->key_size, processed_key,
351 options->flags & CRYPT_FLAG_READONLY, reload);
353 safe_free(processed_key);
358 static int __crypt_query_device(int details, struct crypt_options *options)
362 r = dm_status_device(options->name);
366 r = dm_query_device(options->name, (char **)&options->device, &options->size,
367 &options->skip, &options->offset, (char **)&options->cipher,
368 &options->key_size, NULL, &read_only);
374 options->flags |= CRYPT_FLAG_READONLY;
376 options->flags |= CRYPT_FLAG_FREE_DEVICE;
377 options->flags |= CRYPT_FLAG_FREE_CIPHER;
382 static int __crypt_resize_device(int details, struct crypt_options *options)
384 char *device, *cipher, *key = NULL;
385 uint64_t size, skip, offset;
386 int key_size, read_only, r;
387 struct device_infos infos;
389 r = dm_query_device(options->name, &device, &size, &skip, &offset,
390 &cipher, &key_size, &key, &read_only);
394 if (get_device_infos(device, &infos) < 0)
397 if (!options->size) {
398 options->size = infos.size;
399 if (!options->size) {
400 set_error("Not a block device");
403 if (options->size <= offset) {
404 set_error("Invalid offset");
407 options->size -= offset;
409 size = options->size;
412 options->flags |= CRYPT_FLAG_READONLY;
414 r = dm_create_device(options->name, device, cipher, NULL, size, skip, offset,
415 key_size, key, read_only, 1);
424 static int __crypt_remove_device(int arg, struct crypt_options *options)
428 r = dm_status_device(options->name);
432 set_error("Device busy");
436 return dm_remove_device(options->name, 0, 0);
439 static int __crypt_luks_format(int arg, struct crypt_options *options)
443 struct luks_phdr header;
444 struct luks_masterkey *mk=NULL;
446 char cipherName[LUKS_CIPHERNAME_L];
447 char cipherMode[LUKS_CIPHERMODE_L];
448 unsigned int passwordLen;
449 unsigned int PBKDF2perSecond = 0;
452 if (!LUKS_device_ready(options->device, O_RDWR | O_EXCL))
455 mk = LUKS_generate_masterkey(options->key_size);
456 if(NULL == mk) return -ENOMEM; // FIXME This may be misleading, since we don't know what went wrong
459 #define printoffset(entry) \
460 logger(options, CRYPT_LOG_ERROR, \
461 "offset of " #entry " = %d\n", (char *)(&header.entry)-(char *)(&header))
463 logger(options, CRYPT_LOG_ERROR,
464 "sizeof phdr %d, sizeof key slot %d\n",
465 sizeof(struct luks_phdr),
466 sizeof(header.keyblock[0]));
469 printoffset(version);
470 printoffset(cipherName);
471 printoffset(cipherMode);
472 printoffset(hashSpec);
473 printoffset(payloadOffset);
474 printoffset(keyBytes);
475 printoffset(mkDigest);
476 printoffset(mkDigestSalt);
477 printoffset(mkDigestIterations);
481 r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
484 r = LUKS_generate_phdr(&header, mk, cipherName, cipherMode, options->hash, LUKS_STRIPES, options->align_payload);
487 keyIndex = keyslot_from_option(options->key_slot, &header, options);
488 if(keyIndex == -EINVAL) {
489 r = -EINVAL; goto out;
492 r = LUKS_benchmarkt_iterations(options->hash, &PBKDF2perSecond);
495 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
497 logger(options, CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
499 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
501 r = -EINVAL; goto out;
504 /* Wipe first 8 sectors - fs magic numbers etc. */
505 r = wipe_device_header(options->device, 8);
508 /* Set key, also writes phdr */
509 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk);
514 LUKS_dealloc_masterkey(mk);
519 static int __crypt_luks_open(int arg, struct crypt_options *options)
521 struct luks_masterkey *mk=NULL;
522 struct luks_phdr hdr;
525 unsigned int passwordLen;
526 struct device_infos infos;
527 char *dmCipherSpec = NULL;
528 int r, tries = options->tries;
529 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
531 r = dm_status_device(options->name);
533 set_error("Device %s already exists.", options->name);
537 if (!LUKS_device_ready(options->device, O_RDONLY | excl))
540 if (get_device_infos(options->device, &infos) < 0) {
541 set_error("Can't get device information.\n");
546 options->flags |= CRYPT_FLAG_READONLY;
548 if(asprintf(&prompt, "Enter LUKS passphrase for %s: ", options->device) < 0)
554 if(options->passphrase) {
555 passwordLen = strlen(options->passphrase);
556 password = safe_alloc(passwordLen + 1);
557 strncpy(password, options->passphrase, passwordLen + 1);
559 } else if(get_key(prompt, &password, &passwordLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags))
565 r = -EINVAL; goto out;
568 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk);
570 set_error("No key available with this passphrase.\n");
574 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
577 options->offset = hdr.payloadOffset;
578 if (asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode) < 0) {
582 options->cipher = dmCipherSpec;
583 options->key_size = mk->keyLength;
586 options->size = infos.size;
587 if (!options->size) {
588 set_error("Not a block device.\n");
589 r = -ENOTBLK; goto out2;
591 if (options->size <= options->offset) {
592 set_error("Invalid offset");
593 r = -EINVAL; goto out2;
595 options->size -= options->offset;
596 /* FIXME: code allows multiple crypt mapping, cannot use uuid then.
597 * anyway, it is dangerous and can corrupt data. Remove it in next version! */
598 r = dm_create_device(options->name, options->device, options->cipher,
599 excl ? hdr.uuid : NULL, options->size,
600 0, options->offset, mk->keyLength, mk->key,
601 options->flags & CRYPT_FLAG_READONLY, 0);
609 LUKS_dealloc_masterkey(mk);
610 if (r == -EPERM && tries > 0)
618 static int __crypt_luks_add_key(int arg, struct crypt_options *options)
620 struct luks_masterkey *mk=NULL;
621 struct luks_phdr hdr;
622 char *password=NULL; unsigned int passwordLen;
623 unsigned int keyIndex;
624 unsigned int PBKDF2perSecond = 0;
625 const char *device = options->device;
628 if (!LUKS_device_ready(options->device, O_RDWR))
631 r = LUKS_read_phdr(device, &hdr);
635 keyIndex = keyslot_from_option(options->key_slot, &hdr, options);
636 if(keyIndex == -EINVAL) {
637 r = -EINVAL; goto out;
640 get_key("Enter any LUKS passphrase: ",
645 options->passphrase_fd,
647 options->flags & ~(CRYPT_FLAG_VERIFY | CRYPT_FLAG_VERIFY_IF_POSSIBLE));
650 r = -EINVAL; goto out;
652 r = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk);
654 options->icb->log(CRYPT_LOG_ERROR,"No key available with this passphrase.\n");
655 r = -EPERM; goto out;
657 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
661 get_key("Enter new passphrase for key slot: ",
665 options->new_key_file,
666 options->passphrase_fd,
670 r = -EINVAL; goto out;
673 r = LUKS_benchmarkt_iterations(hdr.hashSpec, &PBKDF2perSecond);
675 hdr.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000));
677 r = LUKS_set_key(device, keyIndex, password, passwordLen, &hdr, mk);
683 LUKS_dealloc_masterkey(mk);
687 static int luks_remove_helper(int arg, struct crypt_options *options, int supply_it)
689 struct luks_masterkey *mk;
690 struct luks_phdr hdr;
692 unsigned int passwordLen;
693 const char *device = options->device;
698 if (!LUKS_device_ready(options->device, O_RDWR))
702 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file,
703 options->passphrase_fd, options->timeout, options->flags);
705 r = -EINVAL; goto out;
708 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk);
710 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
711 r = -EPERM; goto out;
713 logger(options, CRYPT_LOG_NORMAL,"key slot %d selected for deletion.\n", keyIndex);
718 keyIndex = options->key_slot;
719 if (!keyslot_is_valid(keyIndex, options)) {
720 r = -EINVAL; goto out;
724 last_slot = LUKS_is_last_keyslot(options->device, keyIndex);
725 if(last_slot && !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
726 r = -EINVAL; goto out;
729 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
730 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
731 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
733 r = -EINVAL; goto out;
736 r = LUKS_read_phdr(device, &hdr);
738 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
743 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
745 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk);
747 if (openedIndex >= 0) {
748 LUKS_dealloc_masterkey(mk);
751 if(openedIndex < 0) {
752 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
753 r = -EPERM; goto out;
755 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
757 r = LUKS_del_key(device, keyIndex);
766 static int __crypt_luks_kill_slot(int arg, struct crypt_options *options) {
767 return luks_remove_helper(arg, options, 0);
770 static int __crypt_luks_remove_key(int arg, struct crypt_options *options) {
771 return luks_remove_helper(arg, options, 1);
775 static int crypt_job(int (*job)(int arg, struct crypt_options *options),
776 int arg, struct crypt_options *options)
780 if (setup_enter(options->icb->log) < 0) {
785 r = job(arg, options);
795 int crypt_create_device(struct crypt_options *options)
797 return crypt_job(__crypt_create_device, 0, options);
800 int crypt_update_device(struct crypt_options *options)
802 return crypt_job(__crypt_create_device, 1, options);
805 int crypt_resize_device(struct crypt_options *options)
807 return crypt_job(__crypt_resize_device, 0, options);
810 int crypt_query_device(struct crypt_options *options)
812 return crypt_job(__crypt_query_device, 1, options);
815 int crypt_remove_device(struct crypt_options *options)
817 return crypt_job(__crypt_remove_device, 0, options);
821 int crypt_luksFormat(struct crypt_options *options)
823 return crypt_job(__crypt_luks_format, 0, options);
826 int crypt_luksOpen(struct crypt_options *options)
828 return crypt_job(__crypt_luks_open, 0, options);
831 int crypt_luksKillSlot(struct crypt_options *options)
833 return crypt_job(__crypt_luks_kill_slot, 0, options);
836 int crypt_luksRemoveKey(struct crypt_options *options)
838 return crypt_job(__crypt_luks_remove_key, 0, options);
841 int crypt_luksAddKey(struct crypt_options *options)
843 return crypt_job(__crypt_luks_add_key, 0, options);
846 int crypt_luksUUID(struct crypt_options *options)
848 struct luks_phdr hdr;
851 r = LUKS_read_phdr(options->device,&hdr);
854 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
855 options->icb->log(CRYPT_LOG_NORMAL,"\n");
859 int crypt_isLuks(struct crypt_options *options)
861 struct luks_phdr hdr;
862 return LUKS_read_phdr(options->device,&hdr);
865 int crypt_luksDump(struct crypt_options *options)
867 struct luks_phdr hdr;
870 r = LUKS_read_phdr(options->device,&hdr);
873 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
874 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
875 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
876 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
877 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
878 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
879 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
880 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
881 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
882 logger(options, CRYPT_LOG_NORMAL, "\n");
883 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
884 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
885 logger(options, CRYPT_LOG_NORMAL, "\n \t");
886 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
887 logger(options, CRYPT_LOG_NORMAL, "\n");
888 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
889 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
890 for(i=0;i<LUKS_NUMKEYS;i++) {
891 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
892 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
893 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
894 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
895 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
896 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
897 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
898 logger(options, CRYPT_LOG_NORMAL, "\n");
900 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
901 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
904 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
910 void crypt_get_error(char *buf, size_t size)
912 const char *error = get_error();
914 if (!buf || size < 1)
917 strncpy(buf, error, size - 1);
918 buf[size - 1] = '\0';
924 void crypt_put_options(struct crypt_options *options)
926 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
927 free((char *)options->device);
928 options->device = NULL;
929 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
931 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
932 free((char *)options->cipher);
933 options->cipher = NULL;
934 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
938 const char *crypt_get_dir(void)