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 %s already exists.", options->name);
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))
446 mk = LUKS_generate_masterkey(options->key_size);
447 if(NULL == mk) return -ENOMEM; // FIXME This may be misleading, since we don't know what went wrong
450 #define printoffset(entry) logger(options, CRYPT_LOG_ERROR, ("offset of " #entry " = %d\n", (char *)(&header.entry)-(char *)(&header))
452 logger(options, CRYPT_LOG_ERROR, "sizeof phdr %d, key slot %d\n",sizeof(struct luks_phdr),sizeof(header.keyblock[0]));
455 printoffset(version);
456 printoffset(cipherName);
457 printoffset(cipherMode);
458 printoffset(hashSpec);
459 printoffset(payloadOffset);
460 printoffset(keyBytes);
461 printoffset(mkDigest);
462 printoffset(mkDigestSalt);
463 printoffset(mkDigestIterations);
467 r = parse_into_name_and_mode(options->cipher, cipherName, cipherMode);
470 r = LUKS_generate_phdr(&header,mk,cipherName, cipherMode,LUKS_STRIPES, options->align_payload);
472 set_error("Can't generate phdr");
476 keyIndex = keyslot_from_option(options->key_slot, &header, options);
477 if(keyIndex == -EINVAL) {
478 r = -EINVAL; goto out;
481 PBKDF2perSecond = LUKS_benchmarkt_iterations();
482 header.keyblock[keyIndex].passwordIterations = at_least_one(PBKDF2perSecond * ((float)options->iteration_time / 1000.0));
484 logger(options->icb->log,CRYPT_LOG_ERROR, "pitr %d\n", header.keyblock[0].passwordIterations);
486 get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
488 r = -EINVAL; goto out;
491 /* Wipe first 8 sectors - fs magic numbers etc. */
492 r = wipe_device_header(options->device, 8);
495 /* Set key, also writes phdr */
496 r = LUKS_set_key(options->device, keyIndex, password, passwordLen, &header, mk, backend);
501 LUKS_dealloc_masterkey(mk);
506 static int __crypt_luks_open(int arg, struct setup_backend *backend, struct crypt_options *options)
508 struct luks_masterkey *mk=NULL;
509 struct luks_phdr hdr;
511 unsigned int passwordLen;
512 struct device_infos infos;
513 struct crypt_options tmp = {
514 .name = options->name,
517 int r, tries = options->tries;
518 int excl = (options->flags & CRYPT_FLAG_NON_EXCLUSIVE_ACCESS) ? 0 : O_EXCL ;
520 r = backend->status(0, &tmp, NULL);
522 set_error("Device %s already exists.", options->name);
526 if (!LUKS_device_ready(options->device, O_RDONLY | excl))
529 if (get_device_infos(options->device, &infos) < 0) {
530 set_error("Can't get device information.\n");
535 options->flags |= CRYPT_FLAG_READONLY;
540 if(get_key("Enter LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags))
546 r = -EINVAL; goto out;
549 r = LUKS_open_any_key(options->device, password, passwordLen, &hdr, &mk, backend);
551 set_error("No key available with this passphrase.\n");
555 logger(options, CRYPT_LOG_NORMAL,"key slot %d unlocked.\n", r);
558 options->offset = hdr.payloadOffset;
559 asprintf(&dmCipherSpec, "%s-%s", hdr.cipherName, hdr.cipherMode);
564 options->cipher = dmCipherSpec;
565 options->key_size = mk->keyLength;
568 options->size = infos.size;
569 if (!options->size) {
570 set_error("Not a block device.\n");
571 r = -ENOTBLK; goto out2;
573 if (options->size <= options->offset) {
574 set_error("Invalid offset");
575 r = -EINVAL; goto out2;
577 options->size -= options->offset;
578 r = backend->create(0, options, mk->key);
585 LUKS_dealloc_masterkey(mk);
586 if (r == -EPERM && tries > 0)
592 static int __crypt_luks_add_key(int arg, struct setup_backend *backend, struct crypt_options *options)
594 struct luks_masterkey *mk=NULL;
595 struct luks_phdr hdr;
596 char *password=NULL; unsigned int passwordLen;
597 unsigned int keyIndex;
598 const char *device = options->device;
601 if (!LUKS_device_ready(options->device, O_RDWR))
604 r = LUKS_read_phdr(device, &hdr);
608 keyIndex = keyslot_from_option(options->key_slot, &hdr, options);
609 if(keyIndex == -EINVAL) {
610 r = -EINVAL; goto out;
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;
669 if (!LUKS_device_ready(options->device, O_RDWR))
673 get_key("Enter LUKS passphrase to be deleted: ",&password,&passwordLen, 0, options->new_key_file, options->passphrase_fd, options->timeout, options->flags);
675 r = -EINVAL; goto out;
677 keyIndex = LUKS_open_any_key(device, password, passwordLen, &hdr, &mk, backend);
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);
685 keyIndex = options->key_slot;
688 if(LUKS_is_last_keyslot(options->device, keyIndex) &&
689 !(options->icb->yesDialog(_("This is the last keyslot. Device will become unusable after purging this key.")))) {
694 if(options->flags & CRYPT_FLAG_VERIFY_ON_DELKEY) {
695 options->flags &= ~CRYPT_FLAG_VERIFY_ON_DELKEY;
696 get_key("Enter any remaining LUKS passphrase: ",&password,&passwordLen, 0, options->key_file, options->passphrase_fd, options->timeout, options->flags);
698 r = -EINVAL; goto out;
701 r = LUKS_read_phdr(device, &hdr);
703 options->icb->log(CRYPT_LOG_ERROR,"Failed to access device.\n");
706 hdr.keyblock[keyIndex].active = LUKS_KEY_DISABLED;
708 openedIndex = LUKS_open_any_key_with_hdr(device, password, passwordLen, &hdr, &mk, backend);
710 if (openedIndex >= 0) {
711 LUKS_dealloc_masterkey(mk);
714 if(openedIndex < 0) {
715 options->icb->log(CRYPT_LOG_ERROR,"No remaining key available with this passphrase.\n");
716 r = -EPERM; goto out;
718 logger(options, CRYPT_LOG_NORMAL,"key slot %d verified.\n", openedIndex);
720 r = LUKS_del_key(device, keyIndex);
729 static int __crypt_luks_kill_slot(int arg, struct setup_backend *backend, struct crypt_options *options) {
730 return luks_remove_helper(arg, backend, options, 0);
733 static int __crypt_luks_remove_key(int arg, struct setup_backend *backend, struct crypt_options *options) {
734 return luks_remove_helper(arg, backend, options, 1);
738 static int crypt_job(int (*job)(int arg, struct setup_backend *backend,
739 struct crypt_options *options),
740 int arg, struct crypt_options *options)
742 struct setup_backend *backend;
745 backend = get_setup_backend(default_backend);
747 if (setup_enter(backend,options->icb->log) < 0) {
753 set_error("No setup backend available");
758 r = job(arg, backend, options);
760 setup_leave(backend);
762 put_setup_backend(backend);
770 int crypt_create_device(struct crypt_options *options)
772 return crypt_job(__crypt_create_device, 0, options);
775 int crypt_update_device(struct crypt_options *options)
777 return crypt_job(__crypt_create_device, 1, options);
780 int crypt_resize_device(struct crypt_options *options)
782 return crypt_job(__crypt_resize_device, 0, options);
785 int crypt_query_device(struct crypt_options *options)
787 return crypt_job(__crypt_query_device, 1, options);
790 int crypt_remove_device(struct crypt_options *options)
792 return crypt_job(__crypt_remove_device, 0, options);
796 int crypt_luksFormat(struct crypt_options *options)
798 return crypt_job(__crypt_luks_format, 0, options);
801 int crypt_luksOpen(struct crypt_options *options)
803 return crypt_job(__crypt_luks_open, 0, options);
806 int crypt_luksKillSlot(struct crypt_options *options)
808 return crypt_job(__crypt_luks_kill_slot, 0, options);
811 int crypt_luksRemoveKey(struct crypt_options *options)
813 return crypt_job(__crypt_luks_remove_key, 0, options);
816 int crypt_luksAddKey(struct crypt_options *options)
818 return crypt_job(__crypt_luks_add_key, 0, options);
821 int crypt_luksUUID(struct crypt_options *options)
823 struct luks_phdr hdr;
826 r = LUKS_read_phdr(options->device,&hdr);
829 options->icb->log(CRYPT_LOG_NORMAL,hdr.uuid);
830 options->icb->log(CRYPT_LOG_NORMAL,"\n");
834 int crypt_isLuks(struct crypt_options *options)
836 struct luks_phdr hdr;
837 return LUKS_read_phdr(options->device,&hdr);
840 int crypt_luksDump(struct crypt_options *options)
842 struct luks_phdr hdr;
845 r = LUKS_read_phdr(options->device,&hdr);
848 logger(options, CRYPT_LOG_NORMAL, "LUKS header information for %s\n\n",options->device);
849 logger(options, CRYPT_LOG_NORMAL, "Version: \t%d\n",hdr.version);
850 logger(options, CRYPT_LOG_NORMAL, "Cipher name: \t%s\n",hdr.cipherName);
851 logger(options, CRYPT_LOG_NORMAL, "Cipher mode: \t%s\n",hdr.cipherMode);
852 logger(options, CRYPT_LOG_NORMAL, "Hash spec: \t%s\n",hdr.hashSpec);
853 logger(options, CRYPT_LOG_NORMAL, "Payload offset:\t%d\n",hdr.payloadOffset);
854 logger(options, CRYPT_LOG_NORMAL, "MK bits: \t%d\n",hdr.keyBytes*8);
855 logger(options, CRYPT_LOG_NORMAL, "MK digest: \t");
856 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigest,LUKS_DIGESTSIZE);
857 logger(options, CRYPT_LOG_NORMAL, "\n");
858 logger(options, CRYPT_LOG_NORMAL, "MK salt: \t");
859 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt,LUKS_SALTSIZE/2);
860 logger(options, CRYPT_LOG_NORMAL, "\n \t");
861 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.mkDigestSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
862 logger(options, CRYPT_LOG_NORMAL, "\n");
863 logger(options, CRYPT_LOG_NORMAL, "MK iterations: \t%d\n",hdr.mkDigestIterations);
864 logger(options, CRYPT_LOG_NORMAL, "UUID: \t%s\n\n",hdr.uuid);
865 for(i=0;i<LUKS_NUMKEYS;i++) {
866 if(hdr.keyblock[i].active == LUKS_KEY_ENABLED) {
867 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: ENABLED\n",i);
868 logger(options, CRYPT_LOG_NORMAL, "\tIterations: \t%d\n",hdr.keyblock[i].passwordIterations);
869 logger(options, CRYPT_LOG_NORMAL, "\tSalt: \t");
870 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt,LUKS_SALTSIZE/2);
871 logger(options, CRYPT_LOG_NORMAL, "\n\t \t");
872 hexprintICB(options, CRYPT_LOG_NORMAL, hdr.keyblock[i].passwordSalt+LUKS_SALTSIZE/2,LUKS_SALTSIZE/2);
873 logger(options, CRYPT_LOG_NORMAL, "\n");
875 logger(options, CRYPT_LOG_NORMAL, "\tKey material offset:\t%d\n",hdr.keyblock[i].keyMaterialOffset);
876 logger(options, CRYPT_LOG_NORMAL, "\tAF stripes: \t%d\n",hdr.keyblock[i].stripes);
879 logger(options, CRYPT_LOG_NORMAL, "Key Slot %d: DISABLED\n",i);
885 void crypt_get_error(char *buf, size_t size)
887 const char *error = get_error();
889 if (!buf || size < 1)
892 strncpy(buf, error, size - 1);
893 buf[size - 1] = '\0';
899 void crypt_put_options(struct crypt_options *options)
901 if (options->flags & CRYPT_FLAG_FREE_DEVICE) {
902 free((char *)options->device);
903 options->device = NULL;
904 options->flags &= ~CRYPT_FLAG_FREE_DEVICE;
906 if (options->flags & CRYPT_FLAG_FREE_CIPHER) {
907 free((char *)options->cipher);
908 options->cipher = NULL;
909 options->flags &= ~CRYPT_FLAG_FREE_CIPHER;
913 void crypt_set_default_backend(const char *backend)
916 free(default_backend);
918 default_backend = strdup(backend);
920 default_backend = NULL;
923 const char *crypt_get_dir(void)
925 struct setup_backend *backend;
928 backend = get_setup_backend(default_backend);
932 dir = backend->dir();
934 put_setup_backend(backend);
941 // indent-tabs-mode: nil