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) {
260 if(keySlotOption != -1) {
261 if(keySlotOption >= LUKS_NUMKEYS) {
262 set_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 set_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 set_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);
480 PBKDF2perSecond = LUKS_benchmarkt_iterations();
481 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
483 logger(options->icb->log,CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
485 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
487 r = -EINVAL; goto out;
490 /* Wipe first 8 sectors - fs magic numbers etc. */
491 r = wipe_device_header(options->device, 8);
494 /* Set key, also writes phdr */
495 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk, backend);
500 LUKS_dealloc_masterkey(mk);
505 static int __crypt_luks_open(int arg, struct setup_backend *backend, struct crypt_options *options)
507 struct luks_masterkey *mk=NULL;
508 struct luks_phdr hdr;
510 unsigned int passwordLen;
511 struct device_infos infos;
512 struct crypt_options tmp = {
513 .name = options->name,
516 int r, tries = options->tries;
517 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
519 r = backend->status(0, &tmp, NULL);
521 set_error("Device already exists");
525 if (!LUKS_device_ready(options->device, O_RDONLY | excl)) {
526 set_error("Can not access device");
530 if (get_device_infos(options->device, &infos) < 0) {
531 set_error("Can't get device information.\n");
536 options->flags |= CRYPT_FLAG_READONLY;
541 if(get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags))
547 r = -EINVAL; goto out;
550 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk, backend);
552 set_error("No key available with this passphrase.\n");
556 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
559 options->offset = hdr.payloadOffset;
560 asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode);
565 options->cipher = dmCipherSpec;
566 options->key_size = mk->keyLength;
569 options->size = infos.size;
570 if (!options->size) {
571 set_error("Not a block device.\n");
572 r = -ENOTBLK; goto out2;
574 if (options->size <= options->offset) {
575 set_error("Invalid offset");
576 r = -EINVAL; goto out2;
578 options->size -= options->offset;
579 r = backend->create(0, options, mk->key);
586 LUKS_dealloc_masterkey(mk);
587 if (r == -EPERM && tries > 0)
593 static int __crypt_luks_add_key(int arg, struct setup_backend *backend, struct crypt_options *options)
595 struct luks_masterkey *mk=NULL;
596 struct luks_phdr hdr;
597 char *password=NULL; unsigned int passwordLen;
598 unsigned int keyIndex;
599 const char *device = options->device;
602 if (!LUKS_device_ready(options->device, O_RDWR)) {
603 set_error("Can not access device");
604 r = -ENOTBLK; goto out;
607 r = LUKS_read_phdr(device, &hdr);
611 keyIndex = keyslot_from_option(options->key_slot, &hdr);
613 get_key("Enter any LUKS passphrase: ",
618 options->passphrase_fd,
620 options->flags & ~(CRYPT_FLAG_VERIFY | CRYPT_FLAG_VERIFY_IF_POSSIBLE));
623 r = -EINVAL; goto out;
625 r = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
627 options->icb->log(CRYPT_LOG_ERROR,"No key available with this passphrase.\n");
628 r = -EPERM; goto out;
630 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
634 get_key("Enter new passphrase for key slot: ",
638 options->new_key_file,
639 options->passphrase_fd,
643 r = -EINVAL; goto out;
646 hdr.keyblock[keyIndex].passwordIterations = at_least_one(LUKS_benchmarkt_iterations() * ((float)options->iteration_time / 1000));
648 r = LUKS_set_key(device, keyIndex, password, passwordLen, &hdr, mk, backend);
654 LUKS_dealloc_masterkey(mk);
658 static int luks_remove_helper(int arg, struct setup_backend *backend, struct crypt_options *options, int supply_it)
660 struct luks_masterkey *mk;
661 struct luks_phdr hdr;
663 unsigned int passwordLen;
664 const char *device = options->device;
668 if (!LUKS_device_ready(options->device, O_RDWR)) {
669 set_error("Can not access device");
670 r = -ENOTBLK; goto out;
674 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
676 r = -EINVAL; goto out;
678 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
680 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
681 r = -EPERM; goto out;
683 logger(options, CRYPT_LOG_NORMAL,"key slot %d selected for deletion.\n", keyIndex);
686 keyIndex = options->key_slot;
689 if(LUKS_is_last_keyslot(options->device, keyIndex) &&
690 !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
695 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
696 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
697 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
699 r = -EINVAL; goto out;
702 r = LUKS_read_phdr(device, &hdr);
704 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
707 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
709 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk, backend);
711 if (openedIndex >= 0) {
712 LUKS_dealloc_masterkey(mk);
715 if(openedIndex < 0) {
716 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
717 r = -EPERM; goto out;
719 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
721 r = LUKS_del_key(device, keyIndex);
730 static int __crypt_luks_kill_slot(int arg, struct setup_backend *backend, struct crypt_options *options) {
731 return luks_remove_helper(arg, backend, options, 0);
734 static int __crypt_luks_remove_key(int arg, struct setup_backend *backend, struct crypt_options *options) {
735 return luks_remove_helper(arg, backend, options, 1);
739 static int crypt_job(int (*job)(int arg, struct setup_backend *backend,
740 struct crypt_options *options),
741 int arg, struct crypt_options *options)
743 struct setup_backend *backend;
746 backend = get_setup_backend(default_backend);
748 if (setup_enter(backend,options->icb->log) < 0) {
754 set_error("No setup backend available");
759 r = job(arg, backend, options);
761 setup_leave(backend);
763 put_setup_backend(backend);
771 int crypt_create_device(struct crypt_options *options)
773 return crypt_job(__crypt_create_device, 0, options);
776 int crypt_update_device(struct crypt_options *options)
778 return crypt_job(__crypt_create_device, 1, options);
781 int crypt_resize_device(struct crypt_options *options)
783 return crypt_job(__crypt_resize_device, 0, options);
786 int crypt_query_device(struct crypt_options *options)
788 return crypt_job(__crypt_query_device, 1, options);
791 int crypt_remove_device(struct crypt_options *options)
793 return crypt_job(__crypt_remove_device, 0, options);
797 int crypt_luksFormat(struct crypt_options *options)
799 return crypt_job(__crypt_luks_format, 0, options);
802 int crypt_luksOpen(struct crypt_options *options)
804 return crypt_job(__crypt_luks_open, 0, options);
807 int crypt_luksKillSlot(struct crypt_options *options)
809 return crypt_job(__crypt_luks_kill_slot, 0, options);
812 int crypt_luksRemoveKey(struct crypt_options *options)
814 return crypt_job(__crypt_luks_remove_key, 0, options);
817 int crypt_luksAddKey(struct crypt_options *options)
819 return crypt_job(__crypt_luks_add_key, 0, options);
822 int crypt_luksUUID(struct crypt_options *options)
824 struct luks_phdr hdr;
827 r = LUKS_read_phdr(options->device,&hdr);
830 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
831 options->icb->log(CRYPT_LOG_NORMAL,"\n");
835 int crypt_isLuks(struct crypt_options *options)
837 struct luks_phdr hdr;
838 return LUKS_read_phdr(options->device,&hdr);
841 int crypt_luksDump(struct crypt_options *options)
843 struct luks_phdr hdr;
846 r = LUKS_read_phdr(options->device,&hdr);
849 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
850 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
851 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
852 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
853 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
854 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
855 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
856 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
857 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
858 logger(options, CRYPT_LOG_NORMAL, "\n");
859 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
860 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
861 logger(options, CRYPT_LOG_NORMAL, "\n \t");
862 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
863 logger(options, CRYPT_LOG_NORMAL, "\n");
864 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
865 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
866 for(i=0;i<LUKS_NUMKEYS;i++) {
867 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
868 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
869 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
870 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
871 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
872 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
873 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
874 logger(options, CRYPT_LOG_NORMAL, "\n");
876 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
877 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
880 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
886 void crypt_get_error(char *buf, size_t size)
888 const char *error = get_error();
890 if (!buf || size < 1)
893 strncpy(buf, error, size - 1);
894 buf[size - 1] = '\0';
900 void crypt_put_options(struct crypt_options *options)
902 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
903 free((char *)options->device);
904 options->device = NULL;
905 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
907 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
908 free((char *)options->cipher);
909 options->cipher = NULL;
910 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
914 void crypt_set_default_backend(const char *backend)
917 free(default_backend);
919 default_backend = strdup(backend);
921 default_backend = NULL;
924 const char *crypt_get_dir(void)
926 struct setup_backend *backend;
929 backend = get_setup_backend(default_backend);
933 dir = backend->dir();
935 put_setup_backend(backend);
942 // indent-tabs-mode: nil