2 * LUKS - Linux Unified Key Setup
4 * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * version 2 as published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include <sys/types.h>
22 #include <netinet/in.h>
31 #include <uuid/uuid.h>
38 #define div_round_up(a,b) ({ \
39 typeof(a) __a = (a); \
40 typeof(b) __b = (b); \
41 (__a - 1) / __b + 1; \
44 static inline int round_up_modulo(int x, int m) {
45 return div_round_up(x, m) * m;
48 /* Get size of struct luks_phrd with all keyslots material space */
49 static uint64_t LUKS_device_sectors(size_t keyLen, unsigned int stripes)
51 uint64_t keyslot_sectors, sector;
54 keyslot_sectors = div_round_up(keyLen * stripes, SECTOR_SIZE);
55 sector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
57 for (i = 0; i < LUKS_NUMKEYS; i++) {
58 sector = round_up_modulo(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
59 sector += keyslot_sectors;
65 static int LUKS_check_device_size(const char *device,
69 uint64_t dev_size, req_sectors;
71 req_sectors = LUKS_device_sectors(keyLength, LUKS_STRIPES);
72 if (min_sectors > req_sectors)
73 req_sectors = min_sectors;
75 if(device_size(device, &dev_size)) {
76 log_dbg("Cannot get device size for device %s.", device);
80 return (req_sectors > (dev_size >> SECTOR_SHIFT));
83 /* Check keyslot to prevent access outside of header and keyslot area */
84 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
86 uint32_t secs_per_stripes;
88 /* First sectors is the header itself */
89 if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < LUKS_ALIGN_KEYSLOTS) {
90 log_dbg("Invalid offset %u in keyslot %u.",
91 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
95 /* Ignore following check for detached header where offset can be zero. */
96 if (phdr->payloadOffset == 0)
99 if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
100 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
101 phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
102 phdr->payloadOffset);
106 secs_per_stripes = div_round_up(phdr->keyBytes * phdr->keyblock[keyIndex].stripes, SECTOR_SIZE);
108 if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
109 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
110 "keyslot %u (beyond data area offset %u).",
112 phdr->keyblock[keyIndex].keyMaterialOffset,
113 phdr->keyblock[keyIndex].stripes,
114 keyIndex, phdr->payloadOffset);
121 static const char *dbg_slot_state(crypt_keyslot_info ki)
124 case CRYPT_SLOT_INACTIVE:
126 case CRYPT_SLOT_ACTIVE:
128 case CRYPT_SLOT_ACTIVE_LAST:
129 return "ACTIVE_LAST";
130 case CRYPT_SLOT_INVALID:
137 const char *backup_file,
139 struct luks_phdr *hdr,
140 struct crypt_device *ctx)
142 int r = 0, devfd = -1;
147 if(stat(backup_file, &st) == 0) {
148 log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
152 r = LUKS_read_phdr(device, hdr, 1, ctx);
156 buffer_size = hdr->payloadOffset << SECTOR_SHIFT;
157 buffer = crypt_safe_alloc(buffer_size);
158 if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
163 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
164 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
166 devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
168 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
173 if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
179 /* Wipe unused area, so backup cannot contain old signatures */
180 memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
182 devfd = creat(backup_file, S_IRUSR);
187 if(write(devfd, buffer, buffer_size) < buffer_size) {
188 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
198 crypt_safe_free(buffer);
202 int LUKS_hdr_restore(
203 const char *backup_file,
205 struct luks_phdr *hdr,
206 struct crypt_device *ctx)
208 int r = 0, devfd = -1, diff_uuid = 0;
210 char *buffer = NULL, msg[200];
212 struct luks_phdr hdr_file;
214 if(stat(backup_file, &st) < 0) {
215 log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
219 r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
220 buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
222 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
223 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
228 buffer = crypt_safe_alloc(buffer_size);
234 devfd = open(backup_file, O_RDONLY);
236 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
241 if(read(devfd, buffer, buffer_size) < buffer_size) {
242 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
248 r = LUKS_read_phdr(device, hdr, 0, ctx);
250 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
251 if(hdr->payloadOffset != hdr_file.payloadOffset ||
252 hdr->keyBytes != hdr_file.keyBytes) {
253 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
257 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
261 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
262 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
263 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
264 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
269 if (!crypt_confirm(ctx, msg)) {
274 log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
275 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
277 devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
279 log_err(ctx, _("Cannot open device %s.\n"), device);
284 if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
290 /* Be sure to reload new data */
291 r = LUKS_read_phdr(device, hdr, 1, ctx);
295 crypt_safe_free(buffer);
299 static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
301 struct luks_phdr temp_phdr;
302 const unsigned char *sector = (const unsigned char*)phdr;
303 struct volume_key *vk;
304 uint64_t PBKDF2_per_sec = 1;
307 // FIXME check keyBytes
308 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
310 // FIXME check cipher, cipher_mode, hash, uuid, payloadOffset
311 LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
312 phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
313 phdr->payloadOffset, 0,
317 for(i = 0; i < LUKS_NUMKEYS; ++i) {
319 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
320 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
321 (unsigned)phdr->keyblock[i].keyMaterialOffset,
322 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
323 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
327 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
328 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
329 (unsigned)phdr->keyblock[i].stripes,
330 (unsigned)temp_phdr.keyblock[i].stripes);
331 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
335 /* if enabled, do not try to fix it */
336 if (phdr->keyblock[i].active != LUKS_KEY_ENABLED) {
337 /* Known case - MSDOS partition table signature */
338 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
339 log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
344 log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
345 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
346 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
347 phdr->keyblock[i].passwordIterations = 0;
352 crypt_free_volume_key(vk);
353 memset(&temp_phdr, 0, sizeof(temp_phdr));
355 return LUKS_write_phdr(device, phdr, ctx);
358 static int _check_and_convert_hdr(const char *device,
359 struct luks_phdr *hdr,
360 int require_luks_device,
361 struct crypt_device *ctx)
365 char luksMagic[] = LUKS_MAGIC;
367 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
368 log_dbg("LUKS header not detected.");
369 if (require_luks_device)
370 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
372 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
373 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
375 } else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
376 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
379 hdr->payloadOffset = ntohl(hdr->payloadOffset);
380 hdr->keyBytes = ntohl(hdr->keyBytes);
381 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
383 for(i = 0; i < LUKS_NUMKEYS; ++i) {
384 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
385 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
386 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
387 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
388 if (LUKS_check_keyslot_size(hdr, i)) {
389 log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
394 /* Avoid unterminated strings */
395 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
396 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
397 hdr->uuid[UUID_STRING_L - 1] = '\0';
400 log_err(ctx, _("Repairing keyslots.\n"));
401 r = _keyslot_repair(device, hdr, ctx);
409 static void _to_lower(char *str, unsigned max_len)
411 for(; *str && max_len; str++, max_len--)
413 *str = tolower(*str);
416 static void LUKS_fix_header_compatible(struct luks_phdr *header)
418 /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
419 * so always convert hash to lower case in header */
420 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
423 int LUKS_read_phdr_backup(const char *backup_file,
425 struct luks_phdr *hdr,
426 int require_luks_device,
427 struct crypt_device *ctx)
429 ssize_t hdr_size = sizeof(struct luks_phdr);
430 int devfd = 0, r = 0;
432 log_dbg("Reading LUKS header of size %d from backup file %s",
433 (int)hdr_size, backup_file);
435 devfd = open(backup_file, O_RDONLY);
437 log_err(ctx, _("Cannot open file %s.\n"), device);
441 if (read(devfd, hdr, hdr_size) < hdr_size)
444 LUKS_fix_header_compatible(hdr);
445 r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx);
452 int LUKS_read_phdr(const char *device,
453 struct luks_phdr *hdr,
454 int require_luks_device,
455 struct crypt_device *ctx)
457 ssize_t hdr_size = sizeof(struct luks_phdr);
458 int devfd = 0, r = 0;
460 log_dbg("Reading LUKS header of size %d from device %s",
463 devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
465 log_err(ctx, _("Cannot open device %s.\n"), device);
469 if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
472 r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx);
478 int LUKS_write_phdr(const char *device,
479 struct luks_phdr *hdr,
480 struct crypt_device *ctx)
482 ssize_t hdr_size = sizeof(struct luks_phdr);
485 struct luks_phdr convHdr;
488 log_dbg("Updating LUKS header of size %d on device %s",
489 sizeof(struct luks_phdr), device);
491 if (LUKS_check_device_size(device, hdr->payloadOffset, hdr->keyBytes)) {
492 log_err(ctx, _("Device %s is too small.\n"), device);
496 devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
498 log_err(ctx, _("Cannot open device %s.\n"), device);
502 memcpy(&convHdr, hdr, hdr_size);
503 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
505 /* Convert every uint16/32_t item to network byte order */
506 convHdr.version = htons(hdr->version);
507 convHdr.payloadOffset = htonl(hdr->payloadOffset);
508 convHdr.keyBytes = htonl(hdr->keyBytes);
509 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
510 for(i = 0; i < LUKS_NUMKEYS; ++i) {
511 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
512 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
513 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
514 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
517 r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
519 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
522 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
524 r = LUKS_read_phdr(device, hdr, 1, ctx);
526 log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
532 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
533 uint64_t *PBKDF2_per_sec,
534 struct crypt_device *ctx)
536 if (!*PBKDF2_per_sec) {
537 if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
538 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
541 log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
547 int LUKS_generate_phdr(struct luks_phdr *header,
548 const struct volume_key *vk,
549 const char *cipherName, const char *cipherMode, const char *hashSpec,
550 const char *uuid, unsigned int stripes,
551 unsigned int alignPayload,
552 unsigned int alignOffset,
553 uint32_t iteration_time_ms,
554 uint64_t *PBKDF2_per_sec,
555 const char *metadata_device,
556 struct crypt_device *ctx)
559 unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
561 uuid_t partitionUuid;
563 char luksMagic[] = LUKS_MAGIC;
565 /* For separate metadata device allow zero alignment */
566 if (alignPayload == 0 && !metadata_device)
567 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
569 if (PBKDF2_HMAC_ready(hashSpec) < 0) {
570 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
574 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
575 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
579 uuid_generate(partitionUuid);
581 memset(header,0,sizeof(struct luks_phdr));
584 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
586 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
587 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
588 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
590 header->keyBytes=vk->keylength;
592 LUKS_fix_header_compatible(header);
594 log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
595 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
598 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_NORMAL);
600 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
604 if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
607 /* Compute master key digest */
608 iteration_time_ms /= 8;
609 header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
610 LUKS_MKD_ITERATIONS_MIN);
612 r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
613 header->mkDigestSalt,LUKS_SALTSIZE,
614 header->mkDigestIterations,
615 header->mkDigest,LUKS_DIGESTSIZE);
617 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
622 currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
623 for(i = 0; i < LUKS_NUMKEYS; ++i) {
624 header->keyblock[i].active = LUKS_KEY_DISABLED;
625 header->keyblock[i].keyMaterialOffset = currentSector;
626 header->keyblock[i].stripes = stripes;
627 currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
628 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
631 if (metadata_device) {
632 /* for separate metadata device use alignPayload directly */
633 header->payloadOffset = alignPayload;
635 /* alignOffset - offset from natural device alignment provided by topology info */
636 currentSector = round_up_modulo(currentSector, alignPayload);
637 header->payloadOffset = currentSector + alignOffset;
640 uuid_unparse(partitionUuid, header->uuid);
642 log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
643 header->payloadOffset, header->uuid, header->mkDigestIterations);
648 int LUKS_hdr_uuid_set(
650 struct luks_phdr *hdr,
652 struct crypt_device *ctx)
654 uuid_t partitionUuid;
656 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
657 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
661 uuid_generate(partitionUuid);
663 uuid_unparse(partitionUuid, hdr->uuid);
665 return LUKS_write_phdr(device, hdr, ctx);
668 int LUKS_set_key(const char *device, unsigned int keyIndex,
669 const char *password, size_t passwordLen,
670 struct luks_phdr *hdr, struct volume_key *vk,
671 uint32_t iteration_time_ms,
672 uint64_t *PBKDF2_per_sec,
673 struct crypt_device *ctx)
675 struct volume_key *derived_key;
677 unsigned int AFEKSize;
678 uint64_t PBKDF2_temp;
681 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
682 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
686 if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
687 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
692 log_dbg("Calculating data for key slot %d", keyIndex);
694 if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
698 * Avoid floating point operation
699 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
701 PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
703 if (PBKDF2_temp > UINT32_MAX)
704 PBKDF2_temp = UINT32_MAX;
705 hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
706 LUKS_SLOT_ITERATIONS_MIN);
708 log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
710 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
714 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
715 LUKS_SALTSIZE, CRYPT_RND_NORMAL);
719 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
720 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
721 hdr->keyblock[keyIndex].passwordIterations,
722 derived_key->key, hdr->keyBytes);
727 * AF splitting, the masterkey stored in vk->key is split to AfKey
729 assert(vk->keylength == hdr->keyBytes);
730 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
731 AfKey = crypt_safe_alloc(AFEKSize);
737 log_dbg("Using hash %s for AF in key slot %d, %d stripes",
738 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
739 r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
743 log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
744 hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
745 /* Encryption via dm */
746 r = LUKS_encrypt_to_storage(AfKey,
751 hdr->keyblock[keyIndex].keyMaterialOffset,
754 log_err(ctx, _("Failed to write to key storage.\n"));
758 /* Mark the key as active in phdr */
759 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
763 r = LUKS_write_phdr(device, hdr, ctx);
769 crypt_safe_free(AfKey);
770 crypt_free_volume_key(derived_key);
774 /* Check whether a volume key is invalid. */
775 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
776 const struct volume_key *vk)
778 char checkHashBuf[LUKS_DIGESTSIZE];
780 if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
781 hdr->mkDigestSalt, LUKS_SALTSIZE,
782 hdr->mkDigestIterations, checkHashBuf,
783 LUKS_DIGESTSIZE) < 0)
786 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
792 /* Try to open a particular key slot */
793 static int LUKS_open_key(const char *device,
794 unsigned int keyIndex,
795 const char *password,
797 struct luks_phdr *hdr,
798 struct volume_key *vk,
799 struct crypt_device *ctx)
801 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
802 struct volume_key *derived_key;
807 log_dbg("Trying to open key slot %d [%s].", keyIndex,
810 if (ki < CRYPT_SLOT_ACTIVE)
813 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
817 assert(vk->keylength == hdr->keyBytes);
818 AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
819 AfKey = crypt_safe_alloc(AFEKSize);
823 r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
824 hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
825 hdr->keyblock[keyIndex].passwordIterations,
826 derived_key->key, hdr->keyBytes);
830 log_dbg("Reading key slot %d area.", keyIndex);
831 r = LUKS_decrypt_from_storage(AfKey,
836 hdr->keyblock[keyIndex].keyMaterialOffset,
839 log_err(ctx, _("Failed to read from key storage.\n"));
843 r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
847 r = LUKS_verify_volume_key(hdr, vk);
849 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
851 crypt_safe_free(AfKey);
852 crypt_free_volume_key(derived_key);
856 int LUKS_open_key_with_hdr(const char *device,
858 const char *password,
860 struct luks_phdr *hdr,
861 struct volume_key **vk,
862 struct crypt_device *ctx)
867 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
870 r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
871 return (r < 0) ? r : keyIndex;
874 for(i = 0; i < LUKS_NUMKEYS; i++) {
875 r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
879 /* Do not retry for errors that are no -EPERM or -ENOENT,
880 former meaning password wrong, latter key slot inactive */
881 if ((r != -EPERM) && (r != -ENOENT))
884 /* Warning, early returns above */
885 log_err(ctx, _("No key available with this passphrase.\n"));
889 int LUKS_del_key(const char *device,
890 unsigned int keyIndex,
891 struct luks_phdr *hdr,
892 struct crypt_device *ctx)
894 unsigned int startOffset, endOffset, stripesLen;
897 r = LUKS_read_phdr(device, hdr, 1, ctx);
901 r = LUKS_keyslot_set(hdr, keyIndex, 0);
903 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
904 keyIndex, LUKS_NUMKEYS - 1);
908 /* secure deletion of key material */
909 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
910 stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
911 endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
913 r = crypt_wipe(device, startOffset * SECTOR_SIZE,
914 (endOffset - startOffset) * SECTOR_SIZE,
917 log_err(ctx, _("Cannot wipe device %s.\n"), device);
921 /* Wipe keyslot info */
922 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
923 hdr->keyblock[keyIndex].passwordIterations = 0;
925 r = LUKS_write_phdr(device, hdr, ctx);
930 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
934 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
935 return CRYPT_SLOT_INVALID;
937 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
938 return CRYPT_SLOT_INACTIVE;
940 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
941 return CRYPT_SLOT_INVALID;
943 for(i = 0; i < LUKS_NUMKEYS; i++)
944 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
945 return CRYPT_SLOT_ACTIVE;
947 return CRYPT_SLOT_ACTIVE_LAST;
950 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
954 for (i = 0; i < LUKS_NUMKEYS; i++)
955 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
958 if (i == LUKS_NUMKEYS)
964 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
968 for (i = 0; i < LUKS_NUMKEYS; i++)
969 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
975 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
977 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
979 if (ki == CRYPT_SLOT_INVALID)
982 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
983 log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
987 int LUKS1_activate(struct crypt_device *cd,
989 struct volume_key *vk,
993 char *dm_cipher = NULL;
994 struct crypt_dm_active_device dmd = {
995 .device = crypt_get_device_name(cd),
997 .uuid = crypt_get_uuid(cd),
999 .offset = crypt_get_data_offset(cd),
1005 r = device_check_and_adjust(cd, dmd.device, DEV_EXCL,
1006 &dmd.size, &dmd.offset, &flags);
1010 r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1014 dmd.cipher = dm_cipher;
1015 r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);