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);
34 vasprintf(&target, format, argp);
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(struct setup_backend *backend, 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");
76 static int setup_leave(struct setup_backend *backend)
81 /* dangerous, we can't wipe all the memory */
89 * Password processing behaviour matrix of process_key
91 * from binary file: check if there is sufficently large key material
92 * interactive & from fd: hash if requested, otherwise crop or pad with '0'
95 static char *process_key(struct crypt_options *options, char *pass, int passLen) {
96 char *key = safe_alloc(options->key_size);
97 memset(key, 0, options->key_size);
99 /* key is coming from binary file */
100 if (options->key_file && strcmp(options->key_file, "-")) {
101 if(passLen < options->key_size) {
102 set_error("Could not read %d bytes from key file",
107 memcpy(key,pass,options->key_size);
111 /* key is coming from tty, fd or binary stdin */
113 if (hash(NULL, options->hash,
114 key, options->key_size,
120 } else if (passLen > options->key_size) {
121 memcpy(key, pass, options->key_size);
123 memcpy(key, pass, passLen);
129 static int get_device_infos(const char *device, struct device_infos *infos)
133 unsigned long size_small;
138 /* Try to open read-write to check whether it is a read-only device */
139 fd = open(device, O_RDWR);
141 if (errno == EROFS) {
143 fd = open(device, O_RDONLY);
147 fd = open(device, O_RDONLY);
150 set_error("Error opening device: %s",
151 strerror_r(errno, buf, 128));
156 /* If the device can be opened read-write, i.e. readonly is still 0, then
157 * check whether BKROGET says that it is read-only. E.g. read-only loop
158 * devices may be openend read-write but are read-only according to BLKROGET
161 if (ioctl(fd, BLKROGET, &readonly) < 0) {
162 set_error("BLKROGET failed on device: %s",
163 strerror_r(errno, buf, 128));
168 #error BLKROGET not available
172 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
173 size >>= SECTOR_SHIFT;
180 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
181 size = (uint64_t)size_small;
186 # error Need at least the BLKGETSIZE ioctl!
189 set_error("BLKGETSIZE ioctl failed on device: %s",
190 strerror_r(errno, buf, 128));
195 infos->readonly = readonly;
201 static int wipe_device_header(const char *device, int sectors)
204 int size = sectors * SECTOR_SIZE;
208 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
210 set_error("Can't wipe header on device %s", device);
214 buffer = malloc(size);
219 memset(buffer, 0, size);
221 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
229 static int parse_into_name_and_mode(const char *nameAndMode, char *name,
232 /* Token content stringification, see info cpp/stringification */
234 #define xstr(s) str(s)
235 #define scanpattern1 "%" xstr(LUKS_CIPHERNAME_L) "[^-]-%" xstr(LUKS_CIPHERMODE_L) "s"
236 #define scanpattern2 "%" xstr(LUKS_CIPHERNAME_L) "[^-]"
240 if(sscanf(nameAndMode,scanpattern1, name, mode) != 2) {
241 if((r = sscanf(nameAndMode,scanpattern2,name)) == 1) {
242 strncpy(mode,"cbc-plain",10);
245 set_error("no known cipher-spec pattern detected");
258 /* Select free keyslot or verifies that the one specified is empty */
259 static int keyslot_from_option(int keySlotOption, struct luks_phdr *hdr, struct crypt_options *options) {
260 if(keySlotOption >= 0) {
261 if(keySlotOption >= LUKS_NUMKEYS) {
262 logger(options,CRYPT_LOG_ERROR,"slot %d too high, please pick between 0 and %d", keySlotOption, LUKS_NUMKEYS);
264 } else if(hdr->keyblock[keySlotOption].active != LUKS_KEY_DISABLED) {
265 logger(options,CRYPT_LOG_ERROR,"slot %d full, please pick another one", keySlotOption);
268 return keySlotOption;
272 /* Find empty key slot */
273 for(i=0; i<LUKS_NUMKEYS; i++) {
274 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED) break;
276 if(i==LUKS_NUMKEYS) {
277 logger(options,CRYPT_LOG_ERROR,"All slots full");
284 static int __crypt_create_device(int reload, struct setup_backend *backend,
285 struct crypt_options *options)
287 struct crypt_options tmp = {
288 .name = options->name,
290 struct device_infos infos;
293 char *processed_key = NULL;
296 r = backend->status(0, &tmp, NULL);
302 set_error("Device already exists");
309 if (options->key_size < 0 || options->key_size > 1024) {
310 set_error("Invalid key size");
314 if (get_device_infos(options->device, &infos) < 0)
317 if (!options->size) {
318 options->size = infos.size;
319 if (!options->size) {
320 set_error("Not a block device");
323 if (options->size <= options->offset) {
324 set_error("Invalid offset");
327 options->size -= options->offset;
331 options->flags |= CRYPT_FLAG_READONLY;
333 get_key("Enter passphrase: ", &key, &keyLen, options->key_size, options->key_file, options->passphrase_fd, options->timeout, options->flags);
335 set_error("Key reading error");
339 processed_key = process_key(options,key,keyLen);
342 if (!processed_key) {
343 const char *error=get_error();
345 char *c_error_handling_sucks;
346 asprintf(&c_error_handling_sucks,"Key processing error: %s",error);
347 set_error(c_error_handling_sucks);
348 free(c_error_handling_sucks);
350 set_error("Key processing error");
354 r = backend->create(reload, options, processed_key);
356 safe_free(processed_key);
361 static int __crypt_query_device(int details, struct setup_backend *backend,
362 struct crypt_options *options)
364 int r = backend->status(details, options, NULL);
373 static int __crypt_resize_device(int details, struct setup_backend *backend,
374 struct crypt_options *options)
376 struct crypt_options tmp = {
377 .name = options->name,
379 struct device_infos infos;
383 r = backend->status(1, &tmp, &key);
387 if (get_device_infos(tmp.device, &infos) < 0)
390 if (!options->size) {
391 options->size = infos.size;
392 if (!options->size) {
393 set_error("Not a block device");
396 if (options->size <= tmp.offset) {
397 set_error("Invalid offset");
400 options->size -= tmp.offset;
402 tmp.size = options->size;
405 options->flags |= CRYPT_FLAG_READONLY;
407 r = backend->create(1, &tmp, key);
414 static int __crypt_remove_device(int arg, struct setup_backend *backend,
415 struct crypt_options *options)
419 r = backend->status(0, options, NULL);
423 set_error("Device busy");
427 return backend->remove(0, options);
430 static int __crypt_luks_format(int arg, struct setup_backend *backend, struct crypt_options *options)
434 struct luks_phdr header;
435 struct luks_masterkey *mk=NULL;
437 char cipherName[LUKS_CIPHERNAME_L];
438 char cipherMode[LUKS_CIPHERMODE_L];
439 unsigned int passwordLen;
443 if (!LUKS_device_ready(options->device, O_RDWR | O_EXCL)) {
444 set_error("Can not access device");
445 r = -ENOTBLK; goto out;
448 mk = LUKS_generate_masterkey(options->key_size);
449 if(NULL == mk) return -ENOMEM; // FIXME This may be misleading, since we don't know what went wrong
452 #define printoffset(entry) logger(options, CRYPT_LOG_ERROR, ("offset of " #entry " = %d\n", (char *)(&header.entry)-(char *)(&header))
454 logger(options, CRYPT_LOG_ERROR, "sizeof phdr %d, key slot %d\n",sizeof(struct luks_phdr),sizeof(header.keyblock[0]));
457 printoffset(version);
458 printoffset(cipherName);
459 printoffset(cipherMode);
460 printoffset(hashSpec);
461 printoffset(payloadOffset);
462 printoffset(keyBytes);
463 printoffset(mkDigest);
464 printoffset(mkDigestSalt);
465 printoffset(mkDigestIterations);
469 r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
472 r = LUKS_generate_phdr(&header,mk,cipherName, cipherMode,LUKS_STRIPES, options->align_payload);
474 set_error("Can't generate phdr");
478 keyIndex = keyslot_from_option(options->key_slot, &header, options);
479 if(keyIndex == -EINVAL) {
480 r = -EINVAL; goto out;
483 PBKDF2perSecond = LUKS_benchmarkt_iterations();
484 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
486 logger(options->icb->log,CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
488 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
490 r = -EINVAL; goto out;
493 /* Wipe first 8 sectors - fs magic numbers etc. */
494 r = wipe_device_header(options->device, 8);
497 /* Set key, also writes phdr */
498 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk, backend);
503 LUKS_dealloc_masterkey(mk);
508 static int __crypt_luks_open(int arg, struct setup_backend *backend, struct crypt_options *options)
510 struct luks_masterkey *mk=NULL;
511 struct luks_phdr hdr;
513 unsigned int passwordLen;
514 struct device_infos infos;
515 struct crypt_options tmp = {
516 .name = options->name,
519 int r, tries = options->tries;
520 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
522 r = backend->status(0, &tmp, NULL);
524 set_error("Device already exists");
528 if (!LUKS_device_ready(options->device, O_RDONLY | excl)) {
529 set_error("Can not access device");
533 if (get_device_infos(options->device, &infos) < 0) {
534 set_error("Can't get device information.\n");
539 options->flags |= CRYPT_FLAG_READONLY;
544 if(get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags))
550 r = -EINVAL; goto out;
553 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk, backend);
555 set_error("No key available with this passphrase.\n");
559 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
562 options->offset = hdr.payloadOffset;
563 asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode);
568 options->cipher = dmCipherSpec;
569 options->key_size = mk->keyLength;
572 options->size = infos.size;
573 if (!options->size) {
574 set_error("Not a block device.\n");
575 r = -ENOTBLK; goto out2;
577 if (options->size <= options->offset) {
578 set_error("Invalid offset");
579 r = -EINVAL; goto out2;
581 options->size -= options->offset;
582 r = backend->create(0, options, mk->key);
589 LUKS_dealloc_masterkey(mk);
590 if (r == -EPERM && tries > 0)
596 static int __crypt_luks_add_key(int arg, struct setup_backend *backend, struct crypt_options *options)
598 struct luks_masterkey *mk=NULL;
599 struct luks_phdr hdr;
600 char *password=NULL; unsigned int passwordLen;
601 unsigned int keyIndex;
602 const char *device = options->device;
605 if (!LUKS_device_ready(options->device, O_RDWR)) {
606 set_error("Can not access device");
607 r = -ENOTBLK; goto out;
610 r = LUKS_read_phdr(device, &hdr);
614 keyIndex = keyslot_from_option(options->key_slot, &hdr, options);
615 if(keyIndex == -EINVAL) {
616 r = -EINVAL; goto out;
619 get_key("Enter any LUKS passphrase: ",
624 options->passphrase_fd,
626 options->flags & ~(CRYPT_FLAG_VERIFY | CRYPT_FLAG_VERIFY_IF_POSSIBLE));
629 r = -EINVAL; goto out;
631 r = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
633 options->icb->log(CRYPT_LOG_ERROR,"No key available with this passphrase.\n");
634 r = -EPERM; goto out;
636 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
640 get_key("Enter new passphrase for key slot: ",
644 options->new_key_file,
645 options->passphrase_fd,
649 r = -EINVAL; goto out;
652 hdr.keyblock[keyIndex].passwordIterations = at_least_one(LUKS_benchmarkt_iterations() * ((float)options->iteration_time / 1000));
654 r = LUKS_set_key(device, keyIndex, password, passwordLen, &hdr, mk, backend);
660 LUKS_dealloc_masterkey(mk);
664 static int luks_remove_helper(int arg, struct setup_backend *backend, struct crypt_options *options, int supply_it)
666 struct luks_masterkey *mk;
667 struct luks_phdr hdr;
669 unsigned int passwordLen;
670 const char *device = options->device;
674 if (!LUKS_device_ready(options->device, O_RDWR)) {
675 set_error("Can not access device");
676 r = -ENOTBLK; goto out;
680 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
682 r = -EINVAL; goto out;
684 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
686 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
687 r = -EPERM; goto out;
689 logger(options, CRYPT_LOG_NORMAL,"key slot %d selected for deletion.\n", keyIndex);
692 keyIndex = options->key_slot;
695 if(LUKS_is_last_keyslot(options->device, keyIndex) &&
696 !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
701 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
702 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
703 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
705 r = -EINVAL; goto out;
708 r = LUKS_read_phdr(device, &hdr);
710 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
713 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
715 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk, backend);
717 if (openedIndex >= 0) {
718 LUKS_dealloc_masterkey(mk);
721 if(openedIndex < 0) {
722 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
723 r = -EPERM; goto out;
725 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
727 r = LUKS_del_key(device, keyIndex);
736 static int __crypt_luks_kill_slot(int arg, struct setup_backend *backend, struct crypt_options *options) {
737 return luks_remove_helper(arg, backend, options, 0);
740 static int __crypt_luks_remove_key(int arg, struct setup_backend *backend, struct crypt_options *options) {
741 return luks_remove_helper(arg, backend, options, 1);
745 static int crypt_job(int (*job)(int arg, struct setup_backend *backend,
746 struct crypt_options *options),
747 int arg, struct crypt_options *options)
749 struct setup_backend *backend;
752 backend = get_setup_backend(default_backend);
754 if (setup_enter(backend,options->icb->log) < 0) {
760 set_error("No setup backend available");
765 r = job(arg, backend, options);
767 setup_leave(backend);
769 put_setup_backend(backend);
777 int crypt_create_device(struct crypt_options *options)
779 return crypt_job(__crypt_create_device, 0, options);
782 int crypt_update_device(struct crypt_options *options)
784 return crypt_job(__crypt_create_device, 1, options);
787 int crypt_resize_device(struct crypt_options *options)
789 return crypt_job(__crypt_resize_device, 0, options);
792 int crypt_query_device(struct crypt_options *options)
794 return crypt_job(__crypt_query_device, 1, options);
797 int crypt_remove_device(struct crypt_options *options)
799 return crypt_job(__crypt_remove_device, 0, options);
803 int crypt_luksFormat(struct crypt_options *options)
805 return crypt_job(__crypt_luks_format, 0, options);
808 int crypt_luksOpen(struct crypt_options *options)
810 return crypt_job(__crypt_luks_open, 0, options);
813 int crypt_luksKillSlot(struct crypt_options *options)
815 return crypt_job(__crypt_luks_kill_slot, 0, options);
818 int crypt_luksRemoveKey(struct crypt_options *options)
820 return crypt_job(__crypt_luks_remove_key, 0, options);
823 int crypt_luksAddKey(struct crypt_options *options)
825 return crypt_job(__crypt_luks_add_key, 0, options);
828 int crypt_luksUUID(struct crypt_options *options)
830 struct luks_phdr hdr;
833 r = LUKS_read_phdr(options->device,&hdr);
836 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
837 options->icb->log(CRYPT_LOG_NORMAL,"\n");
841 int crypt_isLuks(struct crypt_options *options)
843 struct luks_phdr hdr;
844 return LUKS_read_phdr(options->device,&hdr);
847 int crypt_luksDump(struct crypt_options *options)
849 struct luks_phdr hdr;
852 r = LUKS_read_phdr(options->device,&hdr);
855 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
856 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
857 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
858 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
859 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
860 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
861 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
862 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
863 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
864 logger(options, CRYPT_LOG_NORMAL, "\n");
865 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
866 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
867 logger(options, CRYPT_LOG_NORMAL, "\n \t");
868 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
869 logger(options, CRYPT_LOG_NORMAL, "\n");
870 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
871 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
872 for(i=0;i<LUKS_NUMKEYS;i++) {
873 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
874 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
875 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
876 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
877 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
878 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
879 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
880 logger(options, CRYPT_LOG_NORMAL, "\n");
882 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
883 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
886 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
892 void crypt_get_error(char *buf, size_t size)
894 const char *error = get_error();
896 if (!buf || size < 1)
899 strncpy(buf, error, size - 1);
900 buf[size - 1] = '\0';
906 void crypt_put_options(struct crypt_options *options)
908 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
909 free((char *)options->device);
910 options->device = NULL;
911 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
913 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
914 free((char *)options->cipher);
915 options->cipher = NULL;
916 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
920 void crypt_set_default_backend(const char *backend)
923 free(default_backend);
925 default_backend = strdup(backend);
927 default_backend = NULL;
930 const char *crypt_get_dir(void)
932 struct setup_backend *backend;
935 backend = get_setup_backend(default_backend);
939 dir = backend->dir();
941 put_setup_backend(backend);
948 // indent-tabs-mode: nil