14 #include "libcryptsetup.h"
24 #define at_least_one(a) ({ __typeof__(a) __at_least_one=(a); (__at_least_one)?__at_least_one:1; })
26 static void logger(struct crypt_options *options, int class, char *format, ...) {
30 va_start(argp, format);
32 if (vasprintf(&target, format, argp) > 0)
33 options->icb->log(class, target);
39 static void hexprintICB(struct crypt_options *options, int class, char *d, int n)
42 for(i = 0; i < n; i++)
43 logger(options, class, "%02hhx ", (char)d[i]);
47 * Password processing behaviour matrix of process_key
49 * from binary file: check if there is sufficently large key material
50 * interactive & from fd: hash if requested, otherwise crop or pad with '0'
53 static char *process_key(struct crypt_options *options, char *pass, int passLen) {
54 char *key = safe_alloc(options->key_size);
55 memset(key, 0, options->key_size);
57 /* key is coming from binary file */
58 if (options->key_file && strcmp(options->key_file, "-")) {
59 if(passLen < options->key_size) {
60 set_error("Could not read %d bytes from key file",
65 memcpy(key,pass,options->key_size);
69 /* key is coming from tty, fd or binary stdin */
71 if (hash(NULL, options->hash,
72 key, options->key_size,
78 } else if (passLen > options->key_size) {
79 memcpy(key, pass, options->key_size);
81 memcpy(key, pass, passLen);
87 static int get_device_infos(const char *device, struct device_infos *infos)
91 unsigned long size_small;
96 /* Try to open read-write to check whether it is a read-only device */
97 fd = open(device, O_RDWR);
101 fd = open(device, O_RDONLY);
105 fd = open(device, O_RDONLY);
108 set_error("Error opening device: %s",
109 strerror_r(errno, buf, 128));
114 /* If the device can be opened read-write, i.e. readonly is still 0, then
115 * check whether BKROGET says that it is read-only. E.g. read-only loop
116 * devices may be openend read-write but are read-only according to BLKROGET
119 if (ioctl(fd, BLKROGET, &readonly) < 0) {
120 set_error("BLKROGET failed on device: %s",
121 strerror_r(errno, buf, 128));
126 #error BLKROGET not available
130 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
131 size >>= SECTOR_SHIFT;
138 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
139 size = (uint64_t)size_small;
144 # error Need at least the BLKGETSIZE ioctl!
147 set_error("BLKGETSIZE ioctl failed on device: %s",
148 strerror_r(errno, buf, 128));
153 infos->readonly = readonly;
159 static int wipe_device_header(const char *device, int sectors)
162 int size = sectors * SECTOR_SIZE;
166 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
168 set_error("Can't wipe header on device %s", device);
172 buffer = malloc(size);
177 memset(buffer, 0, size);
179 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
187 static int parse_into_name_and_mode(const char *nameAndMode, char *name,
190 /* Token content stringification, see info cpp/stringification */
192 #define xstr(s) str(s)
193 #define scanpattern1 "%" xstr(LUKS_CIPHERNAME_L) "[^-]-%" xstr(LUKS_CIPHERMODE_L) "s"
194 #define scanpattern2 "%" xstr(LUKS_CIPHERNAME_L) "[^-]"
198 if(sscanf(nameAndMode,scanpattern1, name, mode) != 2) {
199 if((r = sscanf(nameAndMode,scanpattern2,name)) == 1) {
200 strncpy(mode,"cbc-plain",10);
203 set_error("no known cipher-spec pattern detected");
216 static int keyslot_is_valid(int keySlotIndex, struct crypt_options *options)
218 if(keySlotIndex >= LUKS_NUMKEYS || keySlotIndex < 0) {
219 logger(options,CRYPT_LOG_ERROR,"Key slot %d is invalid, please pick between 0 and %d.\n", keySlotIndex, LUKS_NUMKEYS - 1);
226 /* Select free keyslot or verifies that the one specified is empty */
227 static int keyslot_from_option(int keySlotOption, struct luks_phdr *hdr, struct crypt_options *options) {
228 if(keySlotOption >= 0) {
229 if(!keyslot_is_valid(keySlotOption, options))
231 else if(hdr->keyblock[keySlotOption].active != LUKS_KEY_DISABLED) {
232 logger(options,CRYPT_LOG_ERROR,"Key slot %d is full, please pick another one", keySlotOption);
235 return keySlotOption;
239 /* Find empty key slot */
240 for(i=0; i<LUKS_NUMKEYS; i++) {
241 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED) break;
243 if(i==LUKS_NUMKEYS) {
244 logger(options,CRYPT_LOG_ERROR,"All slots full");
251 static int __crypt_create_device(int reload, struct crypt_options *options)
253 struct device_infos infos;
256 char *processed_key = NULL;
259 r = dm_status_device(options->name);
265 set_error("Device %s already exists.", options->name);
272 if (options->key_size < 0 || options->key_size > 1024) {
273 set_error("Invalid key size");
277 if (get_device_infos(options->device, &infos) < 0)
280 if (!options->size) {
281 options->size = infos.size;
282 if (!options->size) {
283 set_error("Not a block device");
286 if (options->size <= options->offset) {
287 set_error("Invalid offset");
290 options->size -= options->offset;
294 options->flags |= CRYPT_FLAG_READONLY;
296 get_key("Enter passphrase: ", &key, &keyLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags);
298 set_error("Key reading error");
302 processed_key = process_key(options,key,keyLen);
305 if (!processed_key) {
306 const char *error=get_error();
308 char *c_error_handling_sucks = NULL;
309 if (asprintf(&c_error_handling_sucks,"Key processing error: %s",error) > 0)
310 set_error(c_error_handling_sucks);
311 free(c_error_handling_sucks);
313 set_error("Key processing error");
317 r = dm_create_device(options->name, options->device, options->cipher,
318 NULL, options->size, options->skip, options->offset,
319 options->key_size, processed_key,
320 options->flags & CRYPT_FLAG_READONLY, reload);
322 safe_free(processed_key);
327 static int __crypt_query_device(int details, struct crypt_options *options)
331 r = dm_status_device(options->name);
335 r = dm_query_device(options->name, (char **)&options->device, &options->size,
336 &options->skip, &options->offset, (char **)&options->cipher,
337 &options->key_size, NULL, &read_only);
343 options->flags |= CRYPT_FLAG_READONLY;
345 options->flags |= CRYPT_FLAG_FREE_DEVICE;
346 options->flags |= CRYPT_FLAG_FREE_CIPHER;
351 static int __crypt_resize_device(int details, struct crypt_options *options)
353 char *device, *cipher, *key = NULL;
354 uint64_t size, skip, offset;
355 int key_size, read_only, r;
356 struct device_infos infos;
358 r = dm_query_device(options->name, &device, &size, &skip, &offset,
359 &cipher, &key_size, &key, &read_only);
363 if (get_device_infos(device, &infos) < 0)
366 if (!options->size) {
367 options->size = infos.size;
368 if (!options->size) {
369 set_error("Not a block device");
372 if (options->size <= offset) {
373 set_error("Invalid offset");
376 options->size -= offset;
378 size = options->size;
381 options->flags |= CRYPT_FLAG_READONLY;
383 r = dm_create_device(options->name, device, cipher, NULL, size, skip, offset,
384 key_size, key, read_only, 1);
393 static int __crypt_remove_device(int arg, struct crypt_options *options)
397 r = dm_status_device(options->name);
401 set_error("Device busy");
405 return dm_remove_device(options->name, 0, 0);
408 static int __crypt_luks_format(int arg, struct crypt_options *options)
412 struct luks_phdr header;
413 struct luks_masterkey *mk=NULL;
415 char cipherName[LUKS_CIPHERNAME_L];
416 char cipherMode[LUKS_CIPHERMODE_L];
417 unsigned int passwordLen;
418 unsigned int PBKDF2perSecond = 0;
421 if (!LUKS_device_ready(options->device, O_RDWR | O_EXCL))
424 mk = LUKS_generate_masterkey(options->key_size);
425 if(NULL == mk) return -ENOMEM; // FIXME This may be misleading, since we don't know what went wrong
428 #define printoffset(entry) \
429 logger(options, CRYPT_LOG_ERROR, \
430 "offset of " #entry " = %d\n", (char *)(&header.entry)-(char *)(&header))
432 logger(options, CRYPT_LOG_ERROR,
433 "sizeof phdr %d, sizeof key slot %d\n",
434 sizeof(struct luks_phdr),
435 sizeof(header.keyblock[0]));
438 printoffset(version);
439 printoffset(cipherName);
440 printoffset(cipherMode);
441 printoffset(hashSpec);
442 printoffset(payloadOffset);
443 printoffset(keyBytes);
444 printoffset(mkDigest);
445 printoffset(mkDigestSalt);
446 printoffset(mkDigestIterations);
450 r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
453 r = LUKS_generate_phdr(&header, mk, cipherName, cipherMode, options->hash, LUKS_STRIPES, options->align_payload);
456 keyIndex = keyslot_from_option(options->key_slot, &header, options);
457 if(keyIndex == -EINVAL) {
458 r = -EINVAL; goto out;
461 r = LUKS_benchmarkt_iterations(options->hash, &PBKDF2perSecond);
464 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
466 logger(options, CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
468 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
470 r = -EINVAL; goto out;
473 /* Wipe first 8 sectors - fs magic numbers etc. */
474 r = wipe_device_header(options->device, 8);
477 /* Set key, also writes phdr */
478 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk);
483 LUKS_dealloc_masterkey(mk);
488 static int __crypt_luks_open(int arg, struct crypt_options *options)
490 struct luks_masterkey *mk=NULL;
491 struct luks_phdr hdr;
494 unsigned int passwordLen;
495 struct device_infos infos;
496 char *dmCipherSpec = NULL;
497 int r, tries = options->tries;
498 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
500 r = dm_status_device(options->name);
502 set_error("Device %s already exists.", options->name);
506 if (!LUKS_device_ready(options->device, O_RDONLY | excl))
509 if (get_device_infos(options->device, &infos) < 0) {
510 set_error("Can't get device information.\n");
515 options->flags |= CRYPT_FLAG_READONLY;
517 if(asprintf(&prompt, "Enter LUKS passphrase for %s: ", options->device) < 0)
523 if(options->passphrase) {
524 passwordLen = strlen(options->passphrase);
525 password = safe_alloc(passwordLen + 1);
526 strncpy(password, options->passphrase, passwordLen + 1);
528 } else if(get_key(prompt, &password, &passwordLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags))
534 r = -EINVAL; goto out;
537 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk);
539 set_error("No key available with this passphrase.\n");
543 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
546 options->offset = hdr.payloadOffset;
547 if (asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode) < 0) {
551 options->cipher = dmCipherSpec;
552 options->key_size = mk->keyLength;
555 options->size = infos.size;
556 if (!options->size) {
557 set_error("Not a block device.\n");
558 r = -ENOTBLK; goto out2;
560 if (options->size <= options->offset) {
561 set_error("Invalid offset");
562 r = -EINVAL; goto out2;
564 options->size -= options->offset;
565 /* FIXME: code allows multiple crypt mapping, cannot use uuid then.
566 * anyway, it is dangerous and can corrupt data. Remove it in next version! */
567 r = dm_create_device(options->name, options->device, options->cipher,
568 excl ? hdr.uuid : NULL, options->size,
569 0, options->offset, mk->keyLength, mk->key,
570 options->flags & CRYPT_FLAG_READONLY, 0);
578 LUKS_dealloc_masterkey(mk);
579 if (r == -EPERM && tries > 0)
587 static int __crypt_luks_add_key(int arg, struct crypt_options *options)
589 struct luks_masterkey *mk=NULL;
590 struct luks_phdr hdr;
591 char *password=NULL; unsigned int passwordLen;
592 unsigned int keyIndex;
593 unsigned int PBKDF2perSecond = 0;
594 const char *device = options->device;
597 if (!LUKS_device_ready(options->device, O_RDWR))
600 r = LUKS_read_phdr(device, &hdr);
604 keyIndex = keyslot_from_option(options->key_slot, &hdr, options);
605 if(keyIndex == -EINVAL) {
606 r = -EINVAL; goto out;
609 get_key("Enter any LUKS passphrase: ",
614 options->passphrase_fd,
616 options->flags & ~(CRYPT_FLAG_VERIFY | CRYPT_FLAG_VERIFY_IF_POSSIBLE));
619 r = -EINVAL; goto out;
621 r = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk);
623 options->icb->log(CRYPT_LOG_ERROR,"No key available with this passphrase.\n");
624 r = -EPERM; goto out;
626 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
630 get_key("Enter new passphrase for key slot: ",
634 options->new_key_file,
635 options->passphrase_fd,
639 r = -EINVAL; goto out;
642 r = LUKS_benchmarkt_iterations(hdr.hashSpec, &PBKDF2perSecond);
644 hdr.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000));
646 r = LUKS_set_key(device, keyIndex, password, passwordLen, &hdr, mk);
652 LUKS_dealloc_masterkey(mk);
656 static int luks_remove_helper(int arg, struct crypt_options *options, int supply_it)
658 struct luks_masterkey *mk;
659 struct luks_phdr hdr;
661 unsigned int passwordLen;
662 const char *device = options->device;
667 if (!LUKS_device_ready(options->device, O_RDWR))
671 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file,
672 options->passphrase_fd, options->timeout, options->flags);
674 r = -EINVAL; goto out;
677 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk);
679 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
680 r = -EPERM; goto out;
682 logger(options, CRYPT_LOG_NORMAL,"key slot %d selected for deletion.\n", keyIndex);
687 keyIndex = options->key_slot;
688 if (!keyslot_is_valid(keyIndex, options)) {
689 r = -EINVAL; goto out;
693 last_slot = LUKS_is_last_keyslot(options->device, keyIndex);
694 if(last_slot && !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
695 r = -EINVAL; goto out;
698 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
699 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
700 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
702 r = -EINVAL; goto out;
705 r = LUKS_read_phdr(device, &hdr);
707 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
712 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
714 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk);
716 if (openedIndex >= 0) {
717 LUKS_dealloc_masterkey(mk);
720 if(openedIndex < 0) {
721 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
722 r = -EPERM; goto out;
724 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
726 r = LUKS_del_key(device, keyIndex);
735 static int __crypt_luks_kill_slot(int arg, struct crypt_options *options) {
736 return luks_remove_helper(arg, options, 0);
739 static int __crypt_luks_remove_key(int arg, struct crypt_options *options) {
740 return luks_remove_helper(arg, options, 1);
743 static int crypt_job(int (*job)(int arg, struct crypt_options *options),
744 int arg, struct crypt_options *options)
748 r = job(arg, options);
756 int crypt_create_device(struct crypt_options *options)
758 return crypt_job(__crypt_create_device, 0, options);
761 int crypt_update_device(struct crypt_options *options)
763 return crypt_job(__crypt_create_device, 1, options);
766 int crypt_resize_device(struct crypt_options *options)
768 return crypt_job(__crypt_resize_device, 0, options);
771 int crypt_query_device(struct crypt_options *options)
773 return crypt_job(__crypt_query_device, 1, options);
776 int crypt_remove_device(struct crypt_options *options)
778 return crypt_job(__crypt_remove_device, 0, options);
782 int crypt_luksFormat(struct crypt_options *options)
784 return crypt_job(__crypt_luks_format, 0, options);
787 int crypt_luksOpen(struct crypt_options *options)
789 return crypt_job(__crypt_luks_open, 0, options);
792 int crypt_luksKillSlot(struct crypt_options *options)
794 return crypt_job(__crypt_luks_kill_slot, 0, options);
797 int crypt_luksRemoveKey(struct crypt_options *options)
799 return crypt_job(__crypt_luks_remove_key, 0, options);
802 int crypt_luksAddKey(struct crypt_options *options)
804 return crypt_job(__crypt_luks_add_key, 0, options);
807 int crypt_luksUUID(struct crypt_options *options)
809 struct luks_phdr hdr;
812 r = LUKS_read_phdr(options->device,&hdr);
815 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
816 options->icb->log(CRYPT_LOG_NORMAL,"\n");
820 int crypt_isLuks(struct crypt_options *options)
822 struct luks_phdr hdr;
823 return LUKS_read_phdr(options->device,&hdr);
826 int crypt_luksDump(struct crypt_options *options)
828 struct luks_phdr hdr;
831 r = LUKS_read_phdr(options->device,&hdr);
834 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
835 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
836 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
837 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
838 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
839 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
840 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
841 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
842 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
843 logger(options, CRYPT_LOG_NORMAL, "\n");
844 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
845 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
846 logger(options, CRYPT_LOG_NORMAL, "\n \t");
847 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
848 logger(options, CRYPT_LOG_NORMAL, "\n");
849 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
850 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
851 for(i=0;i<LUKS_NUMKEYS;i++) {
852 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
853 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
854 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
855 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
856 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
857 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
858 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
859 logger(options, CRYPT_LOG_NORMAL, "\n");
861 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
862 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
865 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
871 void crypt_get_error(char *buf, size_t size)
873 const char *error = get_error();
875 if (!buf || size < 1)
878 strncpy(buf, error, size - 1);
879 buf[size - 1] = '\0';
885 void crypt_put_options(struct crypt_options *options)
887 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
888 free((char *)options->device);
889 options->device = NULL;
890 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
892 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
893 free((char *)options->cipher);
894 options->cipher = NULL;
895 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
899 const char *crypt_get_dir(void)