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, unsigned int stripes)
52 uint64_t keyslot_sectors, sector;
55 keyslot_sectors = div_round_up(keyLen * stripes, SECTOR_SIZE);
56 sector = round_up_modulo(LUKS_PHDR_SIZE, 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(const char *device,
70 uint64_t dev_size, req_sectors;
72 req_sectors = LUKS_device_sectors(keyLength, LUKS_STRIPES);
73 if (min_sectors > req_sectors)
74 req_sectors = min_sectors;
76 if(device_size(device, &dev_size)) {
77 log_dbg("Cannot get device size for device %s.", device);
81 return (req_sectors > (dev_size >> SECTOR_SHIFT));
84 /* Check keyslot to prevent access outside of header and keyslot area */
85 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
87 uint32_t secs_per_stripes;
89 /* First sectors is the header itself */
90 if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
91 log_dbg("Invalid offset %u in keyslot %u.",
92 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
96 /* Ignore following check for detached header where offset can be zero. */
97 if (phdr->payloadOffset == 0)
100 if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
101 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
102 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
103 phdr->payloadOffset);
107 secs_per_stripes = div_round_up(phdr->keyBytes * phdr->keyblock[keyIndex].stripes, SECTOR_SIZE);
109 if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
110 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
111 "keyslot %u (beyond data area offset %u).",
113 phdr->keyblock[keyIndex].keyMaterialOffset,
114 phdr->keyblock[keyIndex].stripes,
115 keyIndex, phdr->payloadOffset);
122 static const char *dbg_slot_state(crypt_keyslot_info ki)
125 case CRYPT_SLOT_INACTIVE:
127 case CRYPT_SLOT_ACTIVE:
129 case CRYPT_SLOT_ACTIVE_LAST:
130 return "ACTIVE_LAST";
131 case CRYPT_SLOT_INVALID:
138 const char *backup_file,
140 struct luks_phdr *hdr,
141 struct crypt_device *ctx)
143 int r = 0, devfd = -1;
148 if(stat(backup_file, &st) == 0) {
149 log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
153 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
157 buffer_size = hdr->payloadOffset << SECTOR_SHIFT;
158 buffer = crypt_safe_alloc(buffer_size);
159 if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
164 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
165 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
167 devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
169 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
174 if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
180 /* Wipe unused area, so backup cannot contain old signatures */
181 memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
183 devfd = creat(backup_file, S_IRUSR);
188 if(write(devfd, buffer, buffer_size) < buffer_size) {
189 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
199 crypt_safe_free(buffer);
203 int LUKS_hdr_restore(
204 const char *backup_file,
206 struct luks_phdr *hdr,
207 struct crypt_device *ctx)
209 int r = 0, devfd = -1, diff_uuid = 0;
211 char *buffer = NULL, msg[200];
213 struct luks_phdr hdr_file;
215 if(stat(backup_file, &st) < 0) {
216 log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
220 r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
221 buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
223 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
224 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
229 buffer = crypt_safe_alloc(buffer_size);
235 devfd = open(backup_file, O_RDONLY);
237 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
242 if(read(devfd, buffer, buffer_size) < buffer_size) {
243 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
249 r = LUKS_read_phdr(device, hdr, 0, 0, ctx);
251 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
252 if(hdr->payloadOffset != hdr_file.payloadOffset ||
253 hdr->keyBytes != hdr_file.keyBytes) {
254 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
258 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
262 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
263 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
264 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
265 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
270 if (!crypt_confirm(ctx, msg)) {
275 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
276 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
278 devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
280 log_err(ctx, _("Cannot open device %s.\n"), device);
285 if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
291 /* Be sure to reload new data */
292 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
296 crypt_safe_free(buffer);
300 /* This routine should do some just basic recovery for known problems. */
301 static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
303 struct luks_phdr temp_phdr;
304 const unsigned char *sector = (const unsigned char*)phdr;
305 struct volume_key *vk;
306 uint64_t PBKDF2_per_sec = 1;
307 int i, bad, r, need_write = 0;
309 if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
310 log_err(ctx, _("Non standard key size, manual repair required.\n"));
313 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
314 if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
315 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
319 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
321 log_verbose(ctx, _("Repairing keyslots.\n"));
323 log_dbg("Generating second header with the same parameters for check.");
324 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
325 /* payloadOffset - cannot check */
326 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
327 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
328 phdr->payloadOffset, 0,
332 log_err(ctx, _("Repair failed."));
336 for(i = 0; i < LUKS_NUMKEYS; ++i) {
337 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
338 log_dbg("Skipping repair for active keyslot %i.", i);
343 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
344 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
345 (unsigned)phdr->keyblock[i].keyMaterialOffset,
346 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
347 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
351 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
352 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
353 (unsigned)phdr->keyblock[i].stripes,
354 (unsigned)temp_phdr.keyblock[i].stripes);
355 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
359 /* Known case - MSDOS partition table signature */
360 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
361 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
366 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
367 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
368 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
369 phdr->keyblock[i].passwordIterations = 0;
377 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
378 r = LUKS_write_phdr(device, phdr, ctx);
381 crypt_free_volume_key(vk);
382 memset(&temp_phdr, 0, sizeof(temp_phdr));
386 static int _check_and_convert_hdr(const char *device,
387 struct luks_phdr *hdr,
388 int require_luks_device,
390 struct crypt_device *ctx)
394 char luksMagic[] = LUKS_MAGIC;
396 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
397 log_dbg("LUKS header not detected.");
398 if (require_luks_device)
399 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
401 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
402 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
406 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
407 if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
408 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
412 /* Header detected */
413 hdr->payloadOffset = ntohl(hdr->payloadOffset);
414 hdr->keyBytes = ntohl(hdr->keyBytes);
415 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
417 for(i = 0; i < LUKS_NUMKEYS; ++i) {
418 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
419 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
420 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
421 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
422 if (LUKS_check_keyslot_size(hdr, i)) {
423 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
428 /* Avoid unterminated strings */
429 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
430 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
431 hdr->uuid[UUID_STRING_L - 1] = '\0';
435 r = _keyslot_repair(device, hdr, ctx);
437 log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
443 static void _to_lower(char *str, unsigned max_len)
445 for(; *str && max_len; str++, max_len--)
447 *str = tolower(*str);
450 static void LUKS_fix_header_compatible(struct luks_phdr *header)
452 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
453 * so always convert hash to lower case in header */
454 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
457 int LUKS_read_phdr_backup(const char *backup_file,
459 struct luks_phdr *hdr,
460 int require_luks_device,
461 struct crypt_device *ctx)
463 ssize_t hdr_size = sizeof(struct luks_phdr);
464 int devfd = 0, r = 0;
466 log_dbg("Reading LUKS header of size %d from backup file %s",
467 (int)hdr_size, backup_file);
469 devfd = open(backup_file, O_RDONLY);
471 log_err(ctx, _("Cannot open file %s.\n"), device);
475 if (read(devfd, hdr, hdr_size) < hdr_size)
478 LUKS_fix_header_compatible(hdr);
479 r = _check_and_convert_hdr(backup_file, hdr,
480 require_luks_device, 0, ctx);
487 int LUKS_read_phdr(const char *device,
488 struct luks_phdr *hdr,
489 int require_luks_device,
491 struct crypt_device *ctx)
493 ssize_t hdr_size = sizeof(struct luks_phdr);
494 int devfd = 0, r = 0;
496 if (repair && !require_luks_device)
499 log_dbg("Reading LUKS header of size %d from device %s",
502 devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
504 log_err(ctx, _("Cannot open device %s.\n"), device);
508 if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
511 r = _check_and_convert_hdr(device, hdr, require_luks_device,
518 int LUKS_write_phdr(const char *device,
519 struct luks_phdr *hdr,
520 struct crypt_device *ctx)
522 ssize_t hdr_size = sizeof(struct luks_phdr);
525 struct luks_phdr convHdr;
528 log_dbg("Updating LUKS header of size %d on device %s",
529 sizeof(struct luks_phdr), device);
531 if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
532 log_err(ctx, _("Device %s is too small.\n"), device);
536 devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
538 log_err(ctx, _("Cannot open device %s.\n"), device);
542 memcpy(&convHdr, hdr, hdr_size);
543 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
545 /* Convert every uint16/32_t item to network byte order */
546 convHdr.version = htons(hdr->version);
547 convHdr.payloadOffset = htonl(hdr->payloadOffset);
548 convHdr.keyBytes = htonl(hdr->keyBytes);
549 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
550 for(i = 0; i < LUKS_NUMKEYS; ++i) {
551 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
552 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
553 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
554 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
557 r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
559 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
562 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
564 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
566 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
572 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
573 uint64_t *PBKDF2_per_sec,
574 struct crypt_device *ctx)
576 if (!*PBKDF2_per_sec) {
577 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
578 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
581 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
587 int LUKS_generate_phdr(struct luks_phdr *header,
588 const struct volume_key *vk,
589 const char *cipherName, const char *cipherMode, const char *hashSpec,
590 const char *uuid, unsigned int stripes,
591 unsigned int alignPayload,
592 unsigned int alignOffset,
593 uint32_t iteration_time_ms,
594 uint64_t *PBKDF2_per_sec,
595 const char *metadata_device,
596 struct crypt_device *ctx)
599 unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
601 uuid_t partitionUuid;
603 char luksMagic[] = LUKS_MAGIC;
605 /* For separate metadata device allow zero alignment */
606 if (alignPayload == 0 && !metadata_device)
607 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
609 if (PBKDF2_HMAC_ready(hashSpec) < 0) {
610 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
614 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
615 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
619 uuid_generate(partitionUuid);
621 memset(header,0,sizeof(struct luks_phdr));
624 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
626 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
627 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
628 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
630 header->keyBytes=vk->keylength;
632 LUKS_fix_header_compatible(header);
634 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
635 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
638 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_NORMAL);
640 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
644 if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
647 /* Compute master key digest */
648 iteration_time_ms /= 8;
649 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
650 LUKS_MKD_ITERATIONS_MIN);
652 r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
653 header->mkDigestSalt,LUKS_SALTSIZE,
654 header->mkDigestIterations,
655 header->mkDigest,LUKS_DIGESTSIZE);
657 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
662 currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
663 for(i = 0; i < LUKS_NUMKEYS; ++i) {
664 header->keyblock[i].active = LUKS_KEY_DISABLED;
665 header->keyblock[i].keyMaterialOffset = currentSector;
666 header->keyblock[i].stripes = stripes;
667 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
668 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
671 if (metadata_device) {
672 /* for separate metadata device use alignPayload directly */
673 header->payloadOffset = alignPayload;
675 /* alignOffset - offset from natural device alignment provided by topology info */
676 currentSector = round_up_modulo(currentSector, alignPayload);
677 header->payloadOffset = currentSector + alignOffset;
680 uuid_unparse(partitionUuid, header->uuid);
682 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
683 header->payloadOffset, header->uuid, header->mkDigestIterations);
688 int LUKS_hdr_uuid_set(
690 struct luks_phdr *hdr,
692 struct crypt_device *ctx)
694 uuid_t partitionUuid;
696 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
697 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
701 uuid_generate(partitionUuid);
703 uuid_unparse(partitionUuid, hdr->uuid);
705 return LUKS_write_phdr(device, hdr, ctx);
708 int LUKS_set_key(const char *device, unsigned int keyIndex,
709 const char *password, size_t passwordLen,
710 struct luks_phdr *hdr, struct volume_key *vk,
711 uint32_t iteration_time_ms,
712 uint64_t *PBKDF2_per_sec,
713 struct crypt_device *ctx)
715 struct volume_key *derived_key;
717 unsigned int AFEKSize;
718 uint64_t PBKDF2_temp;
721 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
722 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
726 if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
727 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
732 log_dbg("Calculating data for key slot %d", keyIndex);
734 if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
738 * Avoid floating point operation
739 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
741 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
743 if (PBKDF2_temp > UINT32_MAX)
744 PBKDF2_temp = UINT32_MAX;
745 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
746 LUKS_SLOT_ITERATIONS_MIN);
748 log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
750 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
754 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
755 LUKS_SALTSIZE, CRYPT_RND_NORMAL);
759 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
760 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
761 hdr->keyblock[keyIndex].passwordIterations,
762 derived_key->key, hdr->keyBytes);
767 * AF splitting, the masterkey stored in vk->key is split to AfKey
769 assert(vk->keylength == hdr->keyBytes);
770 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
771 AfKey = crypt_safe_alloc(AFEKSize);
777 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
778 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
779 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
783 log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
784 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
785 /* Encryption via dm */
786 r = LUKS_encrypt_to_storage(AfKey,
791 hdr->keyblock[keyIndex].keyMaterialOffset,
794 log_err(ctx, _("Failed to write to key storage.\n"));
798 /* Mark the key as active in phdr */
799 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
803 r = LUKS_write_phdr(device, hdr, ctx);
809 crypt_safe_free(AfKey);
810 crypt_free_volume_key(derived_key);
814 /* Check whether a volume key is invalid. */
815 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
816 const struct volume_key *vk)
818 char checkHashBuf[LUKS_DIGESTSIZE];
820 if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
821 hdr->mkDigestSalt, LUKS_SALTSIZE,
822 hdr->mkDigestIterations, checkHashBuf,
823 LUKS_DIGESTSIZE) < 0)
826 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
832 /* Try to open a particular key slot */
833 static int LUKS_open_key(const char *device,
834 unsigned int keyIndex,
835 const char *password,
837 struct luks_phdr *hdr,
838 struct volume_key *vk,
839 struct crypt_device *ctx)
841 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
842 struct volume_key *derived_key;
847 log_dbg("Trying to open key slot %d [%s].", keyIndex,
850 if (ki < CRYPT_SLOT_ACTIVE)
853 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
857 assert(vk->keylength == hdr->keyBytes);
858 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
859 AfKey = crypt_safe_alloc(AFEKSize);
863 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
864 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
865 hdr->keyblock[keyIndex].passwordIterations,
866 derived_key->key, hdr->keyBytes);
870 log_dbg("Reading key slot %d area.", keyIndex);
871 r = LUKS_decrypt_from_storage(AfKey,
876 hdr->keyblock[keyIndex].keyMaterialOffset,
879 log_err(ctx, _("Failed to read from key storage.\n"));
883 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
887 r = LUKS_verify_volume_key(hdr, vk);
889 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
891 crypt_safe_free(AfKey);
892 crypt_free_volume_key(derived_key);
896 int LUKS_open_key_with_hdr(const char *device,
898 const char *password,
900 struct luks_phdr *hdr,
901 struct volume_key **vk,
902 struct crypt_device *ctx)
907 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
910 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
911 return (r < 0) ? r : keyIndex;
914 for(i = 0; i < LUKS_NUMKEYS; i++) {
915 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
919 /* Do not retry for errors that are no -EPERM or -ENOENT,
920 former meaning password wrong, latter key slot inactive */
921 if ((r != -EPERM) && (r != -ENOENT))
924 /* Warning, early returns above */
925 log_err(ctx, _("No key available with this passphrase.\n"));
929 int LUKS_del_key(const char *device,
930 unsigned int keyIndex,
931 struct luks_phdr *hdr,
932 struct crypt_device *ctx)
934 unsigned int startOffset, endOffset, stripesLen;
937 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
941 r = LUKS_keyslot_set(hdr, keyIndex, 0);
943 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
944 keyIndex, LUKS_NUMKEYS - 1);
948 /* secure deletion of key material */
949 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
950 stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
951 endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
953 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
954 (endOffset - startOffset) * SECTOR_SIZE,
957 log_err(ctx, _("Cannot wipe device %s.\n"), device);
961 /* Wipe keyslot info */
962 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
963 hdr->keyblock[keyIndex].passwordIterations = 0;
965 r = LUKS_write_phdr(device, hdr, ctx);
970 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
974 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
975 return CRYPT_SLOT_INVALID;
977 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
978 return CRYPT_SLOT_INACTIVE;
980 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
981 return CRYPT_SLOT_INVALID;
983 for(i = 0; i < LUKS_NUMKEYS; i++)
984 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
985 return CRYPT_SLOT_ACTIVE;
987 return CRYPT_SLOT_ACTIVE_LAST;
990 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
994 for (i = 0; i < LUKS_NUMKEYS; i++)
995 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
998 if (i == LUKS_NUMKEYS)
1004 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1008 for (i = 0; i < LUKS_NUMKEYS; i++)
1009 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1015 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1017 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1019 if (ki == CRYPT_SLOT_INVALID)
1022 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1023 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1027 int LUKS1_activate(struct crypt_device *cd,
1029 struct volume_key *vk,
1033 char *dm_cipher = NULL;
1034 enum devcheck device_check;
1035 struct crypt_dm_active_device dmd = {
1036 .device = crypt_get_device_name(cd),
1038 .uuid = crypt_get_uuid(cd),
1040 .offset = crypt_get_data_offset(cd),
1046 if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1047 device_check = DEV_SHARED;
1049 device_check = DEV_EXCL;
1051 r = device_check_and_adjust(cd, dmd.device, device_check,
1052 &dmd.size, &dmd.offset, &flags);
1056 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1060 dmd.cipher = dm_cipher;
1061 r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);