2 * LUKS - Linux Unified Key Setup
4 * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2013-2014, Milan Broz
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <sys/types.h>
25 #include <netinet/in.h>
34 #include <uuid/uuid.h>
40 /* Get size of struct luks_phdr with all keyslots material space */
41 static size_t LUKS_device_sectors(size_t keyLen)
43 size_t keyslot_sectors, sector;
46 keyslot_sectors = AF_split_sectors(keyLen, LUKS_STRIPES);
47 sector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
49 for (i = 0; i < LUKS_NUMKEYS; i++) {
50 sector = size_round_up(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
51 sector += keyslot_sectors;
57 int LUKS_keyslot_area(struct luks_phdr *hdr,
62 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
65 *offset = hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
66 *length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;
71 static int LUKS_check_device_size(struct crypt_device *ctx, size_t keyLength)
73 struct device *device = crypt_metadata_device(ctx);
74 uint64_t dev_sectors, hdr_sectors;
79 if(device_size(device, &dev_sectors)) {
80 log_dbg("Cannot get device size for device %s.", device_path(device));
84 dev_sectors >>= SECTOR_SHIFT;
85 hdr_sectors = LUKS_device_sectors(keyLength);
86 log_dbg("Key length %zu, device size %" PRIu64 " sectors, header size %"
87 PRIu64 " sectors.",keyLength, dev_sectors, hdr_sectors);
89 if (hdr_sectors > dev_sectors) {
90 log_err(ctx, _("Device %s is too small. (LUKS requires at least %" PRIu64 " bytes.)\n"),
91 device_path(device), hdr_sectors * SECTOR_SIZE);
98 /* Check keyslot to prevent access outside of header and keyslot area */
99 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
101 uint32_t secs_per_stripes;
103 /* First sectors is the header itself */
104 if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
105 log_dbg("Invalid offset %u in keyslot %u.",
106 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
110 /* Ignore following check for detached header where offset can be zero. */
111 if (phdr->payloadOffset == 0)
114 if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
115 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
116 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
117 phdr->payloadOffset);
121 secs_per_stripes = AF_split_sectors(phdr->keyBytes, phdr->keyblock[keyIndex].stripes);
123 if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
124 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
125 "keyslot %u (beyond data area offset %u).",
127 phdr->keyblock[keyIndex].keyMaterialOffset,
128 phdr->keyblock[keyIndex].stripes,
129 keyIndex, phdr->payloadOffset);
136 static const char *dbg_slot_state(crypt_keyslot_info ki)
139 case CRYPT_SLOT_INACTIVE:
141 case CRYPT_SLOT_ACTIVE:
143 case CRYPT_SLOT_ACTIVE_LAST:
144 return "ACTIVE_LAST";
145 case CRYPT_SLOT_INVALID:
151 int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
153 struct device *device = crypt_metadata_device(ctx);
154 struct luks_phdr hdr;
155 int r = 0, devfd = -1;
160 r = LUKS_read_phdr(&hdr, 1, 0, ctx);
164 hdr_size = LUKS_device_sectors(hdr.keyBytes) << SECTOR_SHIFT;
165 buffer_size = size_round_up(hdr_size, crypt_getpagesize());
167 buffer = crypt_safe_alloc(buffer_size);
168 if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
173 log_dbg("Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
174 sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);
176 log_dbg("Output backup file size: %zu bytes.", buffer_size);
178 devfd = device_open(device, O_RDONLY);
180 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device_path(device));
185 if (read_blockwise(devfd, device_block_size(device), buffer, hdr_size) < hdr_size) {
191 /* Wipe unused area, so backup cannot contain old signatures */
192 if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
193 memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));
195 devfd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
198 log_err(ctx, _("Requested header backup file %s already exists.\n"), backup_file);
200 log_err(ctx, _("Cannot create header backup file %s.\n"), backup_file);
204 if (write(devfd, buffer, buffer_size) < buffer_size) {
205 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
215 crypt_memzero(&hdr, sizeof(hdr));
216 crypt_safe_free(buffer);
220 int LUKS_hdr_restore(
221 const char *backup_file,
222 struct luks_phdr *hdr,
223 struct crypt_device *ctx)
225 struct device *device = crypt_metadata_device(ctx);
226 int r = 0, devfd = -1, diff_uuid = 0;
227 ssize_t buffer_size = 0;
228 char *buffer = NULL, msg[200];
229 struct luks_phdr hdr_file;
231 r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
236 buffer_size = LUKS_device_sectors(hdr_file.keyBytes) << SECTOR_SHIFT;
238 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
239 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
244 buffer = crypt_safe_alloc(buffer_size);
250 devfd = open(backup_file, O_RDONLY);
252 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
257 if (read(devfd, buffer, buffer_size) < buffer_size) {
258 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
264 r = LUKS_read_phdr(hdr, 0, 0, ctx);
266 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
267 if(hdr->payloadOffset != hdr_file.payloadOffset ||
268 hdr->keyBytes != hdr_file.keyBytes) {
269 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
273 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
277 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
278 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
279 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
280 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
285 if (!crypt_confirm(ctx, msg)) {
290 log_dbg("Storing backup of header (%zu bytes) and keyslot area (%zu bytes) to device %s.",
291 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
293 devfd = device_open(device, O_RDWR);
296 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
297 device_path(device));
299 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
304 if (write_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
310 /* Be sure to reload new data */
311 r = LUKS_read_phdr(hdr, 1, 0, ctx);
315 crypt_safe_free(buffer);
319 /* This routine should do some just basic recovery for known problems. */
320 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
322 struct luks_phdr temp_phdr;
323 const unsigned char *sector = (const unsigned char*)phdr;
324 struct volume_key *vk;
325 uint64_t PBKDF2_per_sec = 1;
326 int i, bad, r, need_write = 0;
328 if (phdr->keyBytes != 16 && phdr->keyBytes != 32 && phdr->keyBytes != 64) {
329 log_err(ctx, _("Non standard key size, manual repair required.\n"));
332 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
333 if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
334 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
338 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
340 log_verbose(ctx, _("Repairing keyslots.\n"));
342 log_dbg("Generating second header with the same parameters for check.");
343 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
344 /* payloadOffset - cannot check */
345 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
346 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
347 phdr->payloadOffset, 0,
351 log_err(ctx, _("Repair failed."));
355 for(i = 0; i < LUKS_NUMKEYS; ++i) {
356 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
357 log_dbg("Skipping repair for active keyslot %i.", i);
362 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
363 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
364 (unsigned)phdr->keyblock[i].keyMaterialOffset,
365 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
366 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
370 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
371 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
372 (unsigned)phdr->keyblock[i].stripes,
373 (unsigned)temp_phdr.keyblock[i].stripes);
374 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
378 /* Known case - MSDOS partition table signature */
379 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
380 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
385 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
386 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
387 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
388 phdr->keyblock[i].passwordIterations = 0;
396 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
397 r = LUKS_write_phdr(phdr, ctx);
400 crypt_free_volume_key(vk);
401 crypt_memzero(&temp_phdr, sizeof(temp_phdr));
405 static int _check_and_convert_hdr(const char *device,
406 struct luks_phdr *hdr,
407 int require_luks_device,
409 struct crypt_device *ctx)
413 char luksMagic[] = LUKS_MAGIC;
415 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
416 log_dbg("LUKS header not detected.");
417 if (require_luks_device)
418 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
420 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
421 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
425 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
426 if (crypt_hmac_size(hdr->hashSpec) < LUKS_DIGESTSIZE) {
427 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
431 /* Header detected */
432 hdr->payloadOffset = ntohl(hdr->payloadOffset);
433 hdr->keyBytes = ntohl(hdr->keyBytes);
434 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
436 for(i = 0; i < LUKS_NUMKEYS; ++i) {
437 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
438 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
439 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
440 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
441 if (LUKS_check_keyslot_size(hdr, i)) {
442 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
447 /* Avoid unterminated strings */
448 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
449 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
450 hdr->uuid[UUID_STRING_L - 1] = '\0';
454 r = _keyslot_repair(hdr, ctx);
456 log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
462 static void _to_lower(char *str, unsigned max_len)
464 for(; *str && max_len; str++, max_len--)
466 *str = tolower(*str);
469 static void LUKS_fix_header_compatible(struct luks_phdr *header)
471 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
472 * so always convert hash to lower case in header */
473 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
475 /* ECB mode does not use IV but dmcrypt silently allows it.
476 * Drop any IV here if ECB is used (that is not secure anyway).*/
477 if (!strncmp(header->cipherMode, "ecb-", 4)) {
478 memset(header->cipherMode, 0, LUKS_CIPHERMODE_L);
479 strcpy(header->cipherMode, "ecb");
483 int LUKS_read_phdr_backup(const char *backup_file,
484 struct luks_phdr *hdr,
485 int require_luks_device,
486 struct crypt_device *ctx)
488 ssize_t hdr_size = sizeof(struct luks_phdr);
489 int devfd = 0, r = 0;
491 log_dbg("Reading LUKS header of size %d from backup file %s",
492 (int)hdr_size, backup_file);
494 devfd = open(backup_file, O_RDONLY);
496 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
500 if (read(devfd, hdr, hdr_size) < hdr_size)
503 LUKS_fix_header_compatible(hdr);
504 r = _check_and_convert_hdr(backup_file, hdr,
505 require_luks_device, 0, ctx);
512 int LUKS_read_phdr(struct luks_phdr *hdr,
513 int require_luks_device,
515 struct crypt_device *ctx)
517 struct device *device = crypt_metadata_device(ctx);
518 ssize_t hdr_size = sizeof(struct luks_phdr);
519 int devfd = 0, r = 0;
521 /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
522 assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
524 /* Stripes count cannot be changed without additional code fixes yet */
525 assert(LUKS_STRIPES == 4000);
527 if (repair && !require_luks_device)
530 log_dbg("Reading LUKS header of size %zu from device %s",
531 hdr_size, device_path(device));
533 devfd = device_open(device, O_RDONLY);
535 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
539 if (read_blockwise(devfd, device_block_size(device), hdr, hdr_size) < hdr_size)
542 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
546 r = LUKS_check_device_size(ctx, hdr->keyBytes);
552 int LUKS_write_phdr(struct luks_phdr *hdr,
553 struct crypt_device *ctx)
555 struct device *device = crypt_metadata_device(ctx);
556 ssize_t hdr_size = sizeof(struct luks_phdr);
559 struct luks_phdr convHdr;
562 log_dbg("Updating LUKS header of size %zu on device %s",
563 sizeof(struct luks_phdr), device_path(device));
565 r = LUKS_check_device_size(ctx, hdr->keyBytes);
569 devfd = device_open(device, O_RDWR);
572 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
573 device_path(device));
575 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
579 memcpy(&convHdr, hdr, hdr_size);
580 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
582 /* Convert every uint16/32_t item to network byte order */
583 convHdr.version = htons(hdr->version);
584 convHdr.payloadOffset = htonl(hdr->payloadOffset);
585 convHdr.keyBytes = htonl(hdr->keyBytes);
586 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
587 for(i = 0; i < LUKS_NUMKEYS; ++i) {
588 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
589 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
590 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
591 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
594 r = write_blockwise(devfd, device_block_size(device), &convHdr, hdr_size) < hdr_size ? -EIO : 0;
596 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device_path(device));
599 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
601 r = LUKS_read_phdr(hdr, 1, 0, ctx);
603 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"),
604 device_path(device));
610 /* Check that kernel supports requested cipher by decryption of one sector */
611 static int LUKS_check_cipher(struct luks_phdr *hdr, struct crypt_device *ctx)
614 struct volume_key *empty_key;
615 char buf[SECTOR_SIZE];
617 log_dbg("Checking if cipher %s-%s is usable.", hdr->cipherName, hdr->cipherMode);
619 empty_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
623 r = LUKS_decrypt_from_storage(buf, sizeof(buf),
624 hdr->cipherName, hdr->cipherMode,
627 crypt_free_volume_key(empty_key);
628 crypt_memzero(buf, sizeof(buf));
632 int LUKS_generate_phdr(struct luks_phdr *header,
633 const struct volume_key *vk,
634 const char *cipherName, const char *cipherMode, const char *hashSpec,
635 const char *uuid, unsigned int stripes,
636 unsigned int alignPayload,
637 unsigned int alignOffset,
638 uint32_t iteration_time_ms,
639 uint64_t *PBKDF2_per_sec,
640 int detached_metadata_device,
641 struct crypt_device *ctx)
643 unsigned int i = 0, hdr_sectors = LUKS_device_sectors(vk->keylength);
644 size_t blocksPerStripeSet, currentSector;
646 uuid_t partitionUuid;
647 char luksMagic[] = LUKS_MAGIC;
649 /* For separate metadata device allow zero alignment */
650 if (alignPayload == 0 && !detached_metadata_device)
651 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
653 if (alignPayload && detached_metadata_device && alignPayload < hdr_sectors) {
654 log_err(ctx, _("Data offset for detached LUKS header must be "
655 "either 0 or higher than header size (%d sectors).\n"),
660 if (crypt_hmac_size(hashSpec) < LUKS_DIGESTSIZE) {
661 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
665 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
666 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
670 uuid_generate(partitionUuid);
672 memset(header,0,sizeof(struct luks_phdr));
675 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
677 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
678 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
679 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
681 header->keyBytes=vk->keylength;
683 LUKS_fix_header_compatible(header);
685 r = LUKS_check_cipher(header, ctx);
689 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
690 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
693 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
695 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
699 r = crypt_benchmark_kdf(ctx, "pbkdf2", header->hashSpec,
700 "foo", 3, "bar", 3, PBKDF2_per_sec);
702 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"),
707 /* Compute master key digest */
708 iteration_time_ms /= 8;
709 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
710 LUKS_MKD_ITERATIONS_MIN);
712 r = crypt_pbkdf("pbkdf2", header->hashSpec, vk->key,vk->keylength,
713 header->mkDigestSalt, LUKS_SALTSIZE,
714 header->mkDigest,LUKS_DIGESTSIZE,
715 header->mkDigestIterations);
717 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
722 currentSector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
723 blocksPerStripeSet = AF_split_sectors(vk->keylength, stripes);
724 for(i = 0; i < LUKS_NUMKEYS; ++i) {
725 header->keyblock[i].active = LUKS_KEY_DISABLED;
726 header->keyblock[i].keyMaterialOffset = currentSector;
727 header->keyblock[i].stripes = stripes;
728 currentSector = size_round_up(currentSector + blocksPerStripeSet,
729 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
732 if (detached_metadata_device) {
733 /* for separate metadata device use alignPayload directly */
734 header->payloadOffset = alignPayload;
736 /* alignOffset - offset from natural device alignment provided by topology info */
737 currentSector = size_round_up(currentSector, alignPayload);
738 header->payloadOffset = currentSector + alignOffset;
741 uuid_unparse(partitionUuid, header->uuid);
743 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
744 header->payloadOffset, header->uuid, header->mkDigestIterations);
749 int LUKS_hdr_uuid_set(
750 struct luks_phdr *hdr,
752 struct crypt_device *ctx)
754 uuid_t partitionUuid;
756 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
757 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
761 uuid_generate(partitionUuid);
763 uuid_unparse(partitionUuid, hdr->uuid);
765 return LUKS_write_phdr(hdr, ctx);
768 int LUKS_set_key(unsigned int keyIndex,
769 const char *password, size_t passwordLen,
770 struct luks_phdr *hdr, struct volume_key *vk,
771 uint32_t iteration_time_ms,
772 uint64_t *PBKDF2_per_sec,
773 struct crypt_device *ctx)
775 struct volume_key *derived_key;
778 uint64_t PBKDF2_temp;
781 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
782 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
786 /* LUKS keyslot has always at least 4000 stripes accoding to specification */
787 if(hdr->keyblock[keyIndex].stripes < 4000) {
788 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
793 log_dbg("Calculating data for key slot %d", keyIndex);
795 r = crypt_benchmark_kdf(ctx, "pbkdf2", hdr->hashSpec,
796 "foo", 3, "bar", 3, PBKDF2_per_sec);
798 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"),
804 * Avoid floating point operation
805 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
807 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
809 if (PBKDF2_temp > UINT32_MAX)
810 PBKDF2_temp = UINT32_MAX;
811 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
812 LUKS_SLOT_ITERATIONS_MIN);
814 log_dbg("Key slot %d use %" PRIu32 " password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
816 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
820 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
821 LUKS_SALTSIZE, CRYPT_RND_SALT);
825 r = crypt_pbkdf("pbkdf2", hdr->hashSpec, password, passwordLen,
826 hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
827 derived_key->key, hdr->keyBytes,
828 hdr->keyblock[keyIndex].passwordIterations);
833 * AF splitting, the masterkey stored in vk->key is split to AfKey
835 assert(vk->keylength == hdr->keyBytes);
836 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
837 AfKey = crypt_safe_alloc(AFEKSize);
843 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
844 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
845 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
849 log_dbg("Updating key slot %d [0x%04x] area.", keyIndex,
850 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
851 /* Encryption via dm */
852 r = LUKS_encrypt_to_storage(AfKey,
854 hdr->cipherName, hdr->cipherMode,
856 hdr->keyblock[keyIndex].keyMaterialOffset,
861 /* Mark the key as active in phdr */
862 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
866 r = LUKS_write_phdr(hdr, ctx);
872 crypt_safe_free(AfKey);
873 crypt_free_volume_key(derived_key);
877 /* Check whether a volume key is invalid. */
878 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
879 const struct volume_key *vk)
881 char checkHashBuf[LUKS_DIGESTSIZE];
883 if (crypt_pbkdf("pbkdf2", hdr->hashSpec, vk->key, vk->keylength,
884 hdr->mkDigestSalt, LUKS_SALTSIZE,
885 checkHashBuf, LUKS_DIGESTSIZE,
886 hdr->mkDigestIterations) < 0)
889 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
895 /* Try to open a particular key slot */
896 static int LUKS_open_key(unsigned int keyIndex,
897 const char *password,
899 struct luks_phdr *hdr,
900 struct volume_key *vk,
901 struct crypt_device *ctx)
903 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
904 struct volume_key *derived_key;
909 log_dbg("Trying to open key slot %d [%s].", keyIndex,
912 if (ki < CRYPT_SLOT_ACTIVE)
915 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
919 assert(vk->keylength == hdr->keyBytes);
920 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
921 AfKey = crypt_safe_alloc(AFEKSize);
927 r = crypt_pbkdf("pbkdf2", hdr->hashSpec, password, passwordLen,
928 hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
929 derived_key->key, hdr->keyBytes,
930 hdr->keyblock[keyIndex].passwordIterations);
934 log_dbg("Reading key slot %d area.", keyIndex);
935 r = LUKS_decrypt_from_storage(AfKey,
937 hdr->cipherName, hdr->cipherMode,
939 hdr->keyblock[keyIndex].keyMaterialOffset,
944 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
948 r = LUKS_verify_volume_key(hdr, vk);
950 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
952 crypt_safe_free(AfKey);
953 crypt_free_volume_key(derived_key);
957 int LUKS_open_key_with_hdr(int keyIndex,
958 const char *password,
960 struct luks_phdr *hdr,
961 struct volume_key **vk,
962 struct crypt_device *ctx)
967 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
970 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, *vk, ctx);
971 return (r < 0) ? r : keyIndex;
974 for(i = 0; i < LUKS_NUMKEYS; i++) {
975 r = LUKS_open_key(i, password, passwordLen, hdr, *vk, ctx);
979 /* Do not retry for errors that are no -EPERM or -ENOENT,
980 former meaning password wrong, latter key slot inactive */
981 if ((r != -EPERM) && (r != -ENOENT))
984 /* Warning, early returns above */
985 log_err(ctx, _("No key available with this passphrase.\n"));
989 int LUKS_del_key(unsigned int keyIndex,
990 struct luks_phdr *hdr,
991 struct crypt_device *ctx)
993 struct device *device = crypt_metadata_device(ctx);
994 unsigned int startOffset, endOffset;
997 r = LUKS_read_phdr(hdr, 1, 0, ctx);
1001 r = LUKS_keyslot_set(hdr, keyIndex, 0);
1003 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
1004 keyIndex, LUKS_NUMKEYS - 1);
1008 /* secure deletion of key material */
1009 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
1010 endOffset = startOffset + AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes);
1012 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
1013 (endOffset - startOffset) * SECTOR_SIZE,
1014 CRYPT_WIPE_DISK, 0);
1017 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
1018 device_path(device));
1021 log_err(ctx, _("Cannot wipe device %s.\n"),
1022 device_path(device));
1026 /* Wipe keyslot info */
1027 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
1028 hdr->keyblock[keyIndex].passwordIterations = 0;
1030 r = LUKS_write_phdr(hdr, ctx);
1035 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
1039 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
1040 return CRYPT_SLOT_INVALID;
1042 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
1043 return CRYPT_SLOT_INACTIVE;
1045 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1046 return CRYPT_SLOT_INVALID;
1048 for(i = 0; i < LUKS_NUMKEYS; i++)
1049 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1050 return CRYPT_SLOT_ACTIVE;
1052 return CRYPT_SLOT_ACTIVE_LAST;
1055 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1059 for (i = 0; i < LUKS_NUMKEYS; i++)
1060 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1063 if (i == LUKS_NUMKEYS)
1069 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1073 for (i = 0; i < LUKS_NUMKEYS; i++)
1074 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1080 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1082 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1084 if (ki == CRYPT_SLOT_INVALID)
1087 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1088 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1092 int LUKS1_activate(struct crypt_device *cd,
1094 struct volume_key *vk,
1098 char *dm_cipher = NULL;
1099 enum devcheck device_check;
1100 struct crypt_dm_active_device dmd = {
1102 .uuid = crypt_get_uuid(cd),
1105 .data_device = crypt_data_device(cd),
1109 .offset = crypt_get_data_offset(cd),
1114 if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1115 device_check = DEV_SHARED;
1117 device_check = DEV_EXCL;
1119 r = device_block_adjust(cd, dmd.data_device, device_check,
1120 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
1124 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1128 dmd.u.crypt.cipher = dm_cipher;
1129 r = dm_create_device(cd, name, CRYPT_LUKS1, &dmd, 0);