keymanage.c 29 KB
Newer Older
1
/*
2
 * LUKS - Linux Unified Key Setup
3 4
 *
 * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
Milan Broz's avatar
Milan Broz committed
5
 * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6
 *
7 8 9 10 11 12 13 14 15 16 17
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 20
 */

21 22
#include <sys/types.h>
#include <sys/stat.h>
23
#include <netinet/in.h>
24 25 26
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
27
#include <stdio.h>
28 29
#include <stdlib.h>
#include <string.h>
30
#include <ctype.h>
31
#include <assert.h>
32
#include <uuid/uuid.h>
33 34 35 36

#include "luks.h"
#include "af.h"
#include "pbkdf.h"
37
#include "internal.h"
38 39 40 41 42 43 44 45 46 47 48

#define div_round_up(a,b) ({           \
	typeof(a) __a = (a);          \
	typeof(b) __b = (b);          \
	(__a - 1) / __b + 1;        \
})

static inline int round_up_modulo(int x, int m) {
	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)
51 52 53 54
{
	uint64_t keyslot_sectors, sector;
	int i;

55
	keyslot_sectors = div_round_up(keyLen * LUKS_STRIPES, SECTOR_SIZE);
56 57 58 59 60 61 62 63 64 65
	sector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);

	for (i = 0; i < LUKS_NUMKEYS; i++) {
		sector = round_up_modulo(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
		sector += keyslot_sectors;
	}

	return sector;
}

66
static int LUKS_check_device_size(struct crypt_device *ctx, const char *device,
67 68
				  size_t keyLength)
{
69
	uint64_t dev_sectors, hdr_sectors;
70

71 72 73 74
	if (!keyLength)
		return -EINVAL;

	if(device_size(device, &dev_sectors)) {
75 76 77 78
		log_dbg("Cannot get device size for device %s.", device);
		return -EIO;
	}

79 80 81 82 83 84
	dev_sectors >>= SECTOR_SHIFT;
	hdr_sectors = LUKS_device_sectors(keyLength);
	log_dbg("Key length %u, device size %" PRIu64 " sectors, header size %"
		PRIu64 " sectors.",keyLength, dev_sectors, hdr_sectors);

	if (hdr_sectors > dev_sectors) {
85 86 87 88 89
		log_err(ctx, _("Device %s is too small.\n"), device);
		return -EINVAL;
	}

	return 0;
90 91
}

92 93 94 95 96 97
/* Check keyslot to prevent access outside of header and keyslot area */
static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
{
	uint32_t secs_per_stripes;

	/* First sectors is the header itself */
98
	if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		log_dbg("Invalid offset %u in keyslot %u.",
			phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
		return 1;
	}

	/* Ignore following check for detached header where offset can be zero. */
	if (phdr->payloadOffset == 0)
		return 0;

	if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
		log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
			phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
			phdr->payloadOffset);
		return 1;
	}

	secs_per_stripes = div_round_up(phdr->keyBytes * phdr->keyblock[keyIndex].stripes, SECTOR_SIZE);

	if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
		log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
			"keyslot %u (beyond data area offset %u).",
			secs_per_stripes,
			phdr->keyblock[keyIndex].keyMaterialOffset,
			phdr->keyblock[keyIndex].stripes,
			keyIndex, phdr->payloadOffset);
		return 1;
	}

	return 0;
}

130
static const char *dbg_slot_state(crypt_keyslot_info ki)
Milan Broz's avatar
Milan Broz committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144
{
	switch(ki) {
	case CRYPT_SLOT_INACTIVE:
		return "INACTIVE";
	case CRYPT_SLOT_ACTIVE:
		return "ACTIVE";
	case CRYPT_SLOT_ACTIVE_LAST:
		return "ACTIVE_LAST";
	case CRYPT_SLOT_INVALID:
	default:
		return "INVALID";
	}
}

145 146 147 148 149
int LUKS_hdr_backup(
	const char *backup_file,
	const char *device,
	struct luks_phdr *hdr,
	struct crypt_device *ctx)
150
{
151
	int r = 0, devfd = -1;
152
	ssize_t buffer_size;
153 154
	char *buffer = NULL;
	struct stat st;
155

156 157 158 159
	if(stat(backup_file, &st) == 0) {
		log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
		return -EINVAL;
	}
160

161
	r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
162 163 164
	if (r)
		return r;

165
	buffer_size = LUKS_device_sectors(hdr->keyBytes) << SECTOR_SHIFT;
166
	buffer = crypt_safe_alloc(buffer_size);
167 168 169 170 171 172 173 174 175 176
	if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
		r = -ENOMEM;
		goto out;
	}

	log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
		sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);

	devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
	if(devfd == -1) {
177
		log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
		r = -EINVAL;
		goto out;
	}

	if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
		r = -EIO;
		goto out;
	}
	close(devfd);

	/* Wipe unused area, so backup cannot contain old signatures */
	memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));

	devfd = creat(backup_file, S_IRUSR);
	if(devfd == -1) {
		r = -EINVAL;
		goto out;
	}
	if(write(devfd, buffer, buffer_size) < buffer_size) {
		log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
		r = -EIO;
		goto out;
	}
	close(devfd);

	r = 0;
out:
	if (devfd != -1)
		close(devfd);
207
	crypt_safe_free(buffer);
208 209 210 211 212 213 214 215 216 217
	return r;
}

int LUKS_hdr_restore(
	const char *backup_file,
	const char *device,
	struct luks_phdr *hdr,
	struct crypt_device *ctx)
{
	int r = 0, devfd = -1, diff_uuid = 0;
218
	ssize_t buffer_size;
219 220 221 222 223 224 225 226 227 228
	char *buffer = NULL, msg[200];
	struct stat st;
	struct luks_phdr hdr_file;

	if(stat(backup_file, &st) < 0) {
		log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
		return -EINVAL;
	}

	r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
Milan Broz's avatar
Milan Broz committed
229
	if (!r)
230
		buffer_size = LUKS_device_sectors(hdr_file.keyBytes) << SECTOR_SHIFT;
231 232

	if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
Milan Broz's avatar
Milan Broz committed
233
		log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
234 235 236 237
		r = -EINVAL;
		goto out;
	}

238
	buffer = crypt_safe_alloc(buffer_size);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
	if (!buffer) {
		r = -ENOMEM;
		goto out;
	}

	devfd = open(backup_file, O_RDONLY);
	if(devfd == -1) {
		log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
		r = -EINVAL;
		goto out;
	}

	if(read(devfd, buffer, buffer_size) < buffer_size) {
		log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
		r = -EIO;
		goto out;
	}
	close(devfd);

258
	r = LUKS_read_phdr(device, hdr, 0, 0, ctx);
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
	if (r == 0) {
		log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
		if(hdr->payloadOffset != hdr_file.payloadOffset ||
		   hdr->keyBytes != hdr_file.keyBytes) {
			log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
			r = -EINVAL;
			goto out;
		}
		if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
			diff_uuid = 1;
	}

	if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
		 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
		     _("already contains LUKS header. Replacing header will destroy existing keyslots."),
		     diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
		r = -ENOMEM;
		goto out;
	}

	if (!crypt_confirm(ctx, msg)) {
		r = -EINVAL;
		goto out;
	}

	log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
		sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);

	devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
	if(devfd == -1) {
289
		log_err(ctx, _("Cannot open device %s.\n"), device);
290 291
		r = -EINVAL;
		goto out;
292 293
	}

294
	if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
295
		r = -EIO;
296 297 298 299 300
		goto out;
	}
	close(devfd);

	/* Be sure to reload new data */
301
	r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
302 303 304
out:
	if (devfd != -1)
		close(devfd);
305
	crypt_safe_free(buffer);
306 307 308
	return r;
}

309
/* This routine should do some just basic recovery for known problems. */
310 311 312 313 314 315
static int _keyslot_repair(const char *device, struct luks_phdr *phdr, struct crypt_device *ctx)
{
	struct luks_phdr temp_phdr;
	const unsigned char *sector = (const unsigned char*)phdr;
	struct volume_key *vk;
	uint64_t PBKDF2_per_sec = 1;
316
	int i, bad, r, need_write = 0;
317

318 319 320 321
	if (phdr->keyBytes != 16 && phdr->keyBytes != 32) {
		log_err(ctx, _("Non standard key size, manual repair required.\n"));
		return -EINVAL;
	}
322 323 324 325 326 327
	/* cryptsetup 1.0 did not align to 4k, cannot repair this one */
	if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
		log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
		return -EINVAL;
	}

328 329
	vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);

330 331 332 333 334 335
	log_verbose(ctx, _("Repairing keyslots.\n"));

	log_dbg("Generating second header with the same parameters for check.");
	/* cipherName, cipherMode, hashSpec, uuid are already null terminated */
	/* payloadOffset - cannot check */
	r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
336 337 338 339
			       phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
			       phdr->payloadOffset, 0,
			       1, &PBKDF2_per_sec,
			       "/dev/null", ctx);
340 341 342 343
	if (r < 0) {
		log_err(ctx, _("Repair failed."));
		goto out;
	}
344 345

	for(i = 0; i < LUKS_NUMKEYS; ++i) {
346 347 348 349 350
		if (phdr->keyblock[i].active == LUKS_KEY_ENABLED)  {
			log_dbg("Skipping repair for active keyslot %i.", i);
			continue;
		}

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
		bad = 0;
		if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
			log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
				(unsigned)phdr->keyblock[i].keyMaterialOffset,
				(unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
			phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
			bad = 1;
		}

		if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
			log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
				(unsigned)phdr->keyblock[i].stripes,
				(unsigned)temp_phdr.keyblock[i].stripes);
			phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
			bad = 1;
		}

368 369 370 371 372 373 374 375 376 377 378
		/* Known case - MSDOS partition table signature */
		if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
			log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
			bad = 1;
		}

		if(bad) {
			log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
			phdr->keyblock[i].active = LUKS_KEY_DISABLED;
			memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
			phdr->keyblock[i].passwordIterations = 0;
379
		}
380 381 382

		if (bad)
			need_write = 1;
383 384
	}

385 386 387 388 389
	if (need_write) {
		log_verbose(ctx, _("Writing LUKS header to disk.\n"));
		r = LUKS_write_phdr(device, phdr, ctx);
	}
out:
390 391
	crypt_free_volume_key(vk);
	memset(&temp_phdr, 0, sizeof(temp_phdr));
392
	return r;
393 394
}

395 396 397
static int _check_and_convert_hdr(const char *device,
				  struct luks_phdr *hdr,
				  int require_luks_device,
398
				  int repair,
399 400 401 402 403 404 405
				  struct crypt_device *ctx)
{
	int r = 0;
	unsigned int i;
	char luksMagic[] = LUKS_MAGIC;

	if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
406 407
		log_dbg("LUKS header not detected.");
		if (require_luks_device)
408
			log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
409
		return -EINVAL;
410
	} else if((hdr->version = ntohs(hdr->version)) != 1) {	/* Convert every uint16/32_t item from network byte order */
411
		log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
412 413 414 415 416
		return -EINVAL;
	}

	hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
	if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
417
		log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
		return -EINVAL;
	}

	/* Header detected */
	hdr->payloadOffset      = ntohl(hdr->payloadOffset);
	hdr->keyBytes           = ntohl(hdr->keyBytes);
	hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);

	for(i = 0; i < LUKS_NUMKEYS; ++i) {
		hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
		hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
		hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
		hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
		if (LUKS_check_keyslot_size(hdr, i)) {
			log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
			r = -EINVAL;
434
		}
435 436 437 438 439 440
	}

	/* Avoid unterminated strings */
	hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
	hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
	hdr->uuid[UUID_STRING_L - 1] = '\0';
441

442 443
	if (repair) {
		if (r == -EINVAL)
444
			r = _keyslot_repair(device, hdr, ctx);
445 446
		else
			log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
447 448
	}

449 450 451
	return r;
}

452
static void _to_lower(char *str, unsigned max_len)
453
{
454
	for(; *str && max_len; str++, max_len--)
455 456 457 458 459 460 461 462
		if (isupper(*str))
			*str = tolower(*str);
}

static void LUKS_fix_header_compatible(struct luks_phdr *header)
{
	/* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
	 * so always convert hash to lower case in header */
463
	_to_lower(header->hashSpec, LUKS_HASHSPEC_L);
464 465
}

466 467 468 469 470 471
int LUKS_read_phdr_backup(const char *backup_file,
			  const char *device,
			  struct luks_phdr *hdr,
			  int require_luks_device,
			  struct crypt_device *ctx)
{
472
	ssize_t hdr_size = sizeof(struct luks_phdr);
473 474 475
	int devfd = 0, r = 0;

	log_dbg("Reading LUKS header of size %d from backup file %s",
476
		(int)hdr_size, backup_file);
477 478 479 480 481 482 483

	devfd = open(backup_file, O_RDONLY);
	if(-1 == devfd) {
		log_err(ctx, _("Cannot open file %s.\n"), device);
		return -EINVAL;
	}

484
	if (read(devfd, hdr, hdr_size) < hdr_size)
485
		r = -EIO;
486 487
	else {
		LUKS_fix_header_compatible(hdr);
488 489
		r = _check_and_convert_hdr(backup_file, hdr,
					   require_luks_device, 0, ctx);
490
	}
491 492 493 494 495 496 497 498

	close(devfd);
	return r;
}

int LUKS_read_phdr(const char *device,
		   struct luks_phdr *hdr,
		   int require_luks_device,
499
		   int repair,
500 501
		   struct crypt_device *ctx)
{
502
	ssize_t hdr_size = sizeof(struct luks_phdr);
503 504
	int devfd = 0, r = 0;

505 506 507
	if (repair && !require_luks_device)
		return -EINVAL;

508
	log_dbg("Reading LUKS header of size %d from device %s",
509
		hdr_size, device);
510 511 512 513 514 515 516

	devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
	if(-1 == devfd) {
		log_err(ctx, _("Cannot open device %s.\n"), device);
		return -EINVAL;
	}

517
	if (read_blockwise(devfd, hdr, hdr_size) < hdr_size)
518 519
		r = -EIO;
	else
520 521
		r = _check_and_convert_hdr(device, hdr, require_luks_device,
					   repair, ctx);
522

523 524 525
	if (!r)
		r = LUKS_check_device_size(ctx, device, hdr->keyBytes);

526 527 528 529
	close(devfd);
	return r;
}

530 531 532
int LUKS_write_phdr(const char *device,
		    struct luks_phdr *hdr,
		    struct crypt_device *ctx)
533
{
534
	ssize_t hdr_size = sizeof(struct luks_phdr);
535 536
	int devfd = 0;
	unsigned int i;
537 538
	struct luks_phdr convHdr;
	int r;
539

540 541 542
	log_dbg("Updating LUKS header of size %d on device %s",
		sizeof(struct luks_phdr), device);

543 544 545
	r = LUKS_check_device_size(ctx, device, hdr->keyBytes);
	if (r)
		return r;
546

547
	devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
548
	if(-1 == devfd) {
549
		log_err(ctx, _("Cannot open device %s.\n"), device);
550 551 552
		return -EINVAL;
	}

553
	memcpy(&convHdr, hdr, hdr_size);
554
	memset(&convHdr._padding, 0, sizeof(convHdr._padding));
555 556 557 558 559 560 561 562 563 564 565 566 567

	/* Convert every uint16/32_t item to network byte order */
	convHdr.version            = htons(hdr->version);
	convHdr.payloadOffset      = htonl(hdr->payloadOffset);
	convHdr.keyBytes           = htonl(hdr->keyBytes);
	convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
	for(i = 0; i < LUKS_NUMKEYS; ++i) {
		convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
		convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
		convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
		convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
	}

568
	r = write_blockwise(devfd, &convHdr, hdr_size) < hdr_size ? -EIO : 0;
569 570
	if (r)
		log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
571
	close(devfd);
572

573 574
	/* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
	if (!r) {
575
		r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
576 577 578 579
		if (r)
			log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
	}

580
	return r;
581
}
582

583 584 585 586 587 588
static int LUKS_PBKDF2_performance_check(const char *hashSpec,
					 uint64_t *PBKDF2_per_sec,
					 struct crypt_device *ctx)
{
	if (!*PBKDF2_per_sec) {
		if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
589
			log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
590 591 592 593 594 595 596 597
			return -EINVAL;
		}
		log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
	}

	return 0;
}

598
int LUKS_generate_phdr(struct luks_phdr *header,
599
		       const struct volume_key *vk,
600 601 602
		       const char *cipherName, const char *cipherMode, const char *hashSpec,
		       const char *uuid, unsigned int stripes,
		       unsigned int alignPayload,
603
		       unsigned int alignOffset,
604 605
		       uint32_t iteration_time_ms,
		       uint64_t *PBKDF2_per_sec,
606
		       const char *metadata_device,
607
		       struct crypt_device *ctx)
608 609
{
	unsigned int i=0;
610
	unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE);
611 612 613
	int r;
	uuid_t partitionUuid;
	int currentSector;
614
	char luksMagic[] = LUKS_MAGIC;
615

616 617
	/* For separate metadata device allow zero alignment */
	if (alignPayload == 0 && !metadata_device)
618
		alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
619

620 621 622 623 624
	if (PBKDF2_HMAC_ready(hashSpec) < 0) {
		log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
		return -EINVAL;
	}

625 626 627 628 629 630 631
	if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
		log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
		return -EINVAL;
	}
	if (!uuid)
		uuid_generate(partitionUuid);

632 633 634 635 636 637 638
	memset(header,0,sizeof(struct luks_phdr));

	/* Set Magic */
	memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
	header->version=1;
	strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
	strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
639
	strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
640

641
	header->keyBytes=vk->keylength;
642

643 644
	LUKS_fix_header_compatible(header);

645 646 647 648
	log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
		header->version, header->hashSpec ,header->cipherName, header->cipherMode,
		header->keyBytes);

649
	r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
650
	if(r < 0) {
651
		log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
652 653
		return r;
	}
654

655 656 657
	if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
		return r;

658
	/* Compute master key digest */
659 660 661 662
	iteration_time_ms /= 8;
	header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
					      LUKS_MKD_ITERATIONS_MIN);

663
	r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength,
664 665 666 667
			header->mkDigestSalt,LUKS_SALTSIZE,
			header->mkDigestIterations,
			header->mkDigest,LUKS_DIGESTSIZE);
	if(r < 0) {
668 669
		log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
			header->hashSpec);
670 671
		return r;
	}
672

673
	currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
674 675 676 677
	for(i = 0; i < LUKS_NUMKEYS; ++i) {
		header->keyblock[i].active = LUKS_KEY_DISABLED;
		header->keyblock[i].keyMaterialOffset = currentSector;
		header->keyblock[i].stripes = stripes;
678 679
		currentSector = round_up_modulo(currentSector + blocksPerStripeSet,
						LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
680 681
	}

682 683 684 685 686 687 688 689
	if (metadata_device) {
		/* for separate metadata device use alignPayload directly */
		header->payloadOffset = alignPayload;
	} else {
		/* alignOffset - offset from natural device alignment provided by topology info */
		currentSector = round_up_modulo(currentSector, alignPayload);
		header->payloadOffset = currentSector + alignOffset;
	}
690 691 692

        uuid_unparse(partitionUuid, header->uuid);

693 694
	log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
		header->payloadOffset, header->uuid, header->mkDigestIterations);
695

696 697 698
	return 0;
}

699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
int LUKS_hdr_uuid_set(
	const char *device,
	struct luks_phdr *hdr,
	const char *uuid,
	struct crypt_device *ctx)
{
	uuid_t partitionUuid;

	if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
		log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
		return -EINVAL;
	}
	if (!uuid)
		uuid_generate(partitionUuid);

	uuid_unparse(partitionUuid, hdr->uuid);

	return LUKS_write_phdr(device, hdr, ctx);
}

719 720
int LUKS_set_key(const char *device, unsigned int keyIndex,
		 const char *password, size_t passwordLen,
721
		 struct luks_phdr *hdr, struct volume_key *vk,
722 723 724
		 uint32_t iteration_time_ms,
		 uint64_t *PBKDF2_per_sec,
		 struct crypt_device *ctx)
725
{
726
	struct volume_key *derived_key;
727
	char *AfKey = NULL;
728
	unsigned int AFEKSize;
729
	uint64_t PBKDF2_temp;
730
	int r;
731

732
	if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
733
		log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
734 735
		return -EINVAL;
	}
736

737
	if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
738 739
	        log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
			keyIndex);
740 741
	         return -EINVAL;
	}
742

743 744
	log_dbg("Calculating data for key slot %d", keyIndex);

745 746 747 748 749 750 751 752 753 754 755 756 757
	if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
		return r;

	/*
	 * Avoid floating point operation
	 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
	 */
	PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
	PBKDF2_temp /= 1024;
	if (PBKDF2_temp > UINT32_MAX)
		PBKDF2_temp = UINT32_MAX;
	hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
							      LUKS_SLOT_ITERATIONS_MIN);
758 759 760

	log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);

761 762 763 764
	derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
	if (!derived_key)
		return -ENOMEM;

765
	r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
766
		       LUKS_SALTSIZE, CRYPT_RND_SALT);
767 768
	if (r < 0)
		return r;
769

770 771 772
	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
			hdr->keyblock[keyIndex].passwordIterations,
773
			derived_key->key, hdr->keyBytes);
774 775
	if (r < 0)
		goto out;
776

777
	/*
Milan Broz's avatar
Milan Broz committed
778
	 * AF splitting, the masterkey stored in vk->key is split to AfKey
779
	 */
780
	assert(vk->keylength == hdr->keyBytes);
781
	AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
782 783 784 785 786
	AfKey = crypt_safe_alloc(AFEKSize);
	if (!AfKey) {
		r = -ENOMEM;
		goto out;
	}
787

788 789
	log_dbg("Using hash %s for AF in key slot %d, %d stripes",
		hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
790
	r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
791 792
	if (r < 0)
		goto out;
793

794 795
	log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
		hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
796 797 798 799
	/* Encryption via dm */
	r = LUKS_encrypt_to_storage(AfKey,
				    AFEKSize,
				    hdr,
800
				    derived_key,
801
				    device,
802 803
				    hdr->keyblock[keyIndex].keyMaterialOffset,
				    ctx);
804
	if (r < 0) {
Milan Broz's avatar
Milan Broz committed
805
		log_err(ctx, _("Failed to write to key storage.\n"));
806 807 808 809
		goto out;
	}

	/* Mark the key as active in phdr */
810
	r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
811 812
	if (r < 0)
		goto out;
813

814
	r = LUKS_write_phdr(device, hdr, ctx);
815 816
	if (r < 0)
		goto out;
817 818 819

	r = 0;
out:
820
	crypt_safe_free(AfKey);
821
	crypt_free_volume_key(derived_key);
822 823 824
	return r;
}

825 826 827
/* Check whether a volume key is invalid. */
int LUKS_verify_volume_key(const struct luks_phdr *hdr,
			   const struct volume_key *vk)
828 829 830
{
	char checkHashBuf[LUKS_DIGESTSIZE];

831
	if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength,
832 833 834 835 836 837 838 839 840 841 842
			hdr->mkDigestSalt, LUKS_SALTSIZE,
			hdr->mkDigestIterations, checkHashBuf,
			LUKS_DIGESTSIZE) < 0)
		return -EINVAL;

	if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
		return -EPERM;

	return 0;
}

843
/* Try to open a particular key slot */
844
static int LUKS_open_key(const char *device,
845 846 847 848
		  unsigned int keyIndex,
		  const char *password,
		  size_t passwordLen,
		  struct luks_phdr *hdr,
849
		  struct volume_key *vk,
850
		  struct crypt_device *ctx)
851
{
852
	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
853
	struct volume_key *derived_key;
854 855 856
	char *AfKey;
	size_t AFEKSize;
	int r;
857

Milan Broz's avatar
Milan Broz committed
858 859
	log_dbg("Trying to open key slot %d [%s].", keyIndex,
		dbg_slot_state(ki));
860

861
	if (ki < CRYPT_SLOT_ACTIVE)
862 863
		return -ENOENT;

864 865 866
	derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
	if (!derived_key)
		return -ENOMEM;
867

868
	assert(vk->keylength == hdr->keyBytes);
869
	AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength;
870 871 872
	AfKey = crypt_safe_alloc(AFEKSize);
	if (!AfKey)
		return -ENOMEM;
873 874 875 876

	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
			hdr->keyblock[keyIndex].passwordIterations,
877
			derived_key->key, hdr->keyBytes);
878 879
	if (r < 0)
		goto out;
880

881
	log_dbg("Reading key slot %d area.", keyIndex);
882 883 884
	r = LUKS_decrypt_from_storage(AfKey,
				      AFEKSize,
				      hdr,
885
				      derived_key,
886
				      device,
887 888
				      hdr->keyblock[keyIndex].keyMaterialOffset,
				      ctx);
889
	if (r < 0) {
890 891 892
		log_err(ctx, _("Failed to read from key storage.\n"));
		goto out;
	}
893

894
	r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
895 896
	if (r < 0)
		goto out;
897

898
	r = LUKS_verify_volume_key(hdr, vk);
899
	if (!r)
900
		log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
901
out:
902
	crypt_safe_free(AfKey);
903
	crypt_free_volume_key(derived_key);
904 905 906
	return r;
}

907 908 909 910 911
int LUKS_open_key_with_hdr(const char *device,
			   int keyIndex,
			   const char *password,
			   size_t passwordLen,
			   struct luks_phdr *hdr,
912
			   struct volume_key **vk,
913
			   struct crypt_device *ctx)
914
{
915
	unsigned int i;
916 917
	int r;

918
	*vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
919

920 921 922 923
	if (keyIndex >= 0) {
		r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx);
		return (r < 0) ? r : keyIndex;
	}
924

925
	for(i = 0; i < LUKS_NUMKEYS; i++) {
926
		r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx);
927 928 929
		if(r == 0)
			return i;

930 931
		/* Do not retry for errors that are no -EPERM or -ENOENT,
		   former meaning password wrong, latter key slot inactive */
932
		if ((r != -EPERM) && (r != -ENOENT))
933
			return r;
934 935
	}
	/* Warning, early returns above */
936
	log_err(ctx, _("No key available with this passphrase.\n"));
937 938 939
	return -EPERM;
}

940 941 942 943
int LUKS_del_key(const char *device,
		 unsigned int keyIndex,
		 struct luks_phdr *hdr,
		 struct crypt_device *ctx)
944 945 946
{
	unsigned int startOffset, endOffset, stripesLen;
	int r;
947

948
	r = LUKS_read_phdr(device, hdr, 1, 0, ctx);
949 950 951
	if (r)
		return r;

952
	r = LUKS_keyslot_set(hdr, keyIndex, 0);
953
	if (r) {
954 955
		log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
			keyIndex, LUKS_NUMKEYS - 1);
956
		return r;
957 958
	}

959
	/* secure deletion of key material */
960 961
	startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
	stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
962 963
	endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);

964 965 966
	r = crypt_wipe(device, startOffset * SECTOR_SIZE,
		       (endOffset - startOffset) * SECTOR_SIZE,
		       CRYPT_WIPE_DISK, 0);
967 968 969 970 971
	if (r) {
		log_err(ctx, _("Cannot wipe device %s.\n"), device);
		return r;
	}

972 973 974 975
	/* Wipe keyslot info */
	memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
	hdr->keyblock[keyIndex].passwordIterations = 0;

976
	r = LUKS_write_phdr(device, hdr, ctx);
977

978 979 980
	return r;
}

981
crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
982
{
983
	int i;
984

985
	if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
986
		return CRYPT_SLOT_INVALID;
987

988
	if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
989
		return CRYPT_SLOT_INACTIVE;
990 991

	if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
992
		return CRYPT_SLOT_INVALID;
993 994 995

	for(i = 0; i < LUKS_NUMKEYS; i++)
		if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
996
			return CRYPT_SLOT_ACTIVE;
997

998
	return CRYPT_SLOT_ACTIVE_LAST;
999 1000
}

1001
int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1002
{
1003 1004 1005 1006 1007 1008 1009
	int i;

	for (i = 0; i < LUKS_NUMKEYS; i++)
		if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
			break;

	if (i == LUKS_NUMKEYS)
1010 1011
		return -EINVAL;

1012
	return i;
1013 1014
}

1015
int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1016
{
1017
	int i, num = 0;
1018

1019 1020 1021
	for (i = 0; i < LUKS_NUMKEYS; i++)
		if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
			num++;
1022

1023 1024 1025 1026 1027 1028 1029
	return num;
}

int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
{
	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);

1030
	if (ki == CRYPT_SLOT_INVALID)
1031
		return -EINVAL;
1032

1033 1034 1035
	hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
	log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
	return 0;
1036
}
1037 1038 1039 1040 1041 1042 1043 1044

int LUKS1_activate(struct crypt_device *cd,
		   const char *name,
		   struct volume_key *vk,
		   uint32_t flags)
{
	int r;
	char *dm_cipher = NULL;
1045
	enum devcheck device_check;
1046
	struct crypt_dm_active_device dmd = {
1047
		.target = DM_CRYPT,
1048
		.uuid   = crypt_get_uuid(cd),
1049
		.flags  = flags,
1050
		.size   = 0,
1051
		.data_device = crypt_get_device_name(cd),
1052 1053 1054 1055 1056 1057
		.u.crypt = {
			.cipher = NULL,
			.vk     = vk,
			.offset = crypt_get_data_offset(cd),
			.iv_offset = 0,
		}
1058 1059
	};

1060 1061 1062 1063 1064
	if (dmd.flags & CRYPT_ACTIVATE_SHARED)
		device_check = DEV_SHARED;
	else
		device_check = DEV_EXCL;

1065
	r = device_check_and_adjust(cd, dmd.data_device, device_check,
1066 1067
				    &dmd.size, &dmd.u.crypt.offset,
				    &dmd.flags);
1068 1069 1070 1071 1072 1073 1074
	if (r)
		return r;

	r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
	if (r < 0)
		return -ENOMEM;

1075
	dmd.u.crypt.cipher = dm_cipher;
1076
	r = dm_create_device(name, CRYPT_LUKS1, &dmd, 0);
1077 1078 1079 1080

	free(dm_cipher);
	return r;
}