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 	char *uu;
437 	uuid_t partitionUuid;
438 	int currentSector;
439 	int alignSectors = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
440 	if (alignPayload == 0)
441 		alignPayload = alignSectors;
442 
443 	memset(header,0,sizeof(struct luks_phdr));
444 
445 	/* Set Magic */
446 	memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
447 	header->version=1;
448 	strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
449 	strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
450 	strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
451 
452 	header->keyBytes=mk->keyLength;
453 
454 	LUKS_fix_header_compatible(header);
455 
456 	log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
457 		header->version, header->hashSpec ,header->cipherName, header->cipherMode,
458 		header->keyBytes);
459 
460 	r = getRandom(header->mkDigestSalt,LUKS_SALTSIZE);
461 	if(r < 0) {
462 		log_err(ctx,  _("Cannot create LUKS header: reading random salt failed.\n"));
463 		return r;
464 	}
465 
466 	if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx)))
467 		return r;
468 
469 	/* Compute master key digest */
470 	iteration_time_ms /= 8;
471 	header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
472 					      LUKS_MKD_ITERATIONS_MIN);
473 
474 	r = PBKDF2_HMAC(header->hashSpec,mk->key,mk->keyLength,
475 			header->mkDigestSalt,LUKS_SALTSIZE,
476 			header->mkDigestIterations,
477 			header->mkDigest,LUKS_DIGESTSIZE);
478 	if(r < 0) {
479 		log_err(ctx,  _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
480 			header->hashSpec);
481 		return r;
482 	}
483 
484 	currentSector = round_up_modulo(LUKS_PHDR_SIZE, alignSectors);
485 	for(i = 0; i < LUKS_NUMKEYS; ++i) {
486 		header->keyblock[i].active = LUKS_KEY_DISABLED;
487 		header->keyblock[i].keyMaterialOffset = currentSector;
488 		header->keyblock[i].stripes = stripes;
489 		currentSector = round_up_modulo(currentSector + blocksPerStripeSet, alignSectors);
490 	}
491 	currentSector = round_up_modulo(currentSector, alignPayload);
492 
493 	/* alignOffset - offset from natural device alignment provided by topology info */
494 	header->payloadOffset = currentSector + alignOffset;
495 
496 	uuid_from_string(uuid, &partitionUuid, &ret);
497 	if (uuid && ret != uuid_s_ok) {
498 		log_err(ctx, _("Wrong UUID format provided, generating new one.\n"));
499 		uuid = NULL;
500 	}
501 	if (!uuid)
502 		uuid_create(&partitionUuid, &ret);
503 	uuid_to_string(&partitionUuid, &uu, &ret);
504 	if (uu == NULL) {
505 		log_err(ctx, _("Cannot allocate memory in uuid_to_string()\n"));
506 		return -1;
507 	}
508 	memcpy(header->uuid, uu, UUID_STRING_L);
509 	free(uu);
510 
511 	log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
512 		header->payloadOffset, header->uuid, header->mkDigestIterations);
513 
514 	return 0;
515 }
516 
517 int LUKS_set_key(const char *device, unsigned int keyIndex,
518 		 const char *password, size_t passwordLen,
519 		 struct luks_phdr *hdr, struct luks_masterkey *mk,
520 		 uint32_t iteration_time_ms,
521 		 uint64_t *PBKDF2_per_sec,
522 		 struct crypt_device *ctx)
523 {
524 	char derivedKey[hdr->keyBytes];
525 	char *AfKey;
526 	unsigned int AFEKSize;
527 	uint64_t PBKDF2_temp;
528 	int r;
529 
530 	if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
531 		log_err(ctx,  _("Key slot %d active, purge first.\n"), keyIndex);
532 		return -EINVAL;
533 	}
534 
535 	if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) {
536 	        log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
537 			keyIndex);
538 	         return -EINVAL;
539 	}
540 
541 	log_dbg("Calculating data for key slot %d", keyIndex);
542 
543 	if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx)))
544 		return r;
545 
546 	/*
547 	 * Avoid floating point operation
548 	 * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
549 	 */
550 	PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
551 	PBKDF2_temp /= 1024;
552 	if (PBKDF2_temp > UINT32_MAX)
553 		PBKDF2_temp = UINT32_MAX;
554 	hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
555 							      LUKS_SLOT_ITERATIONS_MIN);
556 
557 	log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
558 
559 	r = getRandom(hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE);
560 	if(r < 0) return r;
561 
562 //	assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
563 
564 	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
565 			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
566 			hdr->keyblock[keyIndex].passwordIterations,
567 			derivedKey, hdr->keyBytes);
568 	if(r < 0) return r;
569 
570 	/*
571 	 * AF splitting, the masterkey stored in mk->key is splitted to AfMK
572 	 */
573 	AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
574 	AfKey = (char *)malloc(AFEKSize);
575 	if(AfKey == NULL) return -ENOMEM;
576 
577 	log_dbg("Using hash %s for AF in key slot %d, %d stripes",
578 		hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
579 	r = AF_split(mk->key,AfKey,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
580 	if(r < 0) goto out;
581 
582 	log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex,
583 		hdr->keyblock[keyIndex].keyMaterialOffset << 9, device);
584 	/* Encryption via dm */
585 	r = LUKS_encrypt_to_storage(AfKey,
586 				    AFEKSize,
587 				    hdr,
588 				    derivedKey,
589 				    hdr->keyBytes,
590 				    device,
591 				    hdr->keyblock[keyIndex].keyMaterialOffset,
592 				    ctx);
593 	if(r < 0) {
594 		if(!get_error())
595 			log_err(ctx, _("Failed to write to key storage.\n"));
596 		goto out;
597 	}
598 
599 	/* Mark the key as active in phdr */
600 	r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
601 	if(r < 0) goto out;
602 
603 	r = LUKS_write_phdr(device, hdr, ctx);
604 	if(r < 0) goto out;
605 
606 	r = 0;
607 out:
608 	free(AfKey);
609 	return r;
610 }
611 
612 /* Check whether a master key is invalid. */
613 int LUKS_verify_master_key(const struct luks_phdr *hdr,
614 			   const struct luks_masterkey *mk)
615 {
616 	char checkHashBuf[LUKS_DIGESTSIZE];
617 
618 	if (PBKDF2_HMAC(hdr->hashSpec, mk->key, mk->keyLength,
619 			hdr->mkDigestSalt, LUKS_SALTSIZE,
620 			hdr->mkDigestIterations, checkHashBuf,
621 			LUKS_DIGESTSIZE) < 0)
622 		return -EINVAL;
623 
624 	if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
625 		return -EPERM;
626 
627 	return 0;
628 }
629 
630 /* Try to open a particular key slot */
631 static int LUKS_open_key(const char *device,
632 		  unsigned int keyIndex,
633 		  const char *password,
634 		  size_t passwordLen,
635 		  struct luks_phdr *hdr,
636 		  struct luks_masterkey *mk,
637 		  struct crypt_device *ctx)
638 {
639 	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
640 	char derivedKey[hdr->keyBytes];
641 	char *AfKey;
642 	size_t AFEKSize;
643 	int r;
644 
645 	log_dbg("Trying to open key slot %d [%d].", keyIndex, (int)ki);
646 
647 	if (ki < CRYPT_SLOT_ACTIVE)
648 		return -ENOENT;
649 
650 	// assert((mk->keyLength % TWOFISH_BLOCKSIZE) == 0); FIXME
651 
652 	AFEKSize = hdr->keyblock[keyIndex].stripes*mk->keyLength;
653 	AfKey = (char *)malloc(AFEKSize);
654 	if(AfKey == NULL) return -ENOMEM;
655 
656 	r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen,
657 			hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE,
658 			hdr->keyblock[keyIndex].passwordIterations,
659 			derivedKey, hdr->keyBytes);
660 	if(r < 0) goto out;
661 
662 	log_dbg("Reading key slot %d area.", keyIndex);
663 	r = LUKS_decrypt_from_storage(AfKey,
664 				      AFEKSize,
665 				      hdr,
666 				      derivedKey,
667 				      hdr->keyBytes,
668 				      device,
669 				      hdr->keyblock[keyIndex].keyMaterialOffset,
670 				      ctx);
671 	if(r < 0) {
672 		log_err(ctx, _("Failed to read from key storage.\n"));
673 		goto out;
674 	}
675 
676 	r = AF_merge(AfKey,mk->key,mk->keyLength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
677 	if(r < 0) goto out;
678 
679 	r = LUKS_verify_master_key(hdr, mk);
680 	if (r >= 0)
681 		log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
682 out:
683 	free(AfKey);
684 	return r;
685 }
686 
687 int LUKS_open_key_with_hdr(const char *device,
688 			   int keyIndex,
689 			   const char *password,
690 			   size_t passwordLen,
691 			   struct luks_phdr *hdr,
692 			   struct luks_masterkey **mk,
693 			   struct crypt_device *ctx)
694 {
695 	unsigned int i;
696 	int r;
697 
698 	*mk = LUKS_alloc_masterkey(hdr->keyBytes, NULL);
699 
700 	if (keyIndex >= 0)
701 		return LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *mk, ctx);
702 
703 	for(i = 0; i < LUKS_NUMKEYS; i++) {
704 		r = LUKS_open_key(device, i, password, passwordLen, hdr, *mk, ctx);
705 		if(r == 0)
706 			return i;
707 
708 		/* Do not retry for errors that are no -EPERM or -ENOENT,
709 		   former meaning password wrong, latter key slot inactive */
710 		if ((r != -EPERM) && (r != -ENOENT))
711 			return r;
712 	}
713 	/* Warning, early returns above */
714 	log_err(ctx, _("No key available with this passphrase.\n"));
715 	return -EPERM;
716 }
717 
718 /*
719  * Wipe patterns according to Gutmann's Paper
720  */
721 
722 static void wipeSpecial(char *buffer, size_t buffer_size, unsigned int turn)
723 {
724         unsigned int i;
725 
726         unsigned char write_modes[][3] = {
727                 {"\x55\x55\x55"}, {"\xaa\xaa\xaa"}, {"\x92\x49\x24"},
728                 {"\x49\x24\x92"}, {"\x24\x92\x49"}, {"\x00\x00\x00"},
729                 {"\x11\x11\x11"}, {"\x22\x22\x22"}, {"\x33\x33\x33"},
730                 {"\x44\x44\x44"}, {"\x55\x55\x55"}, {"\x66\x66\x66"},
731                 {"\x77\x77\x77"}, {"\x88\x88\x88"}, {"\x99\x99\x99"},
732                 {"\xaa\xaa\xaa"}, {"\xbb\xbb\xbb"}, {"\xcc\xcc\xcc"},
733                 {"\xdd\xdd\xdd"}, {"\xee\xee\xee"}, {"\xff\xff\xff"},
734                 {"\x92\x49\x24"}, {"\x49\x24\x92"}, {"\x24\x92\x49"},
735                 {"\x6d\xb6\xdb"}, {"\xb6\xdb\x6d"}, {"\xdb\x6d\xb6"}
736         };
737 
738         for(i = 0; i < buffer_size / 3; ++i) {
739                 memcpy(buffer, write_modes[turn], 3);
740                 buffer += 3;
741         }
742 }
743 
744 static int wipe(const char *device, unsigned int from, unsigned int to)
745 {
746 	int devfd;
747 	char *buffer;
748 	unsigned int i;
749 	unsigned int bufLen = (to - from) * SECTOR_SIZE;
750 	int r = 0;
751 
752 	devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
753 	if(devfd == -1)
754 		return -EINVAL;
755 
756 	buffer = (char *) malloc(bufLen);
757 	if(!buffer) return -ENOMEM;
758 
759 	for(i = 0; i < 39; ++i) {
760 		if     (i >=  0 && i <  5) getRandom(buffer, bufLen);
761 		else if(i >=  5 && i < 32) wipeSpecial(buffer, bufLen, i - 5);
762 		else if(i >= 32 && i < 38) getRandom(buffer, bufLen);
763 		else if(i >= 38 && i < 39) memset(buffer, 0xFF, bufLen);
764 
765 		if(write_lseek_blockwise(devfd, buffer, bufLen, from * SECTOR_SIZE) < 0) {
766 			r = -EIO;
767 			break;
768 		}
769 	}
770 
771 	free(buffer);
772 	close(devfd);
773 
774 	return r;
775 }
776 
777 int LUKS_del_key(const char *device,
778 		 unsigned int keyIndex,
779 		 struct luks_phdr *hdr,
780 		 struct crypt_device *ctx)
781 {
782 	unsigned int startOffset, endOffset, stripesLen;
783 	int r;
784 
785 	r = LUKS_read_phdr(device, hdr, 1, ctx);
786 	if (r)
787 		return r;
788 
789 	r = LUKS_keyslot_set(hdr, keyIndex, 0);
790 	if (r) {
791 		log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
792 			keyIndex, LUKS_NUMKEYS - 1);
793 		return r;
794 	}
795 
796 	/* secure deletion of key material */
797 	startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
798 	stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes;
799 	endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE);
800 
801 	r = wipe(device, startOffset, endOffset);
802 	if (r) {
803 		log_err(ctx, _("Cannot wipe device %s.\n"), device);
804 		return r;
805 	}
806 
807 	r = LUKS_write_phdr(device, hdr, ctx);
808 
809 	return r;
810 }
811 
812 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
813 {
814 	int i;
815 
816 	if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
817 		return CRYPT_SLOT_INVALID;
818 
819 	if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
820 		return CRYPT_SLOT_INACTIVE;
821 
822 	if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
823 		return CRYPT_SLOT_INVALID;
824 
825 	for(i = 0; i < LUKS_NUMKEYS; i++)
826 		if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
827 			return CRYPT_SLOT_ACTIVE;
828 
829 	return CRYPT_SLOT_ACTIVE_LAST;
830 }
831 
832 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
833 {
834 	int i;
835 
836 	for (i = 0; i < LUKS_NUMKEYS; i++)
837 		if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
838 			break;
839 
840 	if (i == LUKS_NUMKEYS)
841 		return -EINVAL;
842 
843 	return i;
844 }
845 
846 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
847 {
848 	int i, num = 0;
849 
850 	for (i = 0; i < LUKS_NUMKEYS; i++)
851 		if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
852 			num++;
853 
854 	return num;
855 }
856 
857 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
858 {
859 	crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
860 
861 	if (ki == CRYPT_SLOT_INVALID)
862 		return -EINVAL;
863 
864 	hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
865 	log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
866 	return 0;
867 }
868