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);
222 buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
224 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
225 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
230 buffer = crypt_safe_alloc(buffer_size);
236 devfd = open(backup_file, O_RDONLY);
238 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
243 if(read(devfd, buffer, buffer_size) < buffer_size) {
244 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
250 r = LUKS_read_phdr(device, hdr, 0, 0, ctx);
252 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
253 if(hdr->payloadOffset != hdr_file.payloadOffset ||
254 hdr->keyBytes != hdr_file.keyBytes) {
255 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
259 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
263 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
264 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
265 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
266 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
271 if (!crypt_confirm(ctx, msg)) {
276 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
277 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
279 devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
281 log_err(ctx, _("Cannot open device %s.\n"), device);
286 if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
292 /* Be sure to reload new data */
293 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
297 crypt_safe_free(buffer);
301 /* This routine should do some just basic recovery for known problems. */
302 static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
304 struct luks_phdr temp_phdr;
305 const unsigned char *sector = (const unsigned char*)phdr;
306 struct volume_key *vk;
307 uint64_t PBKDF2_per_sec = 1;
308 int i, bad, r, need_write = 0;
310 if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
311 log_err(ctx, _("Non standard key size, manual repair required.\n"));
314 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
315 if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
316 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
320 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
322 log_verbose(ctx, _("Repairing keyslots.\n"));
324 log_dbg("Generating second header with the same parameters for check.");
325 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
326 /* payloadOffset - cannot check */
327 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
328 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
329 phdr->payloadOffset, 0,
333 log_err(ctx, _("Repair failed."));
337 for(i = 0; i < LUKS_NUMKEYS; ++i) {
338 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
339 log_dbg("Skipping repair for active keyslot %i.", i);
344 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
345 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
346 (unsigned)phdr->keyblock[i].keyMaterialOffset,
347 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
348 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
352 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
353 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
354 (unsigned)phdr->keyblock[i].stripes,
355 (unsigned)temp_phdr.keyblock[i].stripes);
356 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
360 /* Known case - MSDOS partition table signature */
361 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
362 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
367 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
368 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
369 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
370 phdr->keyblock[i].passwordIterations = 0;
378 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
379 r = LUKS_write_phdr(device, phdr, ctx);
382 crypt_free_volume_key(vk);
383 memset(&temp_phdr, 0, sizeof(temp_phdr));
387 static int _check_and_convert_hdr(const char *device,
388 struct luks_phdr *hdr,
389 int require_luks_device,
391 struct crypt_device *ctx)
395 char luksMagic[] = LUKS_MAGIC;
397 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
398 log_dbg("LUKS header not detected.");
399 if (require_luks_device)
400 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
402 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
403 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
407 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
408 if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
409 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
413 /* Header detected */
414 hdr->payloadOffset = ntohl(hdr->payloadOffset);
415 hdr->keyBytes = ntohl(hdr->keyBytes);
416 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
418 for(i = 0; i < LUKS_NUMKEYS; ++i) {
419 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
420 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
421 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
422 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
423 if (LUKS_check_keyslot_size(hdr, i)) {
424 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
429 /* Avoid unterminated strings */
430 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
431 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
432 hdr->uuid[UUID_STRING_L - 1] = '\0';
436 r = _keyslot_repair(device, hdr, ctx);
438 log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
444 static void _to_lower(char *str, unsigned max_len)
446 for(; *str && max_len; str++, max_len--)
448 *str = tolower(*str);
451 static void LUKS_fix_header_compatible(struct luks_phdr *header)
453 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
454 * so always convert hash to lower case in header */
455 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
458 int LUKS_read_phdr_backup(const char *backup_file,
460 struct luks_phdr *hdr,
461 int require_luks_device,
462 struct crypt_device *ctx)
464 ssize_t hdr_size = sizeof(struct luks_phdr);
465 int devfd = 0, r = 0;
467 log_dbg("Reading LUKS header of size %d from backup file %s",
468 (int)hdr_size, backup_file);
470 devfd = open(backup_file, O_RDONLY);
472 log_err(ctx, _("Cannot open file %s.\n"), device);
476 if (read(devfd, hdr, hdr_size) < hdr_size)
479 LUKS_fix_header_compatible(hdr);
480 r = _check_and_convert_hdr(backup_file, hdr,
481 require_luks_device, 0, ctx);
488 int LUKS_read_phdr(const char *device,
489 struct luks_phdr *hdr,
490 int require_luks_device,
492 struct crypt_device *ctx)
494 ssize_t hdr_size = sizeof(struct luks_phdr);
495 int devfd = 0, r = 0;
497 if (repair && !require_luks_device)
500 log_dbg("Reading LUKS header of size %d from device %s",
503 devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
505 log_err(ctx, _("Cannot open device %s.\n"), device);
509 if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
512 r = _check_and_convert_hdr(device, hdr, require_luks_device,
519 int LUKS_write_phdr(const char *device,
520 struct luks_phdr *hdr,
521 struct crypt_device *ctx)
523 ssize_t hdr_size = sizeof(struct luks_phdr);
526 struct luks_phdr convHdr;
529 log_dbg("Updating LUKS header of size %d on device %s",
530 sizeof(struct luks_phdr), device);
532 if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
533 log_err(ctx, _("Device %s is too small.\n"), device);
537 devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
539 log_err(ctx, _("Cannot open device %s.\n"), device);
543 memcpy(&convHdr, hdr, hdr_size);
544 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
546 /* Convert every uint16/32_t item to network byte order */
547 convHdr.version = htons(hdr->version);
548 convHdr.payloadOffset = htonl(hdr->payloadOffset);
549 convHdr.keyBytes = htonl(hdr->keyBytes);
550 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
551 for(i = 0; i < LUKS_NUMKEYS; ++i) {
552 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
553 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
554 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
555 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
558 r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
560 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
563 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
565 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
567 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
573 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
574 uint64_t *PBKDF2_per_sec,
575 struct crypt_device *ctx)
577 if (!*PBKDF2_per_sec) {
578 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
579 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
582 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
588 int LUKS_generate_phdr(struct luks_phdr *header,
589 const struct volume_key *vk,
590 const char *cipherName, const char *cipherMode, const char *hashSpec,
591 const char *uuid, unsigned int stripes,
592 unsigned int alignPayload,
593 unsigned int alignOffset,
594 uint32_t iteration_time_ms,
595 uint64_t *PBKDF2_per_sec,
596 const char *metadata_device,
597 struct crypt_device *ctx)
600 unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
602 uuid_t partitionUuid;
604 char luksMagic[] = LUKS_MAGIC;
606 /* For separate metadata device allow zero alignment */
607 if (alignPayload == 0 && !metadata_device)
608 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
610 if (PBKDF2_HMAC_ready(hashSpec) < 0) {
611 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
615 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
616 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
620 uuid_generate(partitionUuid);
622 memset(header,0,sizeof(struct luks_phdr));
625 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
627 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
628 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
629 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
631 header->keyBytes=vk->keylength;
633 LUKS_fix_header_compatible(header);
635 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
636 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
639 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
641 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
645 if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
648 /* Compute master key digest */
649 iteration_time_ms /= 8;
650 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
651 LUKS_MKD_ITERATIONS_MIN);
653 r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
654 header->mkDigestSalt,LUKS_SALTSIZE,
655 header->mkDigestIterations,
656 header->mkDigest,LUKS_DIGESTSIZE);
658 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
663 currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
664 for(i = 0; i < LUKS_NUMKEYS; ++i) {
665 header->keyblock[i].active = LUKS_KEY_DISABLED;
666 header->keyblock[i].keyMaterialOffset = currentSector;
667 header->keyblock[i].stripes = stripes;
668 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
669 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
672 if (metadata_device) {
673 /* for separate metadata device use alignPayload directly */
674 header->payloadOffset = alignPayload;
676 /* alignOffset - offset from natural device alignment provided by topology info */
677 currentSector = round_up_modulo(currentSector, alignPayload);
678 header->payloadOffset = currentSector + alignOffset;
681 uuid_unparse(partitionUuid, header->uuid);
683 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
684 header->payloadOffset, header->uuid, header->mkDigestIterations);
689 int LUKS_hdr_uuid_set(
691 struct luks_phdr *hdr,
693 struct crypt_device *ctx)
695 uuid_t partitionUuid;
697 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
698 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
702 uuid_generate(partitionUuid);
704 uuid_unparse(partitionUuid, hdr->uuid);
706 return LUKS_write_phdr(device, hdr, ctx);
709 int LUKS_set_key(const char *device, unsigned int keyIndex,
710 const char *password, size_t passwordLen,
711 struct luks_phdr *hdr, struct volume_key *vk,
712 uint32_t iteration_time_ms,
713 uint64_t *PBKDF2_per_sec,
714 struct crypt_device *ctx)
716 struct volume_key *derived_key;
718 unsigned int AFEKSize;
719 uint64_t PBKDF2_temp;
722 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
723 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
727 if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
728 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
733 log_dbg("Calculating data for key slot %d", keyIndex);
735 if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
739 * Avoid floating point operation
740 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
742 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
744 if (PBKDF2_temp > UINT32_MAX)
745 PBKDF2_temp = UINT32_MAX;
746 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
747 LUKS_SLOT_ITERATIONS_MIN);
749 log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
751 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
755 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
756 LUKS_SALTSIZE, CRYPT_RND_SALT);
760 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
761 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
762 hdr->keyblock[keyIndex].passwordIterations,
763 derived_key->key, hdr->keyBytes);
768 * AF splitting, the masterkey stored in vk->key is split to AfKey
770 assert(vk->keylength == hdr->keyBytes);
771 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
772 AfKey = crypt_safe_alloc(AFEKSize);
778 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
779 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
780 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
784 log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
785 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
786 /* Encryption via dm */
787 r = LUKS_encrypt_to_storage(AfKey,
792 hdr->keyblock[keyIndex].keyMaterialOffset,
795 log_err(ctx, _("Failed to write to key storage.\n"));
799 /* Mark the key as active in phdr */
800 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
804 r = LUKS_write_phdr(device, hdr, ctx);
810 crypt_safe_free(AfKey);
811 crypt_free_volume_key(derived_key);
815 /* Check whether a volume key is invalid. */
816 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
817 const struct volume_key *vk)
819 char checkHashBuf[LUKS_DIGESTSIZE];
821 if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
822 hdr->mkDigestSalt, LUKS_SALTSIZE,
823 hdr->mkDigestIterations, checkHashBuf,
824 LUKS_DIGESTSIZE) < 0)
827 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
833 /* Try to open a particular key slot */
834 static int LUKS_open_key(const char *device,
835 unsigned int keyIndex,
836 const char *password,
838 struct luks_phdr *hdr,
839 struct volume_key *vk,
840 struct crypt_device *ctx)
842 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
843 struct volume_key *derived_key;
848 log_dbg("Trying to open key slot %d [%s].", keyIndex,
851 if (ki < CRYPT_SLOT_ACTIVE)
854 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
858 assert(vk->keylength == hdr->keyBytes);
859 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
860 AfKey = crypt_safe_alloc(AFEKSize);
864 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
865 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
866 hdr->keyblock[keyIndex].passwordIterations,
867 derived_key->key, hdr->keyBytes);
871 log_dbg("Reading key slot %d area.", keyIndex);
872 r = LUKS_decrypt_from_storage(AfKey,
877 hdr->keyblock[keyIndex].keyMaterialOffset,
880 log_err(ctx, _("Failed to read from key storage.\n"));
884 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
888 r = LUKS_verify_volume_key(hdr, vk);
890 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
892 crypt_safe_free(AfKey);
893 crypt_free_volume_key(derived_key);
897 int LUKS_open_key_with_hdr(const char *device,
899 const char *password,
901 struct luks_phdr *hdr,
902 struct volume_key **vk,
903 struct crypt_device *ctx)
908 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
911 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
912 return (r < 0) ? r : keyIndex;
915 for(i = 0; i < LUKS_NUMKEYS; i++) {
916 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
920 /* Do not retry for errors that are no -EPERM or -ENOENT,
921 former meaning password wrong, latter key slot inactive */
922 if ((r != -EPERM) && (r != -ENOENT))
925 /* Warning, early returns above */
926 log_err(ctx, _("No key available with this passphrase.\n"));
930 int LUKS_del_key(const char *device,
931 unsigned int keyIndex,
932 struct luks_phdr *hdr,
933 struct crypt_device *ctx)
935 unsigned int startOffset, endOffset, stripesLen;
938 r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
942 r = LUKS_keyslot_set(hdr, keyIndex, 0);
944 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
945 keyIndex, LUKS_NUMKEYS - 1);
949 /* secure deletion of key material */
950 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
951 stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
952 endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
954 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
955 (endOffset - startOffset) * SECTOR_SIZE,
958 log_err(ctx, _("Cannot wipe device %s.\n"), device);
962 /* Wipe keyslot info */
963 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
964 hdr->keyblock[keyIndex].passwordIterations = 0;
966 r = LUKS_write_phdr(device, hdr, ctx);
971 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
975 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
976 return CRYPT_SLOT_INVALID;
978 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
979 return CRYPT_SLOT_INACTIVE;
981 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
982 return CRYPT_SLOT_INVALID;
984 for(i = 0; i < LUKS_NUMKEYS; i++)
985 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
986 return CRYPT_SLOT_ACTIVE;
988 return CRYPT_SLOT_ACTIVE_LAST;
991 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
995 for (i = 0; i < LUKS_NUMKEYS; i++)
996 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
999 if (i == LUKS_NUMKEYS)
1005 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1009 for (i = 0; i < LUKS_NUMKEYS; i++)
1010 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1016 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1018 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1020 if (ki == CRYPT_SLOT_INVALID)
1023 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1024 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1028 int LUKS1_activate(struct crypt_device *cd,
1030 struct volume_key *vk,
1034 char *dm_cipher = NULL;
1035 enum devcheck device_check;
1036 struct crypt_dm_active_device dmd = {
1038 .uuid = crypt_get_uuid(cd),
1041 .data_device = crypt_get_device_name(cd),
1045 .offset = crypt_get_data_offset(cd),
1050 if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1051 device_check = DEV_SHARED;
1053 device_check = DEV_EXCL;
1055 r = device_check_and_adjust(cd, dmd.data_device, device_check,
1056 &dmd.size, &dmd.u.crypt.offset,
1061 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1065 dmd.u.crypt.cipher = dm_cipher;
1066 r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);