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 #define div_round_up(a,b) ({ \
40 typeof(a) __a = (a); \
41 typeof(b) __b = (b); \
42 (__a - 1) / __b + 1; \
45 static inline int round_up_modulo(int x, int m) {
46 return div_round_up(x, m) * m;
49 /* Get size of struct luks_phrd with all keyslots material space */
50 static uint64_t LUKS_device_sectors(size_t keyLen)
52 uint64_t keyslot_sectors, sector;
55 keyslot_sectors = div_round_up(keyLen * LUKS_STRIPES, SECTOR_SIZE);
56 sector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
58 for (i = 0; i < LUKS_NUMKEYS; i++) {
59 sector = round_up_modulo(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
60 sector += keyslot_sectors;
66 static int LUKS_check_device_size(struct crypt_device *ctx, size_t keyLength)
68 struct device *device = crypt_metadata_device(ctx);
69 uint64_t dev_sectors, hdr_sectors;
74 if(device_size(device, &dev_sectors)) {
75 log_dbg("Cannot get device size for device %s.", device_path(device));
79 dev_sectors >>= SECTOR_SHIFT;
80 hdr_sectors = LUKS_device_sectors(keyLength);
81 log_dbg("Key length %u, device size %" PRIu64 " sectors, header size %"
82 PRIu64 " sectors.",keyLength, dev_sectors, hdr_sectors);
84 if (hdr_sectors > dev_sectors) {
85 log_err(ctx, _("Device %s is too small.\n"), device_path(device));
92 /* Check keyslot to prevent access outside of header and keyslot area */
93 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
95 uint32_t secs_per_stripes;
97 /* First sectors is the header itself */
98 if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
99 log_dbg("Invalid offset %u in keyslot %u.",
100 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
104 /* Ignore following check for detached header where offset can be zero. */
105 if (phdr->payloadOffset == 0)
108 if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
109 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
110 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
111 phdr->payloadOffset);
115 secs_per_stripes = div_round_up(phdr->keyBytes * phdr->keyblock[keyIndex].stripes, SECTOR_SIZE);
117 if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
118 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
119 "keyslot %u (beyond data area offset %u).",
121 phdr->keyblock[keyIndex].keyMaterialOffset,
122 phdr->keyblock[keyIndex].stripes,
123 keyIndex, phdr->payloadOffset);
130 static const char *dbg_slot_state(crypt_keyslot_info ki)
133 case CRYPT_SLOT_INACTIVE:
135 case CRYPT_SLOT_ACTIVE:
137 case CRYPT_SLOT_ACTIVE_LAST:
138 return "ACTIVE_LAST";
139 case CRYPT_SLOT_INVALID:
146 const char *backup_file,
147 struct luks_phdr *hdr,
148 struct crypt_device *ctx)
150 struct device *device = crypt_metadata_device(ctx);
151 int r = 0, devfd = -1;
156 if(stat(backup_file, &st) == 0) {
157 log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
161 r = LUKS_read_phdr(hdr, 1, 0, ctx);
165 buffer_size = LUKS_device_sectors(hdr->keyBytes) << SECTOR_SHIFT;
166 buffer = crypt_safe_alloc(buffer_size);
167 if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
172 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
173 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
175 devfd = open(device_path(device), O_RDONLY | O_DIRECT | O_SYNC);
177 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device_path(device));
182 if(read_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
188 /* Wipe unused area, so backup cannot contain old signatures */
189 memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
191 devfd = creat(backup_file, S_IRUSR);
196 if(write(devfd, buffer, buffer_size) < buffer_size) {
197 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
207 crypt_safe_free(buffer);
211 int LUKS_hdr_restore(
212 const char *backup_file,
213 struct luks_phdr *hdr,
214 struct crypt_device *ctx)
216 struct device *device = crypt_metadata_device(ctx);
217 int r = 0, devfd = -1, diff_uuid = 0;
218 ssize_t buffer_size = 0;
219 char *buffer = NULL, msg[200];
221 struct luks_phdr hdr_file;
223 if(stat(backup_file, &st) < 0) {
224 log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
228 r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
230 buffer_size = LUKS_device_sectors(hdr_file.keyBytes) << SECTOR_SHIFT;
232 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
233 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
238 buffer = crypt_safe_alloc(buffer_size);
244 devfd = open(backup_file, O_RDONLY);
246 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
251 if(read(devfd, buffer, buffer_size) < buffer_size) {
252 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
258 r = LUKS_read_phdr(hdr, 0, 0, ctx);
260 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
261 if(hdr->payloadOffset != hdr_file.payloadOffset ||
262 hdr->keyBytes != hdr_file.keyBytes) {
263 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
267 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
271 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
272 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
273 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
274 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
279 if (!crypt_confirm(ctx, msg)) {
284 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
285 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
287 devfd = open(device_path(device), O_WRONLY | O_DIRECT | O_SYNC);
290 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
291 device_path(device));
293 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
298 if (write_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
304 /* Be sure to reload new data */
305 r = LUKS_read_phdr(hdr, 1, 0, ctx);
309 crypt_safe_free(buffer);
313 /* This routine should do some just basic recovery for known problems. */
314 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
316 struct luks_phdr temp_phdr;
317 const unsigned char *sector = (const unsigned char*)phdr;
318 struct volume_key *vk;
319 uint64_t PBKDF2_per_sec = 1;
320 int i, bad, r, need_write = 0;
322 if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
323 log_err(ctx, _("Non standard key size, manual repair required.\n"));
326 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
327 if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
328 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
332 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
334 log_verbose(ctx, _("Repairing keyslots.\n"));
336 log_dbg("Generating second header with the same parameters for check.");
337 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
338 /* payloadOffset - cannot check */
339 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
340 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
341 phdr->payloadOffset, 0,
345 log_err(ctx, _("Repair failed."));
349 for(i = 0; i < LUKS_NUMKEYS; ++i) {
350 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
351 log_dbg("Skipping repair for active keyslot %i.", i);
356 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
357 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
358 (unsigned)phdr->keyblock[i].keyMaterialOffset,
359 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
360 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
364 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
365 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
366 (unsigned)phdr->keyblock[i].stripes,
367 (unsigned)temp_phdr.keyblock[i].stripes);
368 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
372 /* Known case - MSDOS partition table signature */
373 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
374 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
379 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
380 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
381 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
382 phdr->keyblock[i].passwordIterations = 0;
390 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
391 r = LUKS_write_phdr(phdr, ctx);
394 crypt_free_volume_key(vk);
395 memset(&temp_phdr, 0, sizeof(temp_phdr));
399 static int _check_and_convert_hdr(const char *device,
400 struct luks_phdr *hdr,
401 int require_luks_device,
403 struct crypt_device *ctx)
407 char luksMagic[] = LUKS_MAGIC;
409 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
410 log_dbg("LUKS header not detected.");
411 if (require_luks_device)
412 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
414 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
415 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
419 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
420 if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
421 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
425 /* Header detected */
426 hdr->payloadOffset = ntohl(hdr->payloadOffset);
427 hdr->keyBytes = ntohl(hdr->keyBytes);
428 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
430 for(i = 0; i < LUKS_NUMKEYS; ++i) {
431 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
432 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
433 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
434 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
435 if (LUKS_check_keyslot_size(hdr, i)) {
436 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
441 /* Avoid unterminated strings */
442 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
443 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
444 hdr->uuid[UUID_STRING_L - 1] = '\0';
448 r = _keyslot_repair(hdr, ctx);
450 log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
456 static void _to_lower(char *str, unsigned max_len)
458 for(; *str && max_len; str++, max_len--)
460 *str = tolower(*str);
463 static void LUKS_fix_header_compatible(struct luks_phdr *header)
465 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
466 * so always convert hash to lower case in header */
467 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
470 int LUKS_read_phdr_backup(const char *backup_file,
471 struct luks_phdr *hdr,
472 int require_luks_device,
473 struct crypt_device *ctx)
475 ssize_t hdr_size = sizeof(struct luks_phdr);
476 int devfd = 0, r = 0;
478 log_dbg("Reading LUKS header of size %d from backup file %s",
479 (int)hdr_size, backup_file);
481 devfd = open(backup_file, O_RDONLY);
483 log_err(ctx, _("Cannot open file %s.\n"), backup_file);
487 if (read(devfd, hdr, hdr_size) < hdr_size)
490 LUKS_fix_header_compatible(hdr);
491 r = _check_and_convert_hdr(backup_file, hdr,
492 require_luks_device, 0, ctx);
499 int LUKS_read_phdr(struct luks_phdr *hdr,
500 int require_luks_device,
502 struct crypt_device *ctx)
504 struct device *device = crypt_metadata_device(ctx);
505 ssize_t hdr_size = sizeof(struct luks_phdr);
506 int devfd = 0, r = 0;
508 /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
509 assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
511 if (repair && !require_luks_device)
514 log_dbg("Reading LUKS header of size %d from device %s",
515 hdr_size, device_path(device));
517 devfd = open(device_path(device), O_RDONLY | O_DIRECT | O_SYNC);
519 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
523 if (read_blockwise(devfd, device_block_size(device), hdr, hdr_size) < hdr_size)
526 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
530 r = LUKS_check_device_size(ctx, hdr->keyBytes);
536 int LUKS_write_phdr(struct luks_phdr *hdr,
537 struct crypt_device *ctx)
539 struct device *device = crypt_metadata_device(ctx);
540 ssize_t hdr_size = sizeof(struct luks_phdr);
543 struct luks_phdr convHdr;
546 log_dbg("Updating LUKS header of size %d on device %s",
547 sizeof(struct luks_phdr), device_path(device));
549 r = LUKS_check_device_size(ctx, hdr->keyBytes);
553 devfd = open(device_path(device), O_RDWR | O_DIRECT | O_SYNC);
556 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
557 device_path(device));
559 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
563 memcpy(&convHdr, hdr, hdr_size);
564 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
566 /* Convert every uint16/32_t item to network byte order */
567 convHdr.version = htons(hdr->version);
568 convHdr.payloadOffset = htonl(hdr->payloadOffset);
569 convHdr.keyBytes = htonl(hdr->keyBytes);
570 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
571 for(i = 0; i < LUKS_NUMKEYS; ++i) {
572 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
573 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
574 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
575 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
578 r = write_blockwise(devfd, device_block_size(device), &convHdr, hdr_size) < hdr_size ? -EIO : 0;
580 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device_path(device));
583 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
585 r = LUKS_read_phdr(hdr, 1, 0, ctx);
587 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"),
588 device_path(device));
594 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
595 uint64_t *PBKDF2_per_sec,
596 struct crypt_device *ctx)
598 if (!*PBKDF2_per_sec) {
599 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
600 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
603 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
609 int LUKS_generate_phdr(struct luks_phdr *header,
610 const struct volume_key *vk,
611 const char *cipherName, const char *cipherMode, const char *hashSpec,
612 const char *uuid, unsigned int stripes,
613 unsigned int alignPayload,
614 unsigned int alignOffset,
615 uint32_t iteration_time_ms,
616 uint64_t *PBKDF2_per_sec,
617 int detached_metadata_device,
618 struct crypt_device *ctx)
621 unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
623 uuid_t partitionUuid;
625 char luksMagic[] = LUKS_MAGIC;
627 /* For separate metadata device allow zero alignment */
628 if (alignPayload == 0 && !detached_metadata_device)
629 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
631 if (PBKDF2_HMAC_ready(hashSpec) < 0) {
632 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
636 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
637 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
641 uuid_generate(partitionUuid);
643 memset(header,0,sizeof(struct luks_phdr));
646 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
648 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
649 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
650 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
652 header->keyBytes=vk->keylength;
654 LUKS_fix_header_compatible(header);
656 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
657 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
660 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
662 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
666 if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
669 /* Compute master key digest */
670 iteration_time_ms /= 8;
671 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
672 LUKS_MKD_ITERATIONS_MIN);
674 r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
675 header->mkDigestSalt,LUKS_SALTSIZE,
676 header->mkDigestIterations,
677 header->mkDigest,LUKS_DIGESTSIZE);
679 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
684 currentSector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
685 for(i = 0; i < LUKS_NUMKEYS; ++i) {
686 header->keyblock[i].active = LUKS_KEY_DISABLED;
687 header->keyblock[i].keyMaterialOffset = currentSector;
688 header->keyblock[i].stripes = stripes;
689 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
690 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
693 if (detached_metadata_device) {
694 /* for separate metadata device use alignPayload directly */
695 header->payloadOffset = alignPayload;
697 /* alignOffset - offset from natural device alignment provided by topology info */
698 currentSector = round_up_modulo(currentSector, alignPayload);
699 header->payloadOffset = currentSector + alignOffset;
702 uuid_unparse(partitionUuid, header->uuid);
704 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
705 header->payloadOffset, header->uuid, header->mkDigestIterations);
710 int LUKS_hdr_uuid_set(
711 struct luks_phdr *hdr,
713 struct crypt_device *ctx)
715 uuid_t partitionUuid;
717 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
718 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
722 uuid_generate(partitionUuid);
724 uuid_unparse(partitionUuid, hdr->uuid);
726 return LUKS_write_phdr(hdr, ctx);
729 int LUKS_set_key(unsigned int keyIndex,
730 const char *password, size_t passwordLen,
731 struct luks_phdr *hdr, struct volume_key *vk,
732 uint32_t iteration_time_ms,
733 uint64_t *PBKDF2_per_sec,
734 struct crypt_device *ctx)
736 struct volume_key *derived_key;
738 unsigned int AFEKSize;
739 uint64_t PBKDF2_temp;
742 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
743 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
747 if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
748 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
753 log_dbg("Calculating data for key slot %d", keyIndex);
755 if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
759 * Avoid floating point operation
760 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
762 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
764 if (PBKDF2_temp > UINT32_MAX)
765 PBKDF2_temp = UINT32_MAX;
766 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
767 LUKS_SLOT_ITERATIONS_MIN);
769 log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
771 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
775 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
776 LUKS_SALTSIZE, CRYPT_RND_SALT);
780 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
781 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
782 hdr->keyblock[keyIndex].passwordIterations,
783 derived_key->key, hdr->keyBytes);
788 * AF splitting, the masterkey stored in vk->key is split to AfKey
790 assert(vk->keylength == hdr->keyBytes);
791 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
792 AfKey = crypt_safe_alloc(AFEKSize);
798 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
799 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
800 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
804 log_dbg("Updating key slot %d [0x%04x] area.", keyIndex,
805 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
806 /* Encryption via dm */
807 r = LUKS_encrypt_to_storage(AfKey,
811 hdr->keyblock[keyIndex].keyMaterialOffset,
816 /* Mark the key as active in phdr */
817 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
821 r = LUKS_write_phdr(hdr, ctx);
827 crypt_safe_free(AfKey);
828 crypt_free_volume_key(derived_key);
832 /* Check whether a volume key is invalid. */
833 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
834 const struct volume_key *vk)
836 char checkHashBuf[LUKS_DIGESTSIZE];
838 if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
839 hdr->mkDigestSalt, LUKS_SALTSIZE,
840 hdr->mkDigestIterations, checkHashBuf,
841 LUKS_DIGESTSIZE) < 0)
844 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
850 /* Try to open a particular key slot */
851 static int LUKS_open_key(unsigned int keyIndex,
852 const char *password,
854 struct luks_phdr *hdr,
855 struct volume_key *vk,
856 struct crypt_device *ctx)
858 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
859 struct volume_key *derived_key;
864 log_dbg("Trying to open key slot %d [%s].", keyIndex,
867 if (ki < CRYPT_SLOT_ACTIVE)
870 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
874 assert(vk->keylength == hdr->keyBytes);
875 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
876 AfKey = crypt_safe_alloc(AFEKSize);
880 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
881 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
882 hdr->keyblock[keyIndex].passwordIterations,
883 derived_key->key, hdr->keyBytes);
887 log_dbg("Reading key slot %d area.", keyIndex);
888 r = LUKS_decrypt_from_storage(AfKey,
892 hdr->keyblock[keyIndex].keyMaterialOffset,
897 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
901 r = LUKS_verify_volume_key(hdr, vk);
903 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
905 crypt_safe_free(AfKey);
906 crypt_free_volume_key(derived_key);
910 int LUKS_open_key_with_hdr(int keyIndex,
911 const char *password,
913 struct luks_phdr *hdr,
914 struct volume_key **vk,
915 struct crypt_device *ctx)
920 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
923 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, *vk, ctx);
924 return (r < 0) ? r : keyIndex;
927 for(i = 0; i < LUKS_NUMKEYS; i++) {
928 r = LUKS_open_key(i, password, passwordLen, hdr, *vk, ctx);
932 /* Do not retry for errors that are no -EPERM or -ENOENT,
933 former meaning password wrong, latter key slot inactive */
934 if ((r != -EPERM) && (r != -ENOENT))
937 /* Warning, early returns above */
938 log_err(ctx, _("No key available with this passphrase.\n"));
942 int LUKS_del_key(unsigned int keyIndex,
943 struct luks_phdr *hdr,
944 struct crypt_device *ctx)
946 struct device *device = crypt_metadata_device(ctx);
947 unsigned int startOffset, endOffset, stripesLen;
950 r = LUKS_read_phdr(hdr, 1, 0, ctx);
954 r = LUKS_keyslot_set(hdr, keyIndex, 0);
956 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
957 keyIndex, LUKS_NUMKEYS - 1);
961 /* secure deletion of key material */
962 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
963 stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
964 endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
966 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
967 (endOffset - startOffset) * SECTOR_SIZE,
971 log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
972 device_path(device));
975 log_err(ctx, _("Cannot wipe device %s.\n"),
976 device_path(device));
980 /* Wipe keyslot info */
981 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
982 hdr->keyblock[keyIndex].passwordIterations = 0;
984 r = LUKS_write_phdr(hdr, ctx);
989 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
993 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
994 return CRYPT_SLOT_INVALID;
996 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
997 return CRYPT_SLOT_INACTIVE;
999 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1000 return CRYPT_SLOT_INVALID;
1002 for(i = 0; i < LUKS_NUMKEYS; i++)
1003 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1004 return CRYPT_SLOT_ACTIVE;
1006 return CRYPT_SLOT_ACTIVE_LAST;
1009 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1013 for (i = 0; i < LUKS_NUMKEYS; i++)
1014 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1017 if (i == LUKS_NUMKEYS)
1023 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1027 for (i = 0; i < LUKS_NUMKEYS; i++)
1028 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1034 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1036 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1038 if (ki == CRYPT_SLOT_INVALID)
1041 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1042 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1046 int LUKS1_activate(struct crypt_device *cd,
1048 struct volume_key *vk,
1052 char *dm_cipher = NULL;
1053 enum devcheck device_check;
1054 struct crypt_dm_active_device dmd = {
1056 .uuid = crypt_get_uuid(cd),
1059 .data_device = crypt_data_device(cd),
1063 .offset = crypt_get_data_offset(cd),
1068 if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1069 device_check = DEV_SHARED;
1071 device_check = DEV_EXCL;
1073 r = device_block_adjust(cd, dmd.data_device, device_check,
1074 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
1078 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1082 dmd.u.crypt.cipher = dm_cipher;
1083 r = dm_create_device(cd, name, CRYPT_LUKS1, &dmd, 0);