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.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * version 2 as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include <sys/types.h>
23 #include <netinet/in.h>
32 #include <uuid/uuid.h>
39 /* Get size of struct luks_phdr with all keyslots material space */
40 static size_t LUKS_device_sectors(size_t keyLen)
42 size_t keyslot_sectors, sector;
45 keyslot_sectors = AF_split_sectors(keyLen, LUKS_STRIPES);
46 sector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
48 for (i = 0; i < LUKS_NUMKEYS; i++) {
49 sector = size_round_up(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
50 sector += keyslot_sectors;
56 int LUKS_keyslot_area(struct luks_phdr *hdr,
61 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
64 *offset = hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
65 *length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;
70 static int LUKS_check_device_size(struct crypt_device *ctx, size_t keyLength)
72 struct device *device = crypt_metadata_device(ctx);
73 uint64_t dev_sectors, hdr_sectors;
78 if(device_size(device, &dev_sectors)) {
79 log_dbg("Cannot get device size for device %s.", device_path(device));
83 dev_sectors >>= SECTOR_SHIFT;
84 hdr_sectors = LUKS_device_sectors(keyLength);
85 log_dbg("Key length %u, device size %" PRIu64 " sectors, header size %"
86 PRIu64 " sectors.",keyLength, dev_sectors, hdr_sectors);
88 if (hdr_sectors > dev_sectors) {
89 log_err(ctx, _("Device %s is too small.\n"), device_path(device));
96 /* Check keyslot to prevent access outside of header and keyslot area */
97 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
99 uint32_t secs_per_stripes;
101 /* First sectors is the header itself */
102 if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
103 log_dbg("Invalid offset %u in keyslot %u.",
104 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
108 /* Ignore following check for detached header where offset can be zero. */
109 if (phdr->payloadOffset == 0)
112 if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
113 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
114 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
115 phdr->payloadOffset);
119 secs_per_stripes = AF_split_sectors(phdr->keyBytes, phdr->keyblock[keyIndex].stripes);
121 if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
122 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
123 "keyslot %u (beyond data area offset %u).",
125 phdr->keyblock[keyIndex].keyMaterialOffset,
126 phdr->keyblock[keyIndex].stripes,
127 keyIndex, phdr->payloadOffset);
134 static const char *dbg_slot_state(crypt_keyslot_info ki)
137 case CRYPT_SLOT_INACTIVE:
139 case CRYPT_SLOT_ACTIVE:
141 case CRYPT_SLOT_ACTIVE_LAST:
142 return "ACTIVE_LAST";
143 case CRYPT_SLOT_INVALID:
150 const char *backup_file,
151 struct luks_phdr *hdr,
152 struct crypt_device *ctx)
154 struct device *device = crypt_metadata_device(ctx);
155 int r = 0, devfd = -1;
160 if(stat(backup_file, &st) == 0) {
161 log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
165 r = LUKS_read_phdr(hdr, 1, 0, ctx);
169 buffer_size = LUKS_device_sectors(hdr->keyBytes) << SECTOR_SHIFT;
170 buffer = crypt_safe_alloc(buffer_size);
171 if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
176 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
177 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
179 devfd = open(device_path(device), O_RDONLY | O_DIRECT | O_SYNC);
181 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device_path(device));
186 if(read_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
192 /* Wipe unused area, so backup cannot contain old signatures */
193 if (hdr->keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
194 memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
196 devfd = creat(backup_file, S_IRUSR);
201 if(write(devfd, buffer, buffer_size) < buffer_size) {
202 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
212 crypt_safe_free(buffer);
216 int LUKS_hdr_restore(
217 const char *backup_file,
218 struct luks_phdr *hdr,
219 struct crypt_device *ctx)
221 struct device *device = crypt_metadata_device(ctx);
222 int r = 0, devfd = -1, diff_uuid = 0;
223 ssize_t buffer_size = 0;
224 char *buffer = NULL, msg[200];
226 struct luks_phdr hdr_file;
228 if(stat(backup_file, &st) < 0) {
229 log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
233 r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
235 buffer_size = LUKS_device_sectors(hdr_file.keyBytes) << SECTOR_SHIFT;
237 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
238 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
243 buffer = crypt_safe_alloc(buffer_size);
249 devfd = open(backup_file, O_RDONLY);
251 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
256 if(read(devfd, buffer, buffer_size) < buffer_size) {
257 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
263 r = LUKS_read_phdr(hdr, 0, 0, ctx);
265 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
266 if(hdr->payloadOffset != hdr_file.payloadOffset ||
267 hdr->keyBytes != hdr_file.keyBytes) {
268 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
272 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
276 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
277 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
278 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
279 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
284 if (!crypt_confirm(ctx, msg)) {
289 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
290 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
292 devfd = open(device_path(device), O_WRONLY | O_DIRECT | O_SYNC);
295 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
296 device_path(device));
298 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
303 if (write_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
309 /* Be sure to reload new data */
310 r = LUKS_read_phdr(hdr, 1, 0, ctx);
314 crypt_safe_free(buffer);
318 /* This routine should do some just basic recovery for known problems. */
319 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
321 struct luks_phdr temp_phdr;
322 const unsigned char *sector = (const unsigned char*)phdr;
323 struct volume_key *vk;
324 uint64_t PBKDF2_per_sec = 1;
325 int i, bad, r, need_write = 0;
327 if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
328 log_err(ctx, _("Non standard key size, manual repair required.\n"));
331 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
332 if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
333 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
337 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
339 log_verbose(ctx, _("Repairing keyslots.\n"));
341 log_dbg("Generating second header with the same parameters for check.");
342 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
343 /* payloadOffset - cannot check */
344 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
345 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
346 phdr->payloadOffset, 0,
350 log_err(ctx, _("Repair failed."));
354 for(i = 0; i < LUKS_NUMKEYS; ++i) {
355 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
356 log_dbg("Skipping repair for active keyslot %i.", i);
361 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
362 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
363 (unsigned)phdr->keyblock[i].keyMaterialOffset,
364 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
365 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
369 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
370 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
371 (unsigned)phdr->keyblock[i].stripes,
372 (unsigned)temp_phdr.keyblock[i].stripes);
373 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
377 /* Known case - MSDOS partition table signature */
378 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
379 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
384 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
385 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
386 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
387 phdr->keyblock[i].passwordIterations = 0;
395 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
396 r = LUKS_write_phdr(phdr, ctx);
399 crypt_free_volume_key(vk);
400 memset(&temp_phdr, 0, sizeof(temp_phdr));
404 static int _check_and_convert_hdr(const char *device,
405 struct luks_phdr *hdr,
406 int require_luks_device,
408 struct crypt_device *ctx)
412 char luksMagic[] = LUKS_MAGIC;
414 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
415 log_dbg("LUKS header not detected.");
416 if (require_luks_device)
417 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
419 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
420 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
424 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
425 if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
426 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
430 /* Header detected */
431 hdr->payloadOffset = ntohl(hdr->payloadOffset);
432 hdr->keyBytes = ntohl(hdr->keyBytes);
433 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
435 for(i = 0; i < LUKS_NUMKEYS; ++i) {
436 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
437 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
438 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
439 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
440 if (LUKS_check_keyslot_size(hdr, i)) {
441 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
446 /* Avoid unterminated strings */
447 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
448 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
449 hdr->uuid[UUID_STRING_L - 1] = '\0';
453 r = _keyslot_repair(hdr, ctx);
455 log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
461 static void _to_lower(char *str, unsigned max_len)
463 for(; *str && max_len; str++, max_len--)
465 *str = tolower(*str);
468 static void LUKS_fix_header_compatible(struct luks_phdr *header)
470 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
471 * so always convert hash to lower case in header */
472 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
475 int LUKS_read_phdr_backup(const char *backup_file,
476 struct luks_phdr *hdr,
477 int require_luks_device,
478 struct crypt_device *ctx)
480 ssize_t hdr_size = sizeof(struct luks_phdr);
481 int devfd = 0, r = 0;
483 log_dbg("Reading LUKS header of size %d from backup file %s",
484 (int)hdr_size, backup_file);
486 devfd = open(backup_file, O_RDONLY);
488 log_err(ctx, _("Cannot open file %s.\n"), backup_file);
492 if (read(devfd, hdr, hdr_size) < hdr_size)
495 LUKS_fix_header_compatible(hdr);
496 r = _check_and_convert_hdr(backup_file, hdr,
497 require_luks_device, 0, ctx);
504 int LUKS_read_phdr(struct luks_phdr *hdr,
505 int require_luks_device,
507 struct crypt_device *ctx)
509 struct device *device = crypt_metadata_device(ctx);
510 ssize_t hdr_size = sizeof(struct luks_phdr);
511 int devfd = 0, r = 0;
513 /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
514 assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
516 /* Stripes count cannot be changed without additional code fixes yet */
517 assert(LUKS_STRIPES == 4000);
519 if (repair && !require_luks_device)
522 log_dbg("Reading LUKS header of size %d from device %s",
523 hdr_size, device_path(device));
525 devfd = open(device_path(device), O_RDONLY | O_DIRECT | O_SYNC);
527 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
531 if (read_blockwise(devfd, device_block_size(device), hdr, hdr_size) < hdr_size)
534 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
538 r = LUKS_check_device_size(ctx, hdr->keyBytes);
544 int LUKS_write_phdr(struct luks_phdr *hdr,
545 struct crypt_device *ctx)
547 struct device *device = crypt_metadata_device(ctx);
548 ssize_t hdr_size = sizeof(struct luks_phdr);
551 struct luks_phdr convHdr;
554 log_dbg("Updating LUKS header of size %d on device %s",
555 sizeof(struct luks_phdr), device_path(device));
557 r = LUKS_check_device_size(ctx, hdr->keyBytes);
561 devfd = open(device_path(device), O_RDWR | O_DIRECT | O_SYNC);
564 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
565 device_path(device));
567 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
571 memcpy(&convHdr, hdr, hdr_size);
572 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
574 /* Convert every uint16/32_t item to network byte order */
575 convHdr.version = htons(hdr->version);
576 convHdr.payloadOffset = htonl(hdr->payloadOffset);
577 convHdr.keyBytes = htonl(hdr->keyBytes);
578 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
579 for(i = 0; i < LUKS_NUMKEYS; ++i) {
580 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
581 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
582 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
583 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
586 r = write_blockwise(devfd, device_block_size(device), &convHdr, hdr_size) < hdr_size ? -EIO : 0;
588 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device_path(device));
591 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
593 r = LUKS_read_phdr(hdr, 1, 0, ctx);
595 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"),
596 device_path(device));
602 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
603 uint64_t *PBKDF2_per_sec,
604 struct crypt_device *ctx)
606 if (!*PBKDF2_per_sec) {
607 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
608 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
611 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
617 int LUKS_generate_phdr(struct luks_phdr *header,
618 const struct volume_key *vk,
619 const char *cipherName, const char *cipherMode, const char *hashSpec,
620 const char *uuid, unsigned int stripes,
621 unsigned int alignPayload,
622 unsigned int alignOffset,
623 uint32_t iteration_time_ms,
624 uint64_t *PBKDF2_per_sec,
625 int detached_metadata_device,
626 struct crypt_device *ctx)
629 size_t blocksPerStripeSet, currentSector;
631 uuid_t partitionUuid;
632 char luksMagic[] = LUKS_MAGIC;
634 /* For separate metadata device allow zero alignment */
635 if (alignPayload == 0 && !detached_metadata_device)
636 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
638 if (PBKDF2_HMAC_ready(hashSpec) < 0) {
639 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
643 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
644 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
648 uuid_generate(partitionUuid);
650 memset(header,0,sizeof(struct luks_phdr));
653 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
655 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
656 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
657 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
659 header->keyBytes=vk->keylength;
661 LUKS_fix_header_compatible(header);
663 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
664 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
667 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
669 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
673 if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
676 /* Compute master key digest */
677 iteration_time_ms /= 8;
678 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
679 LUKS_MKD_ITERATIONS_MIN);
681 r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
682 header->mkDigestSalt,LUKS_SALTSIZE,
683 header->mkDigestIterations,
684 header->mkDigest,LUKS_DIGESTSIZE);
686 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
691 currentSector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
692 blocksPerStripeSet = AF_split_sectors(vk->keylength, stripes);
693 for(i = 0; i < LUKS_NUMKEYS; ++i) {
694 header->keyblock[i].active = LUKS_KEY_DISABLED;
695 header->keyblock[i].keyMaterialOffset = currentSector;
696 header->keyblock[i].stripes = stripes;
697 currentSector = size_round_up(currentSector + blocksPerStripeSet,
698 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
701 if (detached_metadata_device) {
702 /* for separate metadata device use alignPayload directly */
703 header->payloadOffset = alignPayload;
705 /* alignOffset - offset from natural device alignment provided by topology info */
706 currentSector = size_round_up(currentSector, alignPayload);
707 header->payloadOffset = currentSector + alignOffset;
710 uuid_unparse(partitionUuid, header->uuid);
712 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
713 header->payloadOffset, header->uuid, header->mkDigestIterations);
718 int LUKS_hdr_uuid_set(
719 struct luks_phdr *hdr,
721 struct crypt_device *ctx)
723 uuid_t partitionUuid;
725 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
726 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
730 uuid_generate(partitionUuid);
732 uuid_unparse(partitionUuid, hdr->uuid);
734 return LUKS_write_phdr(hdr, ctx);
737 int LUKS_set_key(unsigned int keyIndex,
738 const char *password, size_t passwordLen,
739 struct luks_phdr *hdr, struct volume_key *vk,
740 uint32_t iteration_time_ms,
741 uint64_t *PBKDF2_per_sec,
742 struct crypt_device *ctx)
744 struct volume_key *derived_key;
747 uint64_t PBKDF2_temp;
750 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
751 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
755 /* LUKS keyslot has always at least 4000 stripes accoding to specification */
756 if(hdr->keyblock[keyIndex].stripes < 4000) {
757 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
762 log_dbg("Calculating data for key slot %d", keyIndex);
764 if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
768 * Avoid floating point operation
769 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
771 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
773 if (PBKDF2_temp > UINT32_MAX)
774 PBKDF2_temp = UINT32_MAX;
775 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
776 LUKS_SLOT_ITERATIONS_MIN);
778 log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
780 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
784 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
785 LUKS_SALTSIZE, CRYPT_RND_SALT);
789 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
790 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
791 hdr->keyblock[keyIndex].passwordIterations,
792 derived_key->key, hdr->keyBytes);
797 * AF splitting, the masterkey stored in vk->key is split to AfKey
799 assert(vk->keylength == hdr->keyBytes);
800 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
801 AfKey = crypt_safe_alloc(AFEKSize);
807 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
808 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
809 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
813 log_dbg("Updating key slot %d [0x%04x] area.", keyIndex,
814 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
815 /* Encryption via dm */
816 r = LUKS_encrypt_to_storage(AfKey,
820 hdr->keyblock[keyIndex].keyMaterialOffset,
825 /* Mark the key as active in phdr */
826 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
830 r = LUKS_write_phdr(hdr, ctx);
836 crypt_safe_free(AfKey);
837 crypt_free_volume_key(derived_key);
841 /* Check whether a volume key is invalid. */
842 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
843 const struct volume_key *vk)
845 char checkHashBuf[LUKS_DIGESTSIZE];
847 if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
848 hdr->mkDigestSalt, LUKS_SALTSIZE,
849 hdr->mkDigestIterations, checkHashBuf,
850 LUKS_DIGESTSIZE) < 0)
853 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
859 /* Try to open a particular key slot */
860 static int LUKS_open_key(unsigned int keyIndex,
861 const char *password,
863 struct luks_phdr *hdr,
864 struct volume_key *vk,
865 struct crypt_device *ctx)
867 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
868 struct volume_key *derived_key;
873 log_dbg("Trying to open key slot %d [%s].", keyIndex,
876 if (ki < CRYPT_SLOT_ACTIVE)
879 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
883 assert(vk->keylength == hdr->keyBytes);
884 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
885 AfKey = crypt_safe_alloc(AFEKSize);
891 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
892 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
893 hdr->keyblock[keyIndex].passwordIterations,
894 derived_key->key, hdr->keyBytes);
898 log_dbg("Reading key slot %d area.", keyIndex);
899 r = LUKS_decrypt_from_storage(AfKey,
903 hdr->keyblock[keyIndex].keyMaterialOffset,
908 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
912 r = LUKS_verify_volume_key(hdr, vk);
914 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
916 crypt_safe_free(AfKey);
917 crypt_free_volume_key(derived_key);
921 int LUKS_open_key_with_hdr(int keyIndex,
922 const char *password,
924 struct luks_phdr *hdr,
925 struct volume_key **vk,
926 struct crypt_device *ctx)
931 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
934 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, *vk, ctx);
935 return (r < 0) ? r : keyIndex;
938 for(i = 0; i < LUKS_NUMKEYS; i++) {
939 r = LUKS_open_key(i, password, passwordLen, hdr, *vk, ctx);
943 /* Do not retry for errors that are no -EPERM or -ENOENT,
944 former meaning password wrong, latter key slot inactive */
945 if ((r != -EPERM) && (r != -ENOENT))
948 /* Warning, early returns above */
949 log_err(ctx, _("No key available with this passphrase.\n"));
953 int LUKS_del_key(unsigned int keyIndex,
954 struct luks_phdr *hdr,
955 struct crypt_device *ctx)
957 struct device *device = crypt_metadata_device(ctx);
958 unsigned int startOffset, endOffset;
961 r = LUKS_read_phdr(hdr, 1, 0, ctx);
965 r = LUKS_keyslot_set(hdr, keyIndex, 0);
967 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
968 keyIndex, LUKS_NUMKEYS - 1);
972 /* secure deletion of key material */
973 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
974 endOffset = startOffset + AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes);
976 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
977 (endOffset - startOffset) * SECTOR_SIZE,
981 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
982 device_path(device));
985 log_err(ctx, _("Cannot wipe device %s.\n"),
986 device_path(device));
990 /* Wipe keyslot info */
991 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
992 hdr->keyblock[keyIndex].passwordIterations = 0;
994 r = LUKS_write_phdr(hdr, ctx);
999 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
1003 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
1004 return CRYPT_SLOT_INVALID;
1006 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
1007 return CRYPT_SLOT_INACTIVE;
1009 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1010 return CRYPT_SLOT_INVALID;
1012 for(i = 0; i < LUKS_NUMKEYS; i++)
1013 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1014 return CRYPT_SLOT_ACTIVE;
1016 return CRYPT_SLOT_ACTIVE_LAST;
1019 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1023 for (i = 0; i < LUKS_NUMKEYS; i++)
1024 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1027 if (i == LUKS_NUMKEYS)
1033 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1037 for (i = 0; i < LUKS_NUMKEYS; i++)
1038 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1044 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1046 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1048 if (ki == CRYPT_SLOT_INVALID)
1051 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1052 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1056 int LUKS1_activate(struct crypt_device *cd,
1058 struct volume_key *vk,
1062 char *dm_cipher = NULL;
1063 enum devcheck device_check;
1064 struct crypt_dm_active_device dmd = {
1066 .uuid = crypt_get_uuid(cd),
1069 .data_device = crypt_data_device(cd),
1073 .offset = crypt_get_data_offset(cd),
1078 if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1079 device_check = DEV_SHARED;
1081 device_check = DEV_EXCL;
1083 r = device_block_adjust(cd, dmd.data_device, device_check,
1084 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
1088 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1092 dmd.u.crypt.cipher = dm_cipher;
1093 r = dm_create_device(cd, name, CRYPT_LUKS1, &dmd, 0);