keymanage.c 35.5 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 6
 * Copyright (C) 2009-2018, Red Hat, Inc. All rights reserved.
 * Copyright (C) 2013-2018, Milan Broz
7
 *
8 9
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
10 11
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
12 13 14 15 16 17 18 19
 *
 * 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
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 22
 */

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

#include "luks.h"
#include "af.h"
38
#include "internal.h"
39

40
/* Get size of struct luks_phdr with all keyslots material space */
41
static size_t LUKS_calculate_device_sectors(size_t keyLen)
42
{
43
	size_t keyslot_sectors, sector;
44 45
	int i;

46
	keyslot_sectors = AF_split_sectors(keyLen, LUKS_STRIPES);
47
	sector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
48 49

	for (i = 0; i < LUKS_NUMKEYS; i++) {
50
		sector = size_round_up(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
51 52 53 54 55 56
		sector += keyslot_sectors;
	}

	return sector;
}

57
int LUKS_keyslot_area(const struct luks_phdr *hdr,
58 59 60 61 62 63 64
	int keyslot,
	uint64_t *offset,
	uint64_t *length)
{
	if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
		return -EINVAL;

65
	*offset = (uint64_t)hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
66 67 68 69 70
	*length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;

	return 0;
}

71 72
/* insertsort: because the array has 8 elements and it's mostly sorted. that's why */
static void LUKS_sort_keyslots(const struct luks_phdr *hdr, int *array)
73 74 75
{
	int i, j, x;

76
	for (i = 1; i < LUKS_NUMKEYS; i++) {
77 78 79 80 81 82 83 84 85 86
		j = i;
		while (j > 0 && hdr->keyblock[array[j-1]].keyMaterialOffset > hdr->keyblock[array[j]].keyMaterialOffset) {
			x = array[j];
			array[j] = array[j-1];
			array[j-1] = x;
			j--;
		}
	}
}

87
size_t LUKS_device_sectors(const struct luks_phdr *hdr)
88 89 90 91 92 93 94 95
{
	int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };

	LUKS_sort_keyslots(hdr, sorted_areas);

	return hdr->keyblock[sorted_areas[LUKS_NUMKEYS-1]].keyMaterialOffset + AF_split_sectors(hdr->keyBytes, LUKS_STRIPES);
}

96 97 98 99 100 101 102 103 104
size_t LUKS_keyslots_offset(const struct luks_phdr *hdr)
{
	int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };

	LUKS_sort_keyslots(hdr, sorted_areas);

	return hdr->keyblock[sorted_areas[0]].keyMaterialOffset;
}

105
static int LUKS_check_device_size(struct crypt_device *ctx, const struct luks_phdr *hdr, int falloc)
106
{
Milan Broz's avatar
Milan Broz committed
107
	struct device *device = crypt_metadata_device(ctx);
108
	uint64_t dev_sectors, hdr_sectors;
109

110
	if (!hdr->keyBytes)
111 112
		return -EINVAL;

113
	if (device_size(device, &dev_sectors)) {
114
		log_dbg(ctx, "Cannot get device size for device %s.", device_path(device));
115 116 117
		return -EIO;
	}

118
	dev_sectors >>= SECTOR_SHIFT;
119
	hdr_sectors = LUKS_device_sectors(hdr);
120
	log_dbg(ctx, "Key length %u, device size %" PRIu64 " sectors, header size %"
121
		PRIu64 " sectors.", hdr->keyBytes, dev_sectors, hdr_sectors);
122 123

	if (hdr_sectors > dev_sectors) {
124 125 126 127
		/* If it is header file, increase its size */
		if (falloc && !device_fallocate(device, hdr_sectors << SECTOR_SHIFT))
			return 0;

128
		log_err(ctx, _("Device %s is too small. (LUKS1 requires at least %" PRIu64 " bytes.)"),
129
			device_path(device), hdr_sectors * SECTOR_SIZE);
130 131 132 133
		return -EINVAL;
	}

	return 0;
134 135
}

136
static int LUKS_check_keyslots(struct crypt_device *ctx, const struct luks_phdr *phdr)
137
{
138 139
	int i, prev, next, sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
	uint32_t secs_per_stripes = AF_split_sectors(phdr->keyBytes, LUKS_STRIPES);
140

141
	LUKS_sort_keyslots(phdr, sorted_areas);
142

143 144 145 146
	/* Check keyslot to prevent access outside of header and keyslot area */
	for (i = 0; i < LUKS_NUMKEYS; i++) {
		/* enforce stripes == 4000 */
		if (phdr->keyblock[i].stripes != LUKS_STRIPES) {
147
			log_dbg(ctx, "Invalid stripes count %u in keyslot %u.",
148
				phdr->keyblock[i].stripes, i);
149
			log_err(ctx, _("LUKS keyslot %u is invalid."), i);
150 151
			return -1;
		}
152

153 154
		/* First sectors is the header itself */
		if (phdr->keyblock[i].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
155
			log_dbg(ctx, "Invalid offset %u in keyslot %u.",
156
				phdr->keyblock[i].keyMaterialOffset, i);
157
			log_err(ctx, _("LUKS keyslot %u is invalid."), i);
158 159
			return -1;
		}
160

161 162 163 164 165
		/* Ignore following check for detached header where offset can be zero. */
		if (phdr->payloadOffset == 0)
			continue;

		if (phdr->payloadOffset <= phdr->keyblock[i].keyMaterialOffset) {
166
			log_dbg(ctx, "Invalid offset %u in keyslot %u (beyond data area offset %u).",
167 168
				phdr->keyblock[i].keyMaterialOffset, i,
				phdr->payloadOffset);
169
			log_err(ctx, _("LUKS keyslot %u is invalid."), i);
170 171 172 173
			return -1;
		}

		if (phdr->payloadOffset < (phdr->keyblock[i].keyMaterialOffset + secs_per_stripes)) {
174
			log_dbg(ctx, "Invalid keyslot size %u (offset %u, stripes %u) in "
175 176 177 178 179
				"keyslot %u (beyond data area offset %u).",
				secs_per_stripes,
				phdr->keyblock[i].keyMaterialOffset,
				phdr->keyblock[i].stripes,
				i, phdr->payloadOffset);
180
			log_err(ctx, _("LUKS keyslot %u is invalid."), i);
181 182 183
			return -1;
		}
	}
184

185 186 187 188 189 190
	/* check no keyslot overlaps with each other */
	for (i = 1; i < LUKS_NUMKEYS; i++) {
		prev = sorted_areas[i-1];
		next = sorted_areas[i];
		if (phdr->keyblock[next].keyMaterialOffset <
		    (phdr->keyblock[prev].keyMaterialOffset + secs_per_stripes)) {
191
			log_dbg(ctx, "Not enough space in LUKS keyslot %d.", prev);
192
			log_err(ctx, _("LUKS keyslot %u is invalid."), prev);
193 194
			return -1;
		}
195
	}
196
	/* do not check last keyslot on purpose, it must be tested in device size check */
197 198 199 200

	return 0;
}

201
static const char *dbg_slot_state(crypt_keyslot_info ki)
Milan Broz's avatar
Milan Broz committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215
{
	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";
	}
}

216
int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
217
{
Milan Broz's avatar
Milan Broz committed
218
	struct device *device = crypt_metadata_device(ctx);
219
	struct luks_phdr hdr;
220
	int r = 0, devfd = -1;
221 222
	size_t hdr_size;
	size_t buffer_size;
223
	char *buffer = NULL;
224

225
	r = LUKS_read_phdr(&hdr, 1, 0, ctx);
226 227 228
	if (r)
		return r;

229
	hdr_size = LUKS_device_sectors(&hdr) << SECTOR_SHIFT;
230 231
	buffer_size = size_round_up(hdr_size, crypt_getpagesize());

232
	buffer = crypt_safe_alloc(buffer_size);
233
	if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
234 235 236 237
		r = -ENOMEM;
		goto out;
	}

238
	log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
239
		sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);
240

241
	log_dbg(ctx, "Output backup file size: %zu bytes.", buffer_size);
242

243
	devfd = device_open(ctx, device, O_RDONLY);
244
	if (devfd < 0) {
245
		log_err(ctx, _("Device %s is not a valid LUKS device."), device_path(device));
246 247 248 249
		r = -EINVAL;
		goto out;
	}

250
	if (read_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
251
			   buffer, hdr_size) < (ssize_t)hdr_size) {
252 253 254 255 256 257
		r = -EIO;
		goto out;
	}
	close(devfd);

	/* Wipe unused area, so backup cannot contain old signatures */
258 259
	if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
		memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));
260

261 262 263
	devfd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
	if (devfd == -1) {
		if (errno == EEXIST)
264
			log_err(ctx, _("Requested header backup file %s already exists."), backup_file);
265
		else
266
			log_err(ctx, _("Cannot create header backup file %s."), backup_file);
267 268 269
		r = -EINVAL;
		goto out;
	}
270
	if (write_buffer(devfd, buffer, buffer_size) < (ssize_t)buffer_size) {
271
		log_err(ctx, _("Cannot write header backup file %s."), backup_file);
272 273 274 275 276 277
		r = -EIO;
		goto out;
	}

	r = 0;
out:
278
	if (devfd >= 0)
279
		close(devfd);
280
	crypt_memzero(&hdr, sizeof(hdr));
281
	crypt_safe_free(buffer);
282 283 284 285 286 287 288 289
	return r;
}

int LUKS_hdr_restore(
	const char *backup_file,
	struct luks_phdr *hdr,
	struct crypt_device *ctx)
{
Milan Broz's avatar
Milan Broz committed
290
	struct device *device = crypt_metadata_device(ctx);
291
	int r = 0, devfd = -1, diff_uuid = 0;
292
	ssize_t buffer_size = 0;
293 294 295
	char *buffer = NULL, msg[200];
	struct luks_phdr hdr_file;

Milan Broz's avatar
Milan Broz committed
296
	r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
297 298 299
	if (r == -ENOENT)
		return r;

Milan Broz's avatar
Milan Broz committed
300
	if (!r)
301
		buffer_size = LUKS_device_sectors(&hdr_file) << SECTOR_SHIFT;
302 303

	if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
304
		log_err(ctx, _("Backup file doesn't contain valid LUKS header."));
305 306 307 308
		r = -EINVAL;
		goto out;
	}

309
	buffer = crypt_safe_alloc(buffer_size);
310 311 312 313 314 315
	if (!buffer) {
		r = -ENOMEM;
		goto out;
	}

	devfd = open(backup_file, O_RDONLY);
316
	if (devfd == -1) {
317
		log_err(ctx, _("Cannot open header backup file %s."), backup_file);
318 319 320 321
		r = -EINVAL;
		goto out;
	}

322
	if (read_buffer(devfd, buffer, buffer_size) < buffer_size) {
323
		log_err(ctx, _("Cannot read header backup file %s."), backup_file);
324 325 326 327
		r = -EIO;
		goto out;
	}
	close(devfd);
328
	devfd = -1;
329

Milan Broz's avatar
Milan Broz committed
330
	r = LUKS_read_phdr(hdr, 0, 0, ctx);
331
	if (r == 0) {
332
		log_dbg(ctx, "Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
333 334
		if(hdr->payloadOffset != hdr_file.payloadOffset ||
		   hdr->keyBytes != hdr_file.keyBytes) {
335
			log_err(ctx, _("Data offset or key size differs on device and backup, restore failed."));
336 337 338 339 340 341 342
			r = -EINVAL;
			goto out;
		}
		if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
			diff_uuid = 1;
	}

Milan Broz's avatar
Milan Broz committed
343
	if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
344 345 346 347 348 349 350 351 352 353 354 355
		 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;
	}

356
	log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes) to device %s.",
Milan Broz's avatar
Milan Broz committed
357
		sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
358

359
	devfd = device_open(ctx, device, O_RDWR);
360
	if (devfd < 0) {
361
		if (errno == EACCES)
362
			log_err(ctx, _("Cannot write to device %s, permission denied."),
363 364
				device_path(device));
		else
365
			log_err(ctx, _("Cannot open device %s."), device_path(device));
366 367
		r = -EINVAL;
		goto out;
368 369
	}

370
	if (write_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
371
			    buffer, buffer_size) < buffer_size) {
372
		r = -EIO;
373 374 375
		goto out;
	}
	close(devfd);
376
	devfd = -1;
377 378

	/* Be sure to reload new data */
Milan Broz's avatar
Milan Broz committed
379
	r = LUKS_read_phdr(hdr, 1, 0, ctx);
380
out:
381
	if (devfd >= 0) {
382
		device_sync(ctx, device, devfd);
383
		close(devfd);
384
	}
385
	crypt_safe_free(buffer);
386 387 388
	return r;
}

389
/* This routine should do some just basic recovery for known problems. */
Milan Broz's avatar
Milan Broz committed
390
static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
391 392 393 394
{
	struct luks_phdr temp_phdr;
	const unsigned char *sector = (const unsigned char*)phdr;
	struct volume_key *vk;
395
	int i, bad, r, need_write = 0;
396

397
	if (phdr->keyBytes != 16 && phdr->keyBytes != 32 && phdr->keyBytes != 64) {
398
		log_err(ctx, _("Non standard key size, manual repair required."));
399 400
		return -EINVAL;
	}
401
	/* cryptsetup 1.0 did not align to 4k, cannot repair this one */
402
	if (LUKS_keyslots_offset(phdr) < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
403
		log_err(ctx, _("Non standard keyslots alignment, manual repair required."));
404 405 406
		return -EINVAL;
	}

407 408 409 410
	r = LUKS_check_cipher(ctx, phdr->keyBytes, phdr->cipherName, phdr->cipherMode);
	if (r < 0)
		return -EINVAL;

411 412
	vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);

413
	log_verbose(ctx, _("Repairing keyslots."));
414

415
	log_dbg(ctx, "Generating second header with the same parameters for check.");
416 417 418
	/* cipherName, cipherMode, hashSpec, uuid are already null terminated */
	/* payloadOffset - cannot check */
	r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
419
			       phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
420
			       phdr->payloadOffset * SECTOR_SIZE, 0, true, ctx);
421
	if (r < 0)
422
		goto out;
423 424

	for(i = 0; i < LUKS_NUMKEYS; ++i) {
425
		if (phdr->keyblock[i].active == LUKS_KEY_ENABLED)  {
426
			log_dbg(ctx, "Skipping repair for active keyslot %i.", i);
427 428 429
			continue;
		}

430 431
		bad = 0;
		if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
432
			log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u)."), i,
433 434 435 436 437 438 439
				(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) {
440
			log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u)."), i,
441 442 443 444 445 446
				(unsigned)phdr->keyblock[i].stripes,
				(unsigned)temp_phdr.keyblock[i].stripes);
			phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
			bad = 1;
		}

447 448
		/* Known case - MSDOS partition table signature */
		if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
449
			log_err(ctx, _("Keyslot %i: bogus partition signature."), i);
450 451 452 453
			bad = 1;
		}

		if(bad) {
454
			log_err(ctx, _("Keyslot %i: salt wiped."), i);
455 456 457
			phdr->keyblock[i].active = LUKS_KEY_DISABLED;
			memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
			phdr->keyblock[i].passwordIterations = 0;
458
		}
459 460 461

		if (bad)
			need_write = 1;
462 463
	}

464
	/*
Andrea Gelmini's avatar
Andrea Gelmini committed
465
	 * check repair result before writing because repair can't fix out of order
466 467 468 469 470
	 * keyslot offsets and would corrupt header again
	 */
	if (LUKS_check_keyslots(ctx, phdr))
		r = -EINVAL;
	else if (need_write) {
471
		log_verbose(ctx, _("Writing LUKS header to disk."));
Milan Broz's avatar
Milan Broz committed
472
		r = LUKS_write_phdr(phdr, ctx);
473 474
	}
out:
475
	if (r)
476
		log_err(ctx, _("Repair failed."));
477
	crypt_free_volume_key(vk);
478
	crypt_memzero(&temp_phdr, sizeof(temp_phdr));
479
	return r;
480 481
}

482 483 484
static int _check_and_convert_hdr(const char *device,
				  struct luks_phdr *hdr,
				  int require_luks_device,
485
				  int repair,
486 487 488 489 490 491 492
				  struct crypt_device *ctx)
{
	int r = 0;
	unsigned int i;
	char luksMagic[] = LUKS_MAGIC;

	if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
493
		log_dbg(ctx, "LUKS header not detected.");
494
		if (require_luks_device)
495
			log_err(ctx, _("Device %s is not a valid LUKS device."), device);
496
		return -EINVAL;
497
	} else if((hdr->version = ntohs(hdr->version)) != 1) {	/* Convert every uint16/32_t item from network byte order */
498
		log_err(ctx, _("Unsupported LUKS version %d."), hdr->version);
499 500 501 502
		return -EINVAL;
	}

	hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
503
	if (crypt_hmac_size(hdr->hashSpec) < LUKS_DIGESTSIZE) {
504
		log_err(ctx, _("Requested LUKS hash %s is not supported."), hdr->hashSpec);
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
		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);
	}

520 521 522
	if (LUKS_check_keyslots(ctx, hdr))
		r = -EINVAL;

523 524 525 526
	/* Avoid unterminated strings */
	hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
	hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
	hdr->uuid[UUID_STRING_L - 1] = '\0';
527

528 529
	if (repair) {
		if (r == -EINVAL)
Milan Broz's avatar
Milan Broz committed
530
			r = _keyslot_repair(hdr, ctx);
531
		else
532
			log_verbose(ctx, _("No known problems detected for LUKS header."));
533 534
	}

535 536 537
	return r;
}

538
static void _to_lower(char *str, unsigned max_len)
539
{
540
	for(; *str && max_len; str++, max_len--)
541 542 543 544 545 546
		if (isupper(*str))
			*str = tolower(*str);
}

static void LUKS_fix_header_compatible(struct luks_phdr *header)
{
Andrea Gelmini's avatar
Andrea Gelmini committed
547
	/* Old cryptsetup expects "sha1", gcrypt allows case insensitive names,
548
	 * so always convert hash to lower case in header */
549
	_to_lower(header->hashSpec, LUKS_HASHSPEC_L);
550 551 552 553 554 555 556

	/* ECB mode does not use IV but dmcrypt silently allows it.
	 * Drop any IV here if ECB is used (that is not secure anyway).*/
	if (!strncmp(header->cipherMode, "ecb-", 4)) {
		memset(header->cipherMode, 0, LUKS_CIPHERMODE_L);
		strcpy(header->cipherMode, "ecb");
	}
557 558
}

559 560 561 562 563
int LUKS_read_phdr_backup(const char *backup_file,
			  struct luks_phdr *hdr,
			  int require_luks_device,
			  struct crypt_device *ctx)
{
564
	ssize_t hdr_size = sizeof(struct luks_phdr);
565 566
	int devfd = 0, r = 0;

567
	log_dbg(ctx, "Reading LUKS header of size %d from backup file %s",
568
		(int)hdr_size, backup_file);
569 570

	devfd = open(backup_file, O_RDONLY);
571
	if (devfd == -1) {
572
		log_err(ctx, _("Cannot open header backup file %s."), backup_file);
573
		return -ENOENT;
574 575
	}

576
	if (read_buffer(devfd, hdr, hdr_size) < hdr_size)
577
		r = -EIO;
578 579
	else {
		LUKS_fix_header_compatible(hdr);
580 581
		r = _check_and_convert_hdr(backup_file, hdr,
					   require_luks_device, 0, ctx);
582
	}
583 584 585 586 587

	close(devfd);
	return r;
}

Milan Broz's avatar
Milan Broz committed
588
int LUKS_read_phdr(struct luks_phdr *hdr,
589
		   int require_luks_device,
590
		   int repair,
591 592
		   struct crypt_device *ctx)
{
Milan Broz's avatar
Milan Broz committed
593
	struct device *device = crypt_metadata_device(ctx);
594
	ssize_t hdr_size = sizeof(struct luks_phdr);
595 596
	int devfd = 0, r = 0;

597 598 599
	/* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
	assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);

600 601 602
	/* Stripes count cannot be changed without additional code fixes yet */
	assert(LUKS_STRIPES == 4000);

603 604 605
	if (repair && !require_luks_device)
		return -EINVAL;

606
	log_dbg(ctx, "Reading LUKS header of size %zu from device %s",
Milan Broz's avatar
Milan Broz committed
607
		hdr_size, device_path(device));
608

609
	devfd = device_open(ctx, device, O_RDONLY);
610
	if (devfd < 0) {
611
		log_err(ctx, _("Cannot open device %s."), device_path(device));
612 613 614
		return -EINVAL;
	}

615
	if (read_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
616
			   hdr, hdr_size) < hdr_size)
617 618
		r = -EIO;
	else
Milan Broz's avatar
Milan Broz committed
619
		r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
620
					   repair, ctx);
621

622
	if (!r)
623
		r = LUKS_check_device_size(ctx, hdr, 0);
624

625 626 627 628 629 630
	/*
	 * Cryptsetup 1.0.0 did not align keyslots to 4k (very rare version).
	 * Disable direct-io to avoid possible IO errors if underlying device
	 * has bigger sector size.
	 */
	if (!r && hdr->keyblock[0].keyMaterialOffset * SECTOR_SIZE < LUKS_ALIGN_KEYSLOTS) {
631
		log_dbg(ctx, "Old unaligned LUKS keyslot detected, disabling direct-io.");
632 633 634
		device_disable_direct_io(device);
	}

635 636 637 638
	close(devfd);
	return r;
}

Milan Broz's avatar
Milan Broz committed
639
int LUKS_write_phdr(struct luks_phdr *hdr,
640
		    struct crypt_device *ctx)
641
{
Milan Broz's avatar
Milan Broz committed
642
	struct device *device = crypt_metadata_device(ctx);
643
	ssize_t hdr_size = sizeof(struct luks_phdr);
644 645
	int devfd = 0;
	unsigned int i;
646 647
	struct luks_phdr convHdr;
	int r;
648

649
	log_dbg(ctx, "Updating LUKS header of size %zu on device %s",
Milan Broz's avatar
Milan Broz committed
650
		sizeof(struct luks_phdr), device_path(device));
651

652
	r = LUKS_check_device_size(ctx, hdr, 1);
653 654
	if (r)
		return r;
655

656
	devfd = device_open(ctx, device, O_RDWR);
657
	if (devfd < 0) {
658
		if (errno == EACCES)
659
			log_err(ctx, _("Cannot write to device %s, permission denied."),
660 661
				device_path(device));
		else
662
			log_err(ctx, _("Cannot open device %s."), device_path(device));
663 664 665
		return -EINVAL;
	}

666
	memcpy(&convHdr, hdr, hdr_size);
667
	memset(&convHdr._padding, 0, sizeof(convHdr._padding));
668 669 670 671 672 673 674 675 676 677 678 679 680

	/* 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);
	}

681
	r = write_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
682
			    &convHdr, hdr_size) < hdr_size ? -EIO : 0;
683
	if (r)
684
		log_err(ctx, _("Error during update of LUKS header on device %s."), device_path(device));
685

686
	device_sync(ctx, device, devfd);
687
	close(devfd);
688

689 690
	/* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
	if (!r) {
Milan Broz's avatar
Milan Broz committed
691
		r = LUKS_read_phdr(hdr, 1, 0, ctx);
692
		if (r)
693
			log_err(ctx, _("Error re-reading LUKS header after update on device %s."),
Milan Broz's avatar
Milan Broz committed
694
				device_path(device));
695 696
	}

697
	return r;
698
}
699

700
/* Check that kernel supports requested cipher by decryption of one sector */
701
int LUKS_check_cipher(struct crypt_device *ctx, size_t keylength, const char *cipher, const char *cipher_mode)
702 703 704 705 706
{
	int r;
	struct volume_key *empty_key;
	char buf[SECTOR_SIZE];

707
	log_dbg(ctx, "Checking if cipher %s-%s is usable.", cipher, cipher_mode);
708

709
	empty_key = crypt_alloc_volume_key(keylength, NULL);
710 711 712
	if (!empty_key)
		return -ENOMEM;

713 714 715
	/* No need to get KEY quality random but it must avoid known weak keys. */
	r = crypt_random_get(ctx, empty_key->key, empty_key->keylength, CRYPT_RND_NORMAL);
	if (!r)
716
		r = LUKS_decrypt_from_storage(buf, sizeof(buf), cipher, cipher_mode, empty_key, 0, ctx);
717 718

	crypt_free_volume_key(empty_key);
719
	crypt_memzero(buf, sizeof(buf));
720 721 722
	return r;
}

723
int LUKS_generate_phdr(struct luks_phdr *header,
724
		       const struct volume_key *vk,
725 726
		       const char *cipherName, const char *cipherMode, const char *hashSpec,
		       const char *uuid, unsigned int stripes,
727 728 729
		       uint64_t data_offset,
		       uint64_t align_offset,
		       bool fixed_data_offset,
730
		       struct crypt_device *ctx)
731
{
732
	unsigned int i = 0, alignPayload, alignOffset, hdr_sectors = LUKS_calculate_device_sectors(vk->keylength);
733
	size_t blocksPerStripeSet, currentSector;
734 735
	int r;
	uuid_t partitionUuid;
736 737
	struct crypt_pbkdf_type *pbkdf;
	double PBKDF2_temp;
738
	char luksMagic[] = LUKS_MAGIC;
739

740 741 742 743
	if (data_offset % SECTOR_SIZE || align_offset % SECTOR_SIZE)
		return -EINVAL;
	alignPayload = data_offset / SECTOR_SIZE;
	alignOffset = align_offset / SECTOR_SIZE;
744

745
	if (alignPayload && fixed_data_offset && alignPayload < hdr_sectors) {
746
		log_err(ctx, _("Data offset for detached LUKS header must be "
747
			       "either 0 or higher than header size."));
748 749 750
		return -EINVAL;
	}

751
	if (crypt_hmac_size(hashSpec) < LUKS_DIGESTSIZE) {
752
		log_err(ctx, _("Requested LUKS hash %s is not supported."), hashSpec);
753 754 755
		return -EINVAL;
	}

756
	if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
757
		log_err(ctx, _("Wrong LUKS UUID format provided."));
758 759 760 761 762
		return -EINVAL;
	}
	if (!uuid)
		uuid_generate(partitionUuid);

763 764 765 766 767
	memset(header,0,sizeof(struct luks_phdr));

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

772
	header->keyBytes=vk->keylength;
773

774 775
	LUKS_fix_header_compatible(header);

776
	log_dbg(ctx, "Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
777 778 779
		header->version, header->hashSpec ,header->cipherName, header->cipherMode,
		header->keyBytes);

780
	r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
781
	if(r < 0) {
782
		log_err(ctx, _("Cannot create LUKS header: reading random salt failed."));
783 784
		return r;
	}
785

786
	/* Compute master key digest */
787
	pbkdf = crypt_get_pbkdf(ctx);
788 789
	r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
	if (r < 0)
790
		return r;
791
	assert(pbkdf->iterations);
792

793 794 795 796
	PBKDF2_temp = (double)pbkdf->iterations * LUKS_MKD_ITERATIONS_MS / pbkdf->time_ms;
	if (PBKDF2_temp > (double)UINT32_MAX)
		return -EINVAL;
	header->mkDigestIterations = at_least((uint32_t)PBKDF2_temp, LUKS_MKD_ITERATIONS_MIN);
797

Milan Broz's avatar
Milan Broz committed
798
	r = crypt_pbkdf(CRYPT_KDF_PBKDF2, header->hashSpec, vk->key,vk->keylength,
799 800
			header->mkDigestSalt, LUKS_SALTSIZE,
			header->mkDigest,LUKS_DIGESTSIZE,
801
			header->mkDigestIterations, 0, 0);
802
	if(r < 0) {
803
		log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s)."),
804
			header->hashSpec);
805 806
		return r;
	}
807

808
	currentSector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
809
	blocksPerStripeSet = AF_split_sectors(vk->keylength, stripes);
810 811 812 813
	for(i = 0; i < LUKS_NUMKEYS; ++i) {
		header->keyblock[i].active = LUKS_KEY_DISABLED;
		header->keyblock[i].keyMaterialOffset = currentSector;
		header->keyblock[i].stripes = stripes;
814
		currentSector = size_round_up(currentSector + blocksPerStripeSet,
815
						LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
816 817
	}

818
	if (fixed_data_offset) {
819 820 821 822
		/* for separate metadata device use alignPayload directly */
		header->payloadOffset = alignPayload;
	} else {
		/* alignOffset - offset from natural device alignment provided by topology info */
823
		currentSector = size_round_up(currentSector, alignPayload);
824 825
		header->payloadOffset = currentSector + alignOffset;
	}
826 827 828

        uuid_unparse(partitionUuid, header->uuid);

829
	log_dbg(ctx, "Data offset %d, UUID %s, digest iterations %" PRIu32,
830
		header->payloadOffset, header->uuid, header->mkDigestIterations);
831

832 833 834
	return 0;
}

835 836 837 838 839 840 841 842
int LUKS_hdr_uuid_set(
	struct luks_phdr *hdr,
	const char *uuid,
	struct crypt_device *ctx)
{
	uuid_t partitionUuid;

	if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
843
		log_err(ctx, _("Wrong LUKS UUID format provided."));
844 845 846 847 848 849 850
		return -EINVAL;
	}
	if (!uuid)
		uuid_generate(partitionUuid);

	uuid_unparse(partitionUuid, hdr->uuid);

Milan Broz's avatar
Milan Broz committed
851
	return LUKS_write_phdr(hdr, ctx);
852 853
}

Milan Broz's avatar
Milan Broz committed
854
int LUKS_set_key(unsigned int keyIndex,
855
		 const char *password, size_t passwordLen,
856
		 struct luks_phdr *hdr, struct volume_key *vk,
857
		 struct crypt_device *ctx)
858
{
859
	struct volume_key *derived_key;
860
	char *AfKey = NULL;
861
	size_t AFEKSize;
862
	struct crypt_pbkdf_type *pbkdf;
863
	int r;
864

865
	if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
866
		log_err(ctx, _("Key slot %d active, purge first."), keyIndex);
867 868
		return -EINVAL;
	}
869

Andrea Gelmini's avatar
Andrea Gelmini committed
870
	/* LUKS keyslot has always at least 4000 stripes according to specification */
871
	if(hdr->keyblock[keyIndex].stripes < 4000) {
872
	        log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?"),
873
			keyIndex);
874 875
	         return -EINVAL;
	}
876

877
	log_dbg(ctx, "Calculating data for key slot %d", keyIndex);
878
	pbkdf = crypt_get_pbkdf(ctx);
879 880
	r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
	if (r < 0)
881
		return r;
882
	assert(pbkdf->iterations);
883 884 885 886

	/*
	 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
	 */
887 888
	hdr->keyblock[keyIndex].passwordIterations =
		at_least(pbkdf->iterations, LUKS_SLOT_ITERATIONS_MIN);
889
	log_dbg(ctx, "Key slot %d use %" PRIu32 " password iterations.", keyIndex,
890
		hdr->keyblock[keyIndex].passwordIterations);
891

892 893 894 895
	derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
	if (!derived_key)
		return -ENOMEM;

896
	r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
897
		       LUKS_SALTSIZE, CRYPT_RND_SALT);
898
	if (r < 0)
899
		goto out;
900

Milan Broz's avatar
Milan Broz committed
901
	r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
902 903
			hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
			derived_key->key, hdr->keyBytes,
904
			hdr->keyblock[keyIndex].passwordIterations, 0, 0);
905 906
	if (r < 0)
		goto out;
907

908
	/*
Milan Broz's avatar
Milan Broz committed
909
	 * AF splitting, the masterkey stored in vk->key is split to AfKey
910
	 */
911
	assert(vk->keylength == hdr->keyBytes);
912
	AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
913 914 915 916 917
	AfKey = crypt_safe_alloc(AFEKSize);
	if (!AfKey) {
		r = -ENOMEM;
		goto out;
	}
918

919
	log_dbg(ctx, "Using hash %s for AF in key slot %d, %d stripes",
920
		hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
921
	r = AF_split(ctx, vk->key, AfKey, vk->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
922 923
	if (r < 0)
		goto out;
924

925
	log_dbg(ctx, "Updating key slot %d [0x%04x] area.", keyIndex,
Milan Broz's avatar
Milan Broz committed
926
		hdr->keyblock[keyIndex].keyMaterialOffset << 9);
927 928 929
	/* Encryption via dm */
	r = LUKS_encrypt_to_storage(AfKey,
				    AFEKSize,
930
				    hdr->cipherName, hdr->cipherMode,
931
				    derived_key,
932 933
				    hdr->keyblock[keyIndex].keyMaterialOffset,
				    ctx);
934
	if (r < 0)
935 936 937
		goto out;

	/* Mark the key as active in phdr */
938
	r = LUKS_keyslot_set(hdr, (int)keyIndex, 1, ctx);
939 940
	if (r < 0)
		goto out;
941

Milan Broz's avatar
Milan Broz committed
942
	r = LUKS_write_phdr(hdr, ctx);
943 944
	if (r < 0)
		goto out;
945 946 947

	r = 0;
out:
948
	crypt_safe_free(AfKey);
949
	crypt_free_volume_key(derived_key);
950 951 952
	return r;
}

953 954 955
/* Check whether a volume key is invalid. */
int LUKS_verify_volume_key(const struct luks_phdr *hdr,
			   const struct volume_key *vk)
956 957 958
{
	char checkHashBuf[LUKS_DIGESTSIZE];

Milan Broz's avatar
Milan Broz committed
959
	if (crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, vk->key, vk->keylength,
960
			hdr->mkDigestSalt, LUKS_SALTSIZE,
961
			checkHashBuf, LUKS_DIGESTSIZE,
962
			hdr->mkDigestIterations, 0, 0) < 0)
963 964 965 966 967 968 969 970
		return -EINVAL;

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

	return 0;
}

971
/* Try to open a particular key slot */
Milan Broz's avatar
Milan Broz committed
972
static int LUKS_open_key(unsigned int keyIndex,
973 974 975
		  const char *password,
		  size_t passwordLen,
		  struct luks_phdr *hdr,
976
		  struct volume_key *vk,
977
		  struct crypt_device *ctx)
978
{
979
	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
980
	struct volume_key *derived_key;
981 982 983
	char *AfKey;
	size_t AFEKSize;
	int r;
984

985
	log_dbg(ctx, "Trying to open key slot %d [%s].", keyIndex,
Milan Broz's avatar
Milan Broz committed
986
		dbg_slot_state(ki));
987

988
	if (ki < CRYPT_SLOT_ACTIVE)
989 990
		return -ENOENT;

991 992 993
	derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
	if (!derived_key)
		return -ENOMEM;
994

995
	assert(vk->keylength == hdr->keyBytes);
996
	AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
997
	AfKey = crypt_safe_alloc(AFEKSize);
998 999 1000 1001
	if (!AfKey) {
		r = -ENOMEM;
		goto out;
	}
1002

Milan Broz's avatar
Milan Broz committed
1003
	r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
1004 1005
			hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
			derived_key->key, hdr->keyBytes,
1006
			hdr->keyblock[keyIndex].passwordIterations, 0, 0);
1007 1008
	if (r < 0)
		goto out;
1009

1010
	log_dbg(ctx, "Reading key slot %d area.", keyIndex);
1011 1012
	r = LUKS_decrypt_from_storage(AfKey,
				      AFEKSize,
1013
				      hdr->cipherName, hdr->cipherMode,
1014
				      derived_key,
1015 1016
				      hdr->keyblock[keyIndex].keyMaterialOffset,
				      ctx);
1017
	if (r < 0)
1018
		goto out;
1019

1020
	r = AF_merge(ctx, AfKey, vk->key, vk->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
1021 1022
	if (r < 0)
		goto out;
1023

1024
	r = LUKS_verify_volume_key(hdr, vk);
1025 1026 1027 1028

	/* Allow only empty passphrase with null cipher */
	if (!r && !strcmp(hdr->cipherName, "cipher_null") && passwordLen)
		r = -EPERM;
1029
out:
1030
	crypt_safe_free(AfKey);
1031
	crypt_free_volume_key(derived_key);
1032 1033 1034
	return r;
}

Milan Broz's avatar
Milan Broz committed
1035
int LUKS_open_key_with_hdr(int keyIndex,
1036 1037 1038
			   const char *password,
			   size_t passwordLen,
			   struct luks_phdr *hdr