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 420
			       phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
			       phdr->payloadOffset, 0,
Milan Broz's avatar
Milan Broz committed
421
			       1, ctx);
422
	if (r < 0)
423
		goto out;
424 425

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

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

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

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

		if (bad)
			need_write = 1;
463 464
	}

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

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

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

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

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

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

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

536 537 538
	return r;
}

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

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

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

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

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

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

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

	close(devfd);
	return r;
}

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

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

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

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

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

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

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

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

626 627 628 629 630 631
	/*
	 * 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) {
632
		log_dbg(ctx, "Old unaligned LUKS keyslot detected, disabling direct-io.");
633 634 635
		device_disable_direct_io(device);
	}

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

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

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

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

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

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

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

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

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

690 691
	/* 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
692
		r = LUKS_read_phdr(hdr, 1, 0, ctx);
693
		if (r)
694
			log_err(ctx, _("Error re-reading LUKS header after update on device %s."),
Milan Broz's avatar
Milan Broz committed
695
				device_path(device));
696 697
	}

698
	return r;
699
}
700

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

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

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

714 715 716
	/* 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)
717
		r = LUKS_decrypt_from_storage(buf, sizeof(buf), cipher, cipher_mode, empty_key, 0, ctx);
718 719

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

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

741
	/* For separate metadata device allow zero alignment */
Milan Broz's avatar
Milan Broz committed
742
	if (alignPayload == 0 && !detached_metadata_device)
743
		alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
744

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

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

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

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

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

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

775 776
	LUKS_fix_header_compatible(header);

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

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

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

794 795 796 797
	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);
798

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

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

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

        uuid_unparse(partitionUuid, header->uuid);

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

833 834 835
	return 0;
}

836 837 838 839 840 841 842 843
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) {
844
		log_err(ctx, _("Wrong LUKS UUID format provided."));
845 846 847 848 849 850 851
		return -EINVAL;
	}
	if (!uuid)
		uuid_generate(partitionUuid);

	uuid_unparse(partitionUuid, hdr->uuid);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return 0;
}

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

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

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

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

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

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

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

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

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

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

Milan Broz's avatar