xref: /dflybsd-src/contrib/cryptsetup/luks/keymanage.c (revision 8bd3d23cacb2ee28cb21ee3d50f68e868fa018cc)
1 /*
2  * LUKS - Linux Unified Key Setup
3  *
4  * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/ioctl.h>
23 #include <netinet/in.h>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 
32 #include "luks.h"
33 #include "af.h"
34 #include "pbkdf.h"
35 #include "random.h"
36 #include <uuid.h>
37 #include <../lib/internal.h>
38 
39 #define div_round_up(a,b) ({           \
40 	typeof(a) __a = (a);          \
41 	typeof(b) __b = (b);          \
42 	(__a - 1) / __b + 1;        \
43 })
44 
45 static inline int round_up_modulo(int x, int m) {
46 	return div_round_up(x, m) * m;
47 }
48 
49 struct luks_masterkey *LUKS_alloc_masterkey(int keylength, const char *key)
50 {
51 	struct luks_masterkey *mk=malloc(sizeof(*mk) + keylength);
52 	if(NULL == mk) return NULL;
53 	mk->keyLength=keylength;
54 	if (key)
55 		memcpy(&mk->key, key, keylength);
56 	return mk;
57 }
58 
59 void LUKS_dealloc_masterkey(struct luks_masterkey *mk)
60 {
61 	if(NULL != mk) {
62 		memset(mk->key,0,mk->keyLength);
63 		mk->keyLength=0;
64 		free(mk);
65 	}
66 }
67 
68 struct luks_masterkey *LUKS_generate_masterkey(int keylength)
69 {
70 	struct luks_masterkey *mk=LUKS_alloc_masterkey(keylength, NULL);
71 	if(NULL == mk) return NULL;
72 
73 	int r = getRandom(mk->key,keylength);
74 	if(r < 0) {
75 		LUKS_dealloc_masterkey(mk);
76 		return NULL;
77 	}
78 	return mk;
79 }
80 
81 int LUKS_hdr_backup(
82 	const char *backup_file,
83 	const char *device,
84 	struct luks_phdr *hdr,
85 	struct crypt_device *ctx)
86 {
87 	int r = 0, devfd = -1;
88 	size_t buffer_size;
89 	char *buffer = NULL;
90 	struct stat st;
91 
92 	if(stat(backup_file, &st) == 0) {
93 		log_err(ctx, _("Requested file %s already exist.\n"), backup_file);
94 		return -EINVAL;
95 	}
96 
97 	r = LUKS_read_phdr(device, hdr, 0, ctx);
98 	if (r)
99 		return r;
100 
101 	buffer_size = hdr->payloadOffset << SECTOR_SHIFT;
102 	buffer = safe_alloc(buffer_size);
103 	if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) {
104 		r = -ENOMEM;
105 		goto out;
106 	}
107 
108 	log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).",
109 		sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS);
110 
111 	devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC);
112 	if(devfd == -1) {
113 		log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
114 		r = -EINVAL;
115 		goto out;
116 	}
117 
118 	if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) {
119 		r = -EIO;
120 		goto out;
121 	}
122 	close(devfd);
123 
124 	/* Wipe unused area, so backup cannot contain old signatures */
125 	memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr));
126 
127 	devfd = creat(backup_file, S_IRUSR);
128 	if(devfd == -1) {
129 		r = -EINVAL;
130 		goto out;
131 	}
132 	if(write(devfd, buffer, buffer_size) < buffer_size) {
133 		log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
134 		r = -EIO;
135 		goto out;
136 	}
137 	close(devfd);
138 
139 	r = 0;
140 out:
141 	if (devfd != -1)
142 		close(devfd);
143 	safe_free(buffer);
144 	return r;
145 }
146 
147 int LUKS_hdr_restore(
148 	const char *backup_file,
149 	const char *device,
150 	struct luks_phdr *hdr,
151 	struct crypt_device *ctx)
152 {
153 	int r = 0, devfd = -1, diff_uuid = 0;
154 	size_t buffer_size;
155 	char *buffer = NULL, msg[200];
156 	struct stat st;
157 	struct luks_phdr hdr_file;
158 
159 	if(stat(backup_file, &st) < 0) {
160 		log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file);
161 		return -EINVAL;
162 	}
163 
164 	r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx);
165 	buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT;
166 
167 	if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
168 		log_err(ctx, _("Backup file do not contain valid LUKS header.\n"));
169 		r = -EINVAL;
170 		goto out;
171 	}
172 
173 	buffer = safe_alloc(buffer_size);
174 	if (!buffer) {
175 		r = -ENOMEM;
176 		goto out;
177 	}
178 
179 	devfd = open(backup_file, O_RDONLY);
180 	if(devfd == -1) {
181 		log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
182 		r = -EINVAL;
183 		goto out;
184 	}
185 
186 	if(read(devfd, buffer, buffer_size) < buffer_size) {
187 		log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
188 		r = -EIO;
189 		goto out;
190 	}
191 	close(devfd);
192 
193 	r = LUKS_read_phdr(device, hdr, 0, ctx);
194 	if (r == 0) {
195 		log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device);
196 		if(hdr->payloadOffset != hdr_file.payloadOffset ||
197 		   hdr->keyBytes != hdr_file.keyBytes) {
198 			log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
199 			r = -EINVAL;
200 			goto out;
201 		}
202 		if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
203 			diff_uuid = 1;
204 	}
205 
206 	if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device,
207 		 r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
208 		     _("already contains LUKS header. Replacing header will destroy existing keyslots."),
209 		     diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
210 		r = -ENOMEM;
211 		goto out;
212 	}
213 
214 	if (!crypt_confirm(ctx, msg)) {
215 		r = -EINVAL;
216 		goto out;
217 	}
218 
219 	log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.",
220 		sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device);
221 
222 	devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC);
223 	if(devfd == -1) {
224 		log_err(ctx, _("Cannot open device %s.\n"), device);
225 		r = -EINVAL;
226 		goto out;
227 	}
228 
229 	if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) {
230 		r = -EIO;
231 		goto out;
232 	}
233 	close(devfd);
234 
235 	/* Be sure to reload new data */
236 	r = LUKS_read_phdr(device, hdr, 0, ctx);
237 out:
238 	if (devfd != -1)
239 		close(devfd);
240 	safe_free(buffer);
241 	return r;
242 }
243 
244 static int _check_and_convert_hdr(const char *device,
245 				  struct luks_phdr *hdr,
246 				  int require_luks_device,
247 				  struct crypt_device *ctx)
248 {
249 	int r = 0;
250 	unsigned int i;
251 	char luksMagic[] = LUKS_MAGIC;
252 
253 	if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
254 		log_dbg("LUKS header not detected.");
255 		if (require_luks_device)
256 			log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
257 		else
258 			set_error(_("Device %s is not a valid LUKS device."), device);
259 		r = -EINVAL;
260 	} else if((hdr->version = ntohs(hdr->version)) != 1) {	/* Convert every uint16/32_t item from network byte order */
261 		log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
262 		r = -EINVAL;
263 	} else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) {
264 		log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
265 		r = -EINVAL;
266 	} else {
267 		hdr->payloadOffset      = ntohl(hdr->payloadOffset);
268 		hdr->keyBytes           = ntohl(hdr->keyBytes);
269 		hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
270 
271 		for(i = 0; i < LUKS_NUMKEYS; ++i) {
272 			hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
273 			hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
274 			hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
275 			hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
276 		}
277 	}
278 
279 	return r;
280 }
281 
282 static void _to_lower(char *str, unsigned max_len)
283 {
284 	for(; *str && max_len; str++, max_len--)
285 		if (isupper(*str))
286 			*str = tolower(*str);
287 }
288 
289 static void LUKS_fix_header_compatible(struct luks_phdr *header)
290 {
291 	/* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
292 	 * so always convert hash to lower case in header */
293 	_to_lower(header->hashSpec, LUKS_HASHSPEC_L);
294 }
295 
296 int LUKS_read_phdr_backup(const char *backup_file,
297 			  const char *device,
298 			  struct luks_phdr *hdr,
299 			  int require_luks_device,
300 			  struct crypt_device *ctx)
301 {
302 	int devfd = 0, r = 0;
303 
304 	log_dbg("Reading LUKS header of size %d from backup file %s",
305 		sizeof(struct luks_phdr), backup_file);
306 
307 	devfd = open(backup_file, O_RDONLY);
308 	if(-1 == devfd) {
309 		log_err(ctx, _("Cannot open file %s.\n"), device);
310 		return -EINVAL;
311 	}
312 
313 	if(read(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr))
314 		r = -EIO;
315 	else {
316 		LUKS_fix_header_compatible(hdr);
317 		r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx);
318 	}
319 
320 	close(devfd);
321 	return r;
322 }
323 
324 int LUKS_read_phdr(const char *device,
325 		   struct luks_phdr *hdr,
326 		   int require_luks_device,
327 		   struct crypt_device *ctx)
328 {
329 	int devfd = 0, r = 0;
330 	uint64_t size;
331 
332 	log_dbg("Reading LUKS header of size %d from device %s",
333 		sizeof(struct luks_phdr), device);
334 
335 	devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC);
336 	if(-1 == devfd) {
337 		log_err(ctx, _("Cannot open device %s.\n"), device);
338 		return -EINVAL;
339 	}
340 
341 	if(read_blockwise(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr))
342 		r = -EIO;
343 	else
344 		r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx);
345 
346 #ifdef BLKGETSIZE64
347 	if (r == 0 && (ioctl(devfd, BLKGETSIZE64, &size) < 0 ||
348 	    size < (uint64_t)hdr->payloadOffset)) {
349 		log_err(ctx, _("LUKS header detected but device %s is too small.\n"), device);
350 		r = -EINVAL;
351 	}
352 #endif
353 	close(devfd);
354 
355 	return r;
356 }
357 
358 int LUKS_write_phdr(const char *device,
359 		    struct luks_phdr *hdr,
360 		    struct crypt_device *ctx)
361 {
362 	int devfd = 0;
363 	unsigned int i;
364 	struct luks_phdr convHdr;
365 	int r;
366 
367 	log_dbg("Updating LUKS header of size %d on device %s",
368 		sizeof(struct luks_phdr), device);
369 
370 	devfd = open(device,O_RDWR | O_DIRECT | O_SYNC);
371 	if(-1 == devfd) {
372 		log_err(ctx, _("Cannot open device %s.\n"), device);
373 		return -EINVAL;
374 	}
375 
376 	memcpy(&convHdr, hdr, sizeof(struct luks_phdr));
377 	memset(&convHdr._padding, 0, sizeof(convHdr._padding));
378 
379 	/* Convert every uint16/32_t item to network byte order */
380 	convHdr.version            = htons(hdr->version);
381 	convHdr.payloadOffset      = htonl(hdr->payloadOffset);
382 	convHdr.keyBytes           = htonl(hdr->keyBytes);
383 	convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
384 	for(i = 0; i < LUKS_NUMKEYS; ++i) {
385 		convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
386 		convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
387 		convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
388 		convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
389 	}
390 
391 	r = write_blockwise(devfd, &convHdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr) ? -EIO : 0;
392 	if (r)
393 		log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device);
394 	close(devfd);
395 
396 	/* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
397 	if (!r) {
398 		r = LUKS_read_phdr(device, hdr, 1, ctx);
399 		if (r)
400 			log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device);
401 	}
402 
403 	return r;
404 }
405 
406 static int LUKS_PBKDF2_performance_check(const char *hashSpec,
407 					 uint64_t *PBKDF2_per_sec,
408 					 struct crypt_device *ctx)
409 {
410 	if (!*PBKDF2_per_sec) {
411 		if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) {
412 			log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec);
413 			return -EINVAL;
414 		}
415 		log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec);
416 	}
417 
418 	return 0;
419 }
420 
421 int LUKS_generate_phdr(struct luks_phdr *header,
422 		       const struct luks_masterkey *mk,
423 		       const char *cipherName, const char *cipherMode, const char *hashSpec,
424 		       const char *uuid, unsigned int stripes,
425 		       unsigned int alignPayload,
426 		       unsigned int alignOffset,
427 		       uint32_t iteration_time_ms,
428 		       uint64_t *PBKDF2_per_sec,
429 		       struct crypt_device *ctx)
430 {
431 	unsigned int i=0;
432 	unsigned int blocksPerStripeSet = div_round_up(mk->keyLength*stripes,SECTOR_SIZE);
433 	int r;
434 	uint32_t ret;
435 	char luksMagic[] = LUKS_MAGIC;
436 	uuid_t partitionUuid;
437 	int currentSector;
438 	int alignSectors = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
439 	if (alignPayload == 0)
440 		alignPayload = alignSectors;
441 
442 	memset(header,0,sizeof(struct luks_phdr));
443 
444 	/* Set Magic */
445 	memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
446 	header->version=1;
447 	strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
448 	strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
449 	strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
450 
451 	header->keyBytes=mk->keyLength;
452 
453 	LUKS_fix_header_compatible(header);
454 
455 	log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
456 		header->version, header->hashSpec ,header->cipherName, header->cipherMode,
457 		header->keyBytes);
458 
459 	r = getRandom(header->mkDigestSalt,LUKS_SALTSIZE);
460 	if(r < 0) {
461 		log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
462 		return r;
463 	}
464 
465 	if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
466 		return r;
467 
468 	/* Compute master key digest */
469 	iteration_time_ms /= 8;
470 	header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
471 					      LUKS_MKD_ITERATIONS_MIN);
472 
473 	r = PBKDF2_HMAC(header->hashSpec,mk->key,mk->keyLength,
474 			header->mkDigestSalt,LUKS_SALTSIZE,
475 			header->mkDigestIterations,
476 			header->mkDigest,LUKS_DIGESTSIZE);
477 	if(r < 0) {
478 		log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
479 			header->hashSpec);
480 		return r;
481 	}
482 
483 	currentSector = round_up_modulo(LUKS_PHDR_SIZE, alignSectors);
484 	for(i = 0; i < LUKS_NUMKEYS; ++i) {
485 		header->keyblock[i].active = LUKS_KEY_DISABLED;
486 		header->keyblock[i].keyMaterialOffset = currentSector;
487 		header->keyblock[i].stripes = stripes;
488 		currentSector = round_up_modulo(currentSector + blocksPerStripeSet, alignSectors);
489 	}
490 	currentSector = round_up_modulo(currentSector, alignPayload);
491 
492 	/* alignOffset - offset from natural device alignment provided by topology info */
493 	header->payloadOffset = currentSector + alignOffset;
494 
495 	uuid_from_string(uuid, &partitionUuid, &ret);
496 	if (uuid && ret != uuid_s_ok) {
497 		log_err(ctx, _("Wrong UUID format provided, generating new one.\n"));
498 		uuid = NULL;
499 	}
500 	if (!uuid)
501 		uuid_create(&partitionUuid, &ret);
502 	uuid_to_string(&partitionUuid, &header->uuid, &ret);
503 
504 	log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
505 		header->payloadOffset, header->uuid, header->mkDigestIterations);
506 
507 	return 0;
508 }
509 
510 int LUKS_set_key(const char *device, unsigned int keyIndex,
511 		 const char *password, size_t passwordLen,
512 		 struct luks_phdr *hdr, struct luks_masterkey *mk,
513 		 uint32_t iteration_time_ms,
514 		 uint64_t *PBKDF2_per_sec,
515 		 struct crypt_device *ctx)
516 {
517 	char derivedKey[hdr->keyBytes];
518 	char *AfKey;
519 	unsigned int AFEKSize;
520 	uint64_t PBKDF2_temp;
521 	int r;
522 
523 	if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
524 		log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
525 		return -EINVAL;
526 	}
527 
528 	if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
529 	        log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
530 			keyIndex);
531 	         return -EINVAL;
532 	}
533 
534 	log_dbg("Calculating data for key slot %d", keyIndex);
535 
536 	if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
537 		return r;
538 
539 	/*
540 	 * Avoid floating point operation
541 	 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
542 	 */
543 	PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
544 	PBKDF2_temp /= 1024;
545 	if (PBKDF2_temp > UINT32_MAX)
546 		PBKDF2_temp = UINT32_MAX;
547 	hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
548 							      LUKS_SLOT_ITERATIONS_MIN);
549 
550 	log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
551 
552 	r = getRandom(hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE);
553 	if(r < 0) return r;
554 
555 //	assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
556 
557 	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
558 			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
559 			hdr->keyblock[keyIndex].passwordIterations,
560 			derivedKey, hdr->keyBytes);
561 	if(r < 0) return r;
562 
563 	/*
564 	 * AF splitting, the masterkey stored in mk->key is splitted to AfMK
565 	 */
566 	AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
567 	AfKey = (char *)malloc(AFEKSize);
568 	if(AfKey == NULL) return -ENOMEM;
569 
570 	log_dbg("Using hash %s for AF in key slot %d, %d stripes",
571 		hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
572 	r = AF_split(mk->key,AfKey,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
573 	if(r < 0) goto out;
574 
575 	log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
576 		hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
577 	/* Encryption via dm */
578 	r = LUKS_encrypt_to_storage(AfKey,
579 				    AFEKSize,
580 				    hdr,
581 				    derivedKey,
582 				    hdr->keyBytes,
583 				    device,
584 				    hdr->keyblock[keyIndex].keyMaterialOffset,
585 				    ctx);
586 	if(r < 0) {
587 		if(!get_error())
588 			log_err(ctx, _("Failed to write to key storage.\n"));
589 		goto out;
590 	}
591 
592 	/* Mark the key as active in phdr */
593 	r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
594 	if(r < 0) goto out;
595 
596 	r = LUKS_write_phdr(device, hdr, ctx);
597 	if(r < 0) goto out;
598 
599 	r = 0;
600 out:
601 	free(AfKey);
602 	return r;
603 }
604 
605 /* Check whether a master key is invalid. */
606 int LUKS_verify_master_key(const struct luks_phdr *hdr,
607 			   const struct luks_masterkey *mk)
608 {
609 	char checkHashBuf[LUKS_DIGESTSIZE];
610 
611 	if (PBKDF2_HMAC(hdr->hashSpec, mk->key, mk->keyLength,
612 			hdr->mkDigestSalt, LUKS_SALTSIZE,
613 			hdr->mkDigestIterations, checkHashBuf,
614 			LUKS_DIGESTSIZE) < 0)
615 		return -EINVAL;
616 
617 	if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
618 		return -EPERM;
619 
620 	return 0;
621 }
622 
623 /* Try to open a particular key slot */
624 static int LUKS_open_key(const char *device,
625 		  unsigned int keyIndex,
626 		  const char *password,
627 		  size_t passwordLen,
628 		  struct luks_phdr *hdr,
629 		  struct luks_masterkey *mk,
630 		  struct crypt_device *ctx)
631 {
632 	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
633 	char derivedKey[hdr->keyBytes];
634 	char *AfKey;
635 	size_t AFEKSize;
636 	int r;
637 
638 	log_dbg("Trying to open key slot %d [%d].", keyIndex, (int)ki);
639 
640 	if (ki < CRYPT_SLOT_ACTIVE)
641 		return -ENOENT;
642 
643 	// assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
644 
645 	AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
646 	AfKey = (char *)malloc(AFEKSize);
647 	if(AfKey == NULL) return -ENOMEM;
648 
649 	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
650 			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
651 			hdr->keyblock[keyIndex].passwordIterations,
652 			derivedKey, hdr->keyBytes);
653 	if(r < 0) goto out;
654 
655 	log_dbg("Reading key slot %d area.", keyIndex);
656 	r = LUKS_decrypt_from_storage(AfKey,
657 				      AFEKSize,
658 				      hdr,
659 				      derivedKey,
660 				      hdr->keyBytes,
661 				      device,
662 				      hdr->keyblock[keyIndex].keyMaterialOffset,
663 				      ctx);
664 	if(r < 0) {
665 		log_err(ctx, _("Failed to read from key storage.\n"));
666 		goto out;
667 	}
668 
669 	r = AF_merge(AfKey,mk->key,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
670 	if(r < 0) goto out;
671 
672 	r = LUKS_verify_master_key(hdr, mk);
673 	if (r >= 0)
674 		log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
675 out:
676 	free(AfKey);
677 	return r;
678 }
679 
680 int LUKS_open_key_with_hdr(const char *device,
681 			   int keyIndex,
682 			   const char *password,
683 			   size_t passwordLen,
684 			   struct luks_phdr *hdr,
685 			   struct luks_masterkey **mk,
686 			   struct crypt_device *ctx)
687 {
688 	unsigned int i;
689 	int r;
690 
691 	*mk = LUKS_alloc_masterkey(hdr->keyBytes, NULL);
692 
693 	if (keyIndex >= 0)
694 		return LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *mk, ctx);
695 
696 	for(i = 0; i < LUKS_NUMKEYS; i++) {
697 		r = LUKS_open_key(device, i, password, passwordLen, hdr, *mk, ctx);
698 		if(r == 0)
699 			return i;
700 
701 		/* Do not retry for errors that are no -EPERM or -ENOENT,
702 		   former meaning password wrong, latter key slot inactive */
703 		if ((r != -EPERM) && (r != -ENOENT))
704 			return r;
705 	}
706 	/* Warning, early returns above */
707 	log_err(ctx, _("No key available with this passphrase.\n"));
708 	return -EPERM;
709 }
710 
711 /*
712  * Wipe patterns according to Gutmann's Paper
713  */
714 
715 static void wipeSpecial(char *buffer, size_t buffer_size, unsigned int turn)
716 {
717         unsigned int i;
718 
719         unsigned char write_modes[][3] = {
720                 {"\x55\x55\x55"}, {"\xaa\xaa\xaa"}, {"\x92\x49\x24"},
721                 {"\x49\x24\x92"}, {"\x24\x92\x49"}, {"\x00\x00\x00"},
722                 {"\x11\x11\x11"}, {"\x22\x22\x22"}, {"\x33\x33\x33"},
723                 {"\x44\x44\x44"}, {"\x55\x55\x55"}, {"\x66\x66\x66"},
724                 {"\x77\x77\x77"}, {"\x88\x88\x88"}, {"\x99\x99\x99"},
725                 {"\xaa\xaa\xaa"}, {"\xbb\xbb\xbb"}, {"\xcc\xcc\xcc"},
726                 {"\xdd\xdd\xdd"}, {"\xee\xee\xee"}, {"\xff\xff\xff"},
727                 {"\x92\x49\x24"}, {"\x49\x24\x92"}, {"\x24\x92\x49"},
728                 {"\x6d\xb6\xdb"}, {"\xb6\xdb\x6d"}, {"\xdb\x6d\xb6"}
729         };
730 
731         for(i = 0; i < buffer_size / 3; ++i) {
732                 memcpy(buffer, write_modes[turn], 3);
733                 buffer += 3;
734         }
735 }
736 
737 static int wipe(const char *device, unsigned int from, unsigned int to)
738 {
739 	int devfd;
740 	char *buffer;
741 	unsigned int i;
742 	unsigned int bufLen = (to - from) * SECTOR_SIZE;
743 	int r = 0;
744 
745 	devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
746 	if(devfd == -1)
747 		return -EINVAL;
748 
749 	buffer = (char *) malloc(bufLen);
750 	if(!buffer) return -ENOMEM;
751 
752 	for(i = 0; i < 39; ++i) {
753 		if     (i >=  0 && i <  5) getRandom(buffer, bufLen);
754 		else if(i >=  5 && i < 32) wipeSpecial(buffer, bufLen, i - 5);
755 		else if(i >= 32 && i < 38) getRandom(buffer, bufLen);
756 		else if(i >= 38 && i < 39) memset(buffer, 0xFF, bufLen);
757 
758 		if(write_lseek_blockwise(devfd, buffer, bufLen, from * SECTOR_SIZE) < 0) {
759 			r = -EIO;
760 			break;
761 		}
762 	}
763 
764 	free(buffer);
765 	close(devfd);
766 
767 	return r;
768 }
769 
770 int LUKS_del_key(const char *device,
771 		 unsigned int keyIndex,
772 		 struct luks_phdr *hdr,
773 		 struct crypt_device *ctx)
774 {
775 	unsigned int startOffset, endOffset, stripesLen;
776 	int r;
777 
778 	r = LUKS_read_phdr(device, hdr, 1, ctx);
779 	if (r)
780 		return r;
781 
782 	r = LUKS_keyslot_set(hdr, keyIndex, 0);
783 	if (r) {
784 		log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
785 			keyIndex, LUKS_NUMKEYS - 1);
786 		return r;
787 	}
788 
789 	/* secure deletion of key material */
790 	startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
791 	stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
792 	endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
793 
794 	r = wipe(device, startOffset, endOffset);
795 	if (r) {
796 		log_err(ctx, _("Cannot wipe device %s.\n"), device);
797 		return r;
798 	}
799 
800 	r = LUKS_write_phdr(device, hdr, ctx);
801 
802 	return r;
803 }
804 
805 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
806 {
807 	int i;
808 
809 	if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
810 		return CRYPT_SLOT_INVALID;
811 
812 	if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
813 		return CRYPT_SLOT_INACTIVE;
814 
815 	if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
816 		return CRYPT_SLOT_INVALID;
817 
818 	for(i = 0; i < LUKS_NUMKEYS; i++)
819 		if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
820 			return CRYPT_SLOT_ACTIVE;
821 
822 	return CRYPT_SLOT_ACTIVE_LAST;
823 }
824 
825 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
826 {
827 	int i;
828 
829 	for (i = 0; i < LUKS_NUMKEYS; i++)
830 		if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
831 			break;
832 
833 	if (i == LUKS_NUMKEYS)
834 		return -EINVAL;
835 
836 	return i;
837 }
838 
839 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
840 {
841 	int i, num = 0;
842 
843 	for (i = 0; i < LUKS_NUMKEYS; i++)
844 		if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
845 			num++;
846 
847 	return num;
848 }
849 
850 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
851 {
852 	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
853 
854 	if (ki == CRYPT_SLOT_INVALID)
855 		return -EINVAL;
856 
857 	hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
858 	log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
859 	return 0;
860 }
861