2 * LUKS - Linux Unified Key Setup
4 * Copyright (C) 2004-2006 Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2009-2020 Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2013-2020 Milan Broz
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include <sys/types.h>
25 #include <netinet/in.h>
33 #include <uuid/uuid.h>
39 int LUKS_keyslot_area(const struct luks_phdr *hdr,
44 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
47 *offset = (uint64_t)hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
48 *length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;
53 /* insertsort: because the array has 8 elements and it's mostly sorted. that's why */
54 static void LUKS_sort_keyslots(const struct luks_phdr *hdr, int *array)
58 for (i = 1; i < LUKS_NUMKEYS; i++) {
60 while (j > 0 && hdr->keyblock[array[j-1]].keyMaterialOffset > hdr->keyblock[array[j]].keyMaterialOffset) {
62 array[j] = array[j-1];
69 size_t LUKS_device_sectors(const struct luks_phdr *hdr)
71 int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
73 LUKS_sort_keyslots(hdr, sorted_areas);
75 return hdr->keyblock[sorted_areas[LUKS_NUMKEYS-1]].keyMaterialOffset + AF_split_sectors(hdr->keyBytes, LUKS_STRIPES);
78 size_t LUKS_keyslots_offset(const struct luks_phdr *hdr)
80 int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
82 LUKS_sort_keyslots(hdr, sorted_areas);
84 return hdr->keyblock[sorted_areas[0]].keyMaterialOffset;
87 static int LUKS_check_device_size(struct crypt_device *ctx, const struct luks_phdr *hdr, int falloc)
89 struct device *device = crypt_metadata_device(ctx);
90 uint64_t dev_sectors, hdr_sectors;
95 if (device_size(device, &dev_sectors)) {
96 log_dbg(ctx, "Cannot get device size for device %s.", device_path(device));
100 dev_sectors >>= SECTOR_SHIFT;
101 hdr_sectors = LUKS_device_sectors(hdr);
102 log_dbg(ctx, "Key length %u, device size %" PRIu64 " sectors, header size %"
103 PRIu64 " sectors.", hdr->keyBytes, dev_sectors, hdr_sectors);
105 if (hdr_sectors > dev_sectors) {
106 /* If it is header file, increase its size */
107 if (falloc && !device_fallocate(device, hdr_sectors << SECTOR_SHIFT))
110 log_err(ctx, _("Device %s is too small. (LUKS1 requires at least %" PRIu64 " bytes.)"),
111 device_path(device), hdr_sectors * SECTOR_SIZE);
118 static int LUKS_check_keyslots(struct crypt_device *ctx, const struct luks_phdr *phdr)
120 int i, prev, next, sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
121 uint32_t secs_per_stripes = AF_split_sectors(phdr->keyBytes, LUKS_STRIPES);
123 LUKS_sort_keyslots(phdr, sorted_areas);
125 /* Check keyslot to prevent access outside of header and keyslot area */
126 for (i = 0; i < LUKS_NUMKEYS; i++) {
127 /* enforce stripes == 4000 */
128 if (phdr->keyblock[i].stripes != LUKS_STRIPES) {
129 log_dbg(ctx, "Invalid stripes count %u in keyslot %u.",
130 phdr->keyblock[i].stripes, i);
131 log_err(ctx, _("LUKS keyslot %u is invalid."), i);
135 /* First sectors is the header itself */
136 if (phdr->keyblock[i].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
137 log_dbg(ctx, "Invalid offset %u in keyslot %u.",
138 phdr->keyblock[i].keyMaterialOffset, i);
139 log_err(ctx, _("LUKS keyslot %u is invalid."), i);
143 /* Ignore following check for detached header where offset can be zero. */
144 if (phdr->payloadOffset == 0)
147 if (phdr->payloadOffset <= phdr->keyblock[i].keyMaterialOffset) {
148 log_dbg(ctx, "Invalid offset %u in keyslot %u (beyond data area offset %u).",
149 phdr->keyblock[i].keyMaterialOffset, i,
150 phdr->payloadOffset);
151 log_err(ctx, _("LUKS keyslot %u is invalid."), i);
155 if (phdr->payloadOffset < (phdr->keyblock[i].keyMaterialOffset + secs_per_stripes)) {
156 log_dbg(ctx, "Invalid keyslot size %u (offset %u, stripes %u) in "
157 "keyslot %u (beyond data area offset %u).",
159 phdr->keyblock[i].keyMaterialOffset,
160 phdr->keyblock[i].stripes,
161 i, phdr->payloadOffset);
162 log_err(ctx, _("LUKS keyslot %u is invalid."), i);
167 /* check no keyslot overlaps with each other */
168 for (i = 1; i < LUKS_NUMKEYS; i++) {
169 prev = sorted_areas[i-1];
170 next = sorted_areas[i];
171 if (phdr->keyblock[next].keyMaterialOffset <
172 (phdr->keyblock[prev].keyMaterialOffset + secs_per_stripes)) {
173 log_dbg(ctx, "Not enough space in LUKS keyslot %d.", prev);
174 log_err(ctx, _("LUKS keyslot %u is invalid."), prev);
178 /* do not check last keyslot on purpose, it must be tested in device size check */
183 static const char *dbg_slot_state(crypt_keyslot_info ki)
186 case CRYPT_SLOT_INACTIVE:
188 case CRYPT_SLOT_ACTIVE:
190 case CRYPT_SLOT_ACTIVE_LAST:
191 return "ACTIVE_LAST";
192 case CRYPT_SLOT_INVALID:
198 int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
200 struct device *device = crypt_metadata_device(ctx);
201 struct luks_phdr hdr;
202 int fd, devfd, r = 0;
208 r = LUKS_read_phdr(&hdr, 1, 0, ctx);
212 hdr_size = LUKS_device_sectors(&hdr) << SECTOR_SHIFT;
213 buffer_size = size_round_up(hdr_size, crypt_getpagesize());
215 buffer = crypt_safe_alloc(buffer_size);
216 if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
221 log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
222 sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);
224 log_dbg(ctx, "Output backup file size: %zu bytes.", buffer_size);
226 devfd = device_open(ctx, device, O_RDONLY);
228 log_err(ctx, _("Device %s is not a valid LUKS device."), device_path(device));
233 if (read_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
234 buffer, hdr_size, 0) < (ssize_t)hdr_size) {
239 /* Wipe unused area, so backup cannot contain old signatures */
240 if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
241 memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));
243 fd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
246 log_err(ctx, _("Requested header backup file %s already exists."), backup_file);
248 log_err(ctx, _("Cannot create header backup file %s."), backup_file);
252 ret = write_buffer(fd, buffer, buffer_size);
254 if (ret < (ssize_t)buffer_size) {
255 log_err(ctx, _("Cannot write header backup file %s."), backup_file);
262 crypt_safe_memzero(&hdr, sizeof(hdr));
263 crypt_safe_free(buffer);
267 int LUKS_hdr_restore(
268 const char *backup_file,
269 struct luks_phdr *hdr,
270 struct crypt_device *ctx)
272 struct device *device = crypt_metadata_device(ctx);
273 int fd, r = 0, devfd = -1, diff_uuid = 0;
274 ssize_t ret, buffer_size = 0;
275 char *buffer = NULL, msg[200];
276 struct luks_phdr hdr_file;
278 r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
283 buffer_size = LUKS_device_sectors(&hdr_file) << SECTOR_SHIFT;
285 if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
286 log_err(ctx, _("Backup file does not contain valid LUKS header."));
291 buffer = crypt_safe_alloc(buffer_size);
297 fd = open(backup_file, O_RDONLY);
299 log_err(ctx, _("Cannot open header backup file %s."), backup_file);
304 ret = read_buffer(fd, buffer, buffer_size);
306 if (ret < buffer_size) {
307 log_err(ctx, _("Cannot read header backup file %s."), backup_file);
312 r = LUKS_read_phdr(hdr, 0, 0, ctx);
314 log_dbg(ctx, "Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
315 if(hdr->payloadOffset != hdr_file.payloadOffset ||
316 hdr->keyBytes != hdr_file.keyBytes) {
317 log_err(ctx, _("Data offset or key size differs on device and backup, restore failed."));
321 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
325 if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
326 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
327 _("already contains LUKS header. Replacing header will destroy existing keyslots."),
328 diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
333 if (!crypt_confirm(ctx, msg)) {
338 log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes) to device %s.",
339 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
341 devfd = device_open(ctx, device, O_RDWR);
344 log_err(ctx, _("Cannot write to device %s, permission denied."),
345 device_path(device));
347 log_err(ctx, _("Cannot open device %s."), device_path(device));
352 if (write_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
353 buffer, buffer_size, 0) < buffer_size) {
358 /* Be sure to reload new data */
359 r = LUKS_read_phdr(hdr, 1, 0, ctx);
361 device_sync(ctx, device);
362 crypt_safe_free(buffer);
366 /* This routine should do some just basic recovery for known problems. */
367 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
369 struct luks_phdr temp_phdr;
370 const unsigned char *sector = (const unsigned char*)phdr;
371 struct volume_key *vk;
372 int i, bad, r, need_write = 0;
374 if (phdr->keyBytes != 16 && phdr->keyBytes != 32 && phdr->keyBytes != 64) {
375 log_err(ctx, _("Non standard key size, manual repair required."));
378 /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
379 if (LUKS_keyslots_offset(phdr) < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
380 log_err(ctx, _("Non standard keyslots alignment, manual repair required."));
384 r = LUKS_check_cipher(ctx, phdr->keyBytes, phdr->cipherName, phdr->cipherMode);
388 vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
390 log_verbose(ctx, _("Repairing keyslots."));
392 log_dbg(ctx, "Generating second header with the same parameters for check.");
393 /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
394 /* payloadOffset - cannot check */
395 r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
396 phdr->hashSpec, phdr->uuid,
397 phdr->payloadOffset * SECTOR_SIZE, 0, 0, ctx);
401 for(i = 0; i < LUKS_NUMKEYS; ++i) {
402 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED) {
403 log_dbg(ctx, "Skipping repair for active keyslot %i.", i);
408 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
409 log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u)."), i,
410 (unsigned)phdr->keyblock[i].keyMaterialOffset,
411 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
412 phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
416 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
417 log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u)."), i,
418 (unsigned)phdr->keyblock[i].stripes,
419 (unsigned)temp_phdr.keyblock[i].stripes);
420 phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
424 /* Known case - MSDOS partition table signature */
425 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
426 log_err(ctx, _("Keyslot %i: bogus partition signature."), i);
431 log_err(ctx, _("Keyslot %i: salt wiped."), i);
432 phdr->keyblock[i].active = LUKS_KEY_DISABLED;
433 memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
434 phdr->keyblock[i].passwordIterations = 0;
442 * check repair result before writing because repair can't fix out of order
443 * keyslot offsets and would corrupt header again
445 if (LUKS_check_keyslots(ctx, phdr))
447 else if (need_write) {
448 log_verbose(ctx, _("Writing LUKS header to disk."));
449 r = LUKS_write_phdr(phdr, ctx);
453 log_err(ctx, _("Repair failed."));
454 crypt_free_volume_key(vk);
455 crypt_safe_memzero(&temp_phdr, sizeof(temp_phdr));
459 static int _check_and_convert_hdr(const char *device,
460 struct luks_phdr *hdr,
461 int require_luks_device,
463 struct crypt_device *ctx)
467 char luksMagic[] = LUKS_MAGIC;
469 if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
470 log_dbg(ctx, "LUKS header not detected.");
471 if (require_luks_device)
472 log_err(ctx, _("Device %s is not a valid LUKS device."), device);
474 } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */
475 log_err(ctx, _("Unsupported LUKS version %d."), hdr->version);
479 hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
480 if (crypt_hmac_size(hdr->hashSpec) < LUKS_DIGESTSIZE) {
481 log_err(ctx, _("Requested LUKS hash %s is not supported."), hdr->hashSpec);
485 /* Header detected */
486 hdr->payloadOffset = ntohl(hdr->payloadOffset);
487 hdr->keyBytes = ntohl(hdr->keyBytes);
488 hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
490 for(i = 0; i < LUKS_NUMKEYS; ++i) {
491 hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active);
492 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
493 hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset);
494 hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes);
497 if (LUKS_check_keyslots(ctx, hdr))
500 /* Avoid unterminated strings */
501 hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
502 hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
503 hdr->uuid[UUID_STRING_L - 1] = '\0';
507 r = _keyslot_repair(hdr, ctx);
509 log_verbose(ctx, _("No known problems detected for LUKS header."));
515 static void _to_lower(char *str, unsigned max_len)
517 for(; *str && max_len; str++, max_len--)
519 *str = tolower(*str);
522 static void LUKS_fix_header_compatible(struct luks_phdr *header)
524 /* Old cryptsetup expects "sha1", gcrypt allows case insensitive names,
525 * so always convert hash to lower case in header */
526 _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
528 /* ECB mode does not use IV but dmcrypt silently allows it.
529 * Drop any IV here if ECB is used (that is not secure anyway).*/
530 if (!strncmp(header->cipherMode, "ecb-", 4)) {
531 memset(header->cipherMode, 0, LUKS_CIPHERMODE_L);
532 strcpy(header->cipherMode, "ecb");
536 int LUKS_read_phdr_backup(const char *backup_file,
537 struct luks_phdr *hdr,
538 int require_luks_device,
539 struct crypt_device *ctx)
541 ssize_t hdr_size = sizeof(struct luks_phdr);
542 int devfd = 0, r = 0;
544 log_dbg(ctx, "Reading LUKS header of size %d from backup file %s",
545 (int)hdr_size, backup_file);
547 devfd = open(backup_file, O_RDONLY);
549 log_err(ctx, _("Cannot open header backup file %s."), backup_file);
553 if (read_buffer(devfd, hdr, hdr_size) < hdr_size)
556 LUKS_fix_header_compatible(hdr);
557 r = _check_and_convert_hdr(backup_file, hdr,
558 require_luks_device, 0, ctx);
565 int LUKS_read_phdr(struct luks_phdr *hdr,
566 int require_luks_device,
568 struct crypt_device *ctx)
571 struct device *device = crypt_metadata_device(ctx);
572 ssize_t hdr_size = sizeof(struct luks_phdr);
574 /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
575 assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
577 /* Stripes count cannot be changed without additional code fixes yet */
578 assert(LUKS_STRIPES == 4000);
580 if (repair && !require_luks_device)
583 log_dbg(ctx, "Reading LUKS header of size %zu from device %s",
584 hdr_size, device_path(device));
586 devfd = device_open(ctx, device, O_RDONLY);
588 log_err(ctx, _("Cannot open device %s."), device_path(device));
592 if (read_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
593 hdr, hdr_size, 0) < hdr_size)
596 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
600 r = LUKS_check_device_size(ctx, hdr, 0);
603 * Cryptsetup 1.0.0 did not align keyslots to 4k (very rare version).
604 * Disable direct-io to avoid possible IO errors if underlying device
605 * has bigger sector size.
607 if (!r && hdr->keyblock[0].keyMaterialOffset * SECTOR_SIZE < LUKS_ALIGN_KEYSLOTS) {
608 log_dbg(ctx, "Old unaligned LUKS keyslot detected, disabling direct-io.");
609 device_disable_direct_io(device);
615 int LUKS_write_phdr(struct luks_phdr *hdr,
616 struct crypt_device *ctx)
618 struct device *device = crypt_metadata_device(ctx);
619 ssize_t hdr_size = sizeof(struct luks_phdr);
622 struct luks_phdr convHdr;
625 log_dbg(ctx, "Updating LUKS header of size %zu on device %s",
626 sizeof(struct luks_phdr), device_path(device));
628 r = LUKS_check_device_size(ctx, hdr, 1);
632 devfd = device_open(ctx, device, O_RDWR);
635 log_err(ctx, _("Cannot write to device %s, permission denied."),
636 device_path(device));
638 log_err(ctx, _("Cannot open device %s."), device_path(device));
642 memcpy(&convHdr, hdr, hdr_size);
643 memset(&convHdr._padding, 0, sizeof(convHdr._padding));
645 /* Convert every uint16/32_t item to network byte order */
646 convHdr.version = htons(hdr->version);
647 convHdr.payloadOffset = htonl(hdr->payloadOffset);
648 convHdr.keyBytes = htonl(hdr->keyBytes);
649 convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
650 for(i = 0; i < LUKS_NUMKEYS; ++i) {
651 convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active);
652 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
653 convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset);
654 convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes);
657 r = write_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
658 &convHdr, hdr_size, 0) < hdr_size ? -EIO : 0;
660 log_err(ctx, _("Error during update of LUKS header on device %s."), device_path(device));
662 device_sync(ctx, device);
664 /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
666 r = LUKS_read_phdr(hdr, 1, 0, ctx);
668 log_err(ctx, _("Error re-reading LUKS header after update on device %s."),
669 device_path(device));
675 /* Check that kernel supports requested cipher by decryption of one sector */
676 int LUKS_check_cipher(struct crypt_device *ctx, size_t keylength, const char *cipher, const char *cipher_mode)
679 struct volume_key *empty_key;
680 char buf[SECTOR_SIZE];
682 log_dbg(ctx, "Checking if cipher %s-%s is usable.", cipher, cipher_mode);
684 empty_key = crypt_alloc_volume_key(keylength, NULL);
688 /* No need to get KEY quality random but it must avoid known weak keys. */
689 r = crypt_random_get(ctx, empty_key->key, empty_key->keylength, CRYPT_RND_NORMAL);
691 r = LUKS_decrypt_from_storage(buf, sizeof(buf), cipher, cipher_mode, empty_key, 0, ctx);
693 crypt_free_volume_key(empty_key);
694 crypt_safe_memzero(buf, sizeof(buf));
698 int LUKS_generate_phdr(struct luks_phdr *header,
699 const struct volume_key *vk,
700 const char *cipherName,
701 const char *cipherMode,
702 const char *hashSpec,
704 uint64_t data_offset, /* in bytes */
705 uint64_t align_offset, /* in bytes */
706 uint64_t required_alignment, /* in bytes */
707 struct crypt_device *ctx)
710 size_t keyslot_sectors, header_sectors;
711 uuid_t partitionUuid;
712 struct crypt_pbkdf_type *pbkdf;
714 char luksMagic[] = LUKS_MAGIC;
716 if (data_offset % SECTOR_SIZE || align_offset % SECTOR_SIZE ||
717 required_alignment % SECTOR_SIZE)
720 memset(header, 0, sizeof(struct luks_phdr));
722 keyslot_sectors = AF_split_sectors(vk->keylength, LUKS_STRIPES);
723 header_sectors = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
725 for (i = 0; i < LUKS_NUMKEYS; i++) {
726 header->keyblock[i].active = LUKS_KEY_DISABLED;
727 header->keyblock[i].keyMaterialOffset = header_sectors;
728 header->keyblock[i].stripes = LUKS_STRIPES;
729 header_sectors = size_round_up(header_sectors + keyslot_sectors,
730 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
732 /* In sector is now size of all keyslot material space */
734 /* Data offset has priority */
736 header->payloadOffset = data_offset / SECTOR_SIZE;
737 else if (required_alignment) {
738 header->payloadOffset = size_round_up(header_sectors, (required_alignment / SECTOR_SIZE));
739 header->payloadOffset += (align_offset / SECTOR_SIZE);
741 header->payloadOffset = 0;
743 if (header->payloadOffset && header->payloadOffset < header_sectors) {
744 log_err(ctx, _("Data offset for LUKS header must be "
745 "either 0 or higher than header size."));
749 if (crypt_hmac_size(hashSpec) < LUKS_DIGESTSIZE) {
750 log_err(ctx, _("Requested LUKS hash %s is not supported."), hashSpec);
754 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
755 log_err(ctx, _("Wrong LUKS UUID format provided."));
759 uuid_generate(partitionUuid);
762 memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
764 strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L-1);
765 strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L-1);
766 strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L-1);
768 header->keyBytes=vk->keylength;
770 LUKS_fix_header_compatible(header);
772 log_dbg(ctx, "Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
773 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
776 r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
778 log_err(ctx, _("Cannot create LUKS header: reading random salt failed."));
782 /* Compute master key digest */
783 pbkdf = crypt_get_pbkdf(ctx);
784 r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
787 assert(pbkdf->iterations);
789 if (pbkdf->flags & CRYPT_PBKDF_NO_BENCHMARK && pbkdf->time_ms == 0)
790 PBKDF2_temp = LUKS_MKD_ITERATIONS_MIN;
791 else /* iterations per ms * LUKS_MKD_ITERATIONS_MS */
792 PBKDF2_temp = (double)pbkdf->iterations * LUKS_MKD_ITERATIONS_MS / pbkdf->time_ms;
794 if (PBKDF2_temp > (double)UINT32_MAX)
796 header->mkDigestIterations = at_least((uint32_t)PBKDF2_temp, LUKS_MKD_ITERATIONS_MIN);
797 assert(header->mkDigestIterations);
799 r = crypt_pbkdf(CRYPT_KDF_PBKDF2, header->hashSpec, vk->key,vk->keylength,
800 header->mkDigestSalt, LUKS_SALTSIZE,
801 header->mkDigest,LUKS_DIGESTSIZE,
802 header->mkDigestIterations, 0, 0);
804 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s)."),
809 uuid_unparse(partitionUuid, header->uuid);
811 log_dbg(ctx, "Data offset %d, UUID %s, digest iterations %" PRIu32,
812 header->payloadOffset, header->uuid, header->mkDigestIterations);
817 int LUKS_hdr_uuid_set(
818 struct luks_phdr *hdr,
820 struct crypt_device *ctx)
822 uuid_t partitionUuid;
824 if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
825 log_err(ctx, _("Wrong LUKS UUID format provided."));
829 uuid_generate(partitionUuid);
831 uuid_unparse(partitionUuid, hdr->uuid);
833 return LUKS_write_phdr(hdr, ctx);
836 int LUKS_set_key(unsigned int keyIndex,
837 const char *password, size_t passwordLen,
838 struct luks_phdr *hdr, struct volume_key *vk,
839 struct crypt_device *ctx)
841 struct volume_key *derived_key;
844 struct crypt_pbkdf_type *pbkdf;
847 if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
848 log_err(ctx, _("Key slot %d active, purge first."), keyIndex);
852 /* LUKS keyslot has always at least 4000 stripes according to specification */
853 if(hdr->keyblock[keyIndex].stripes < 4000) {
854 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?"),
859 log_dbg(ctx, "Calculating data for key slot %d", keyIndex);
860 pbkdf = crypt_get_pbkdf(ctx);
861 r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
864 assert(pbkdf->iterations);
867 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
869 hdr->keyblock[keyIndex].passwordIterations =
870 at_least(pbkdf->iterations, LUKS_SLOT_ITERATIONS_MIN);
871 log_dbg(ctx, "Key slot %d use %" PRIu32 " password iterations.", keyIndex,
872 hdr->keyblock[keyIndex].passwordIterations);
874 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
878 r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
879 LUKS_SALTSIZE, CRYPT_RND_SALT);
883 r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
884 hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
885 derived_key->key, hdr->keyBytes,
886 hdr->keyblock[keyIndex].passwordIterations, 0, 0);
891 * AF splitting, the masterkey stored in vk->key is split to AfKey
893 assert(vk->keylength == hdr->keyBytes);
894 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
895 AfKey = crypt_safe_alloc(AFEKSize);
901 log_dbg(ctx, "Using hash %s for AF in key slot %d, %d stripes",
902 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
903 r = AF_split(ctx, vk->key, AfKey, vk->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
907 log_dbg(ctx, "Updating key slot %d [0x%04x] area.", keyIndex,
908 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
909 /* Encryption via dm */
910 r = LUKS_encrypt_to_storage(AfKey,
912 hdr->cipherName, hdr->cipherMode,
914 hdr->keyblock[keyIndex].keyMaterialOffset,
919 /* Mark the key as active in phdr */
920 r = LUKS_keyslot_set(hdr, (int)keyIndex, 1, ctx);
924 r = LUKS_write_phdr(hdr, ctx);
930 crypt_safe_free(AfKey);
931 crypt_free_volume_key(derived_key);
935 /* Check whether a volume key is invalid. */
936 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
937 const struct volume_key *vk)
939 char checkHashBuf[LUKS_DIGESTSIZE];
941 if (crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, vk->key, vk->keylength,
942 hdr->mkDigestSalt, LUKS_SALTSIZE,
943 checkHashBuf, LUKS_DIGESTSIZE,
944 hdr->mkDigestIterations, 0, 0) < 0)
947 if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
953 /* Try to open a particular key slot */
954 static int LUKS_open_key(unsigned int keyIndex,
955 const char *password,
957 struct luks_phdr *hdr,
958 struct volume_key *vk,
959 struct crypt_device *ctx)
961 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
962 struct volume_key *derived_key;
967 log_dbg(ctx, "Trying to open key slot %d [%s].", keyIndex,
970 if (ki < CRYPT_SLOT_ACTIVE)
973 derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
977 assert(vk->keylength == hdr->keyBytes);
978 AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
979 AfKey = crypt_safe_alloc(AFEKSize);
985 r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
986 hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
987 derived_key->key, hdr->keyBytes,
988 hdr->keyblock[keyIndex].passwordIterations, 0, 0);
990 log_err(ctx, _("Cannot open keyslot (using hash %s)."), hdr->hashSpec);
994 log_dbg(ctx, "Reading key slot %d area.", keyIndex);
995 r = LUKS_decrypt_from_storage(AfKey,
997 hdr->cipherName, hdr->cipherMode,
999 hdr->keyblock[keyIndex].keyMaterialOffset,
1004 r = AF_merge(ctx, AfKey, vk->key, vk->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
1008 r = LUKS_verify_volume_key(hdr, vk);
1010 /* Allow only empty passphrase with null cipher */
1011 if (!r && !strcmp(hdr->cipherName, "cipher_null") && passwordLen)
1014 crypt_safe_free(AfKey);
1015 crypt_free_volume_key(derived_key);
1019 int LUKS_open_key_with_hdr(int keyIndex,
1020 const char *password,
1022 struct luks_phdr *hdr,
1023 struct volume_key **vk,
1024 struct crypt_device *ctx)
1026 unsigned int i, tried = 0;
1029 *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
1031 if (keyIndex >= 0) {
1032 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, *vk, ctx);
1033 return (r < 0) ? r : keyIndex;
1036 for (i = 0; i < LUKS_NUMKEYS; i++) {
1037 r = LUKS_open_key(i, password, passwordLen, hdr, *vk, ctx);
1041 /* Do not retry for errors that are no -EPERM or -ENOENT,
1042 former meaning password wrong, latter key slot inactive */
1043 if ((r != -EPERM) && (r != -ENOENT))
1048 /* Warning, early returns above */
1049 return tried ? -EPERM : -ENOENT;
1052 int LUKS_del_key(unsigned int keyIndex,
1053 struct luks_phdr *hdr,
1054 struct crypt_device *ctx)
1056 struct device *device = crypt_metadata_device(ctx);
1057 unsigned int startOffset, endOffset;
1060 r = LUKS_read_phdr(hdr, 1, 0, ctx);
1064 r = LUKS_keyslot_set(hdr, keyIndex, 0, ctx);
1066 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d."),
1067 keyIndex, LUKS_NUMKEYS - 1);
1071 /* secure deletion of key material */
1072 startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
1073 endOffset = startOffset + AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes);
1075 r = crypt_wipe_device(ctx, device, CRYPT_WIPE_SPECIAL, startOffset * SECTOR_SIZE,
1076 (endOffset - startOffset) * SECTOR_SIZE,
1077 (endOffset - startOffset) * SECTOR_SIZE, NULL, NULL);
1080 log_err(ctx, _("Cannot write to device %s, permission denied."),
1081 device_path(device));
1084 log_err(ctx, _("Cannot wipe device %s."),
1085 device_path(device));
1089 /* Wipe keyslot info */
1090 memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
1091 hdr->keyblock[keyIndex].passwordIterations = 0;
1093 r = LUKS_write_phdr(hdr, ctx);
1098 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
1102 if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
1103 return CRYPT_SLOT_INVALID;
1105 if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
1106 return CRYPT_SLOT_INACTIVE;
1108 if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1109 return CRYPT_SLOT_INVALID;
1111 for(i = 0; i < LUKS_NUMKEYS; i++)
1112 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1113 return CRYPT_SLOT_ACTIVE;
1115 return CRYPT_SLOT_ACTIVE_LAST;
1118 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1122 for (i = 0; i < LUKS_NUMKEYS; i++)
1123 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1126 if (i == LUKS_NUMKEYS)
1132 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1136 for (i = 0; i < LUKS_NUMKEYS; i++)
1137 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1143 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable, struct crypt_device *ctx)
1145 crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1147 if (ki == CRYPT_SLOT_INVALID)
1150 hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1151 log_dbg(ctx, "Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1155 int LUKS1_activate(struct crypt_device *cd,
1157 struct volume_key *vk,
1161 struct crypt_dm_active_device dmd = {
1163 .uuid = crypt_get_uuid(cd),
1166 r = dm_crypt_target_set(&dmd.segment, 0, dmd.size, crypt_data_device(cd),
1167 vk, crypt_get_cipher_spec(cd), crypt_get_iv_offset(cd),
1168 crypt_get_data_offset(cd), crypt_get_integrity(cd),
1169 crypt_get_integrity_tag_size(cd), crypt_get_sector_size(cd));
1171 r = create_or_reload_device(cd, name, CRYPT_LUKS1, &dmd);
1173 dm_targets_free(cd, &dmd);
1178 int LUKS_wipe_header_areas(struct luks_phdr *hdr,
1179 struct crypt_device *ctx)
1182 uint64_t offset, length;
1185 /* Wipe complete header, keyslots and padding areas with zeroes. */
1187 length = (uint64_t)hdr->payloadOffset * SECTOR_SIZE;
1188 wipe_block = 1024 * 1024;
1190 /* On detached header or bogus header, wipe at least the first 4k */
1191 if (length == 0 || length > (LUKS_MAX_KEYSLOT_SIZE * LUKS_NUMKEYS)) {
1196 log_dbg(ctx, "Wiping LUKS areas (0x%06" PRIx64 " - 0x%06" PRIx64") with zeroes.",
1197 offset, length + offset);
1199 r = crypt_wipe_device(ctx, crypt_metadata_device(ctx), CRYPT_WIPE_ZERO,
1200 offset, length, wipe_block, NULL, NULL);
1204 /* Wipe keyslots areas */
1205 wipe_block = 1024 * 1024;
1206 for (i = 0; i < LUKS_NUMKEYS; i++) {
1207 r = LUKS_keyslot_area(hdr, i, &offset, &length);
1211 /* Ignore too big LUKS1 keyslots here */
1212 if (length > LUKS_MAX_KEYSLOT_SIZE ||
1213 offset > (LUKS_MAX_KEYSLOT_SIZE - length))
1216 if (length == 0 || offset < 4096)
1219 log_dbg(ctx, "Wiping keyslot %i area (0x%06" PRIx64 " - 0x%06" PRIx64") with random data.",
1220 i, offset, length + offset);
1222 r = crypt_wipe_device(ctx, crypt_metadata_device(ctx), CRYPT_WIPE_RANDOM,
1223 offset, length, wipe_block, NULL, NULL);
1231 int LUKS_keyslot_pbkdf(struct luks_phdr *hdr, int keyslot, struct crypt_pbkdf_type *pbkdf)
1233 if (LUKS_keyslot_info(hdr, keyslot) < CRYPT_SLOT_ACTIVE)
1236 pbkdf->type = CRYPT_KDF_PBKDF2;
1237 pbkdf->hash = hdr->hashSpec;
1238 pbkdf->iterations = hdr->keyblock[keyslot].passwordIterations;
1239 pbkdf->max_memory_kb = 0;
1240 pbkdf->parallel_threads = 0;