luks: Avoid crash when image does not contain a LUKS header
[nbdkit.git] / filters / luks / luks-encryption.c
blob6f33e76ed86c4793c54e93b597c5c057ec2f9272
1 /* nbdkit
2 * Copyright (C) 2018-2022 Red Hat Inc.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * * Neither the name of Red Hat nor the names of its contributors may be
16 * used to endorse or promote products derived from this software without
17 * specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
26 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
33 #include <config.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <stdint.h>
38 #include <inttypes.h>
39 #include <string.h>
40 #include <limits.h>
41 #include <assert.h>
43 #include <gnutls/crypto.h>
45 #include <nbdkit-filter.h>
47 #include "luks-encryption.h"
49 #include "byte-swapping.h"
50 #include "cleanup.h"
51 #include "isaligned.h"
52 #include "rounding.h"
54 /* LUKSv1 constants. */
55 #define LUKS_MAGIC { 'L', 'U', 'K', 'S', 0xBA, 0xBE }
56 #define LUKS_MAGIC_LEN 6
57 #define LUKS_DIGESTSIZE 20
58 #define LUKS_SALTSIZE 32
59 #define LUKS_NUMKEYS 8
60 #define LUKS_KEY_DISABLED 0x0000DEAD
61 #define LUKS_KEY_ENABLED 0x00AC71F3
62 #define LUKS_STRIPES 4000
63 #define LUKS_ALIGN_KEYSLOTS 4096
65 /* Key slot. */
66 struct luks_keyslot {
67 uint32_t active; /* LUKS_KEY_DISABLED|LUKS_KEY_ENABLED */
68 uint32_t password_iterations;
69 char password_salt[LUKS_SALTSIZE];
70 uint32_t key_material_offset;
71 uint32_t stripes;
72 } __attribute__((__packed__));
74 /* LUKS superblock. */
75 struct luks_phdr {
76 char magic[LUKS_MAGIC_LEN]; /* LUKS_MAGIC */
77 uint16_t version; /* Only 1 is supported. */
78 char cipher_name[32];
79 char cipher_mode[32];
80 char hash_spec[32];
81 uint32_t payload_offset;
82 uint32_t master_key_len;
83 uint8_t master_key_digest[LUKS_DIGESTSIZE];
84 uint8_t master_key_salt[LUKS_SALTSIZE];
85 uint32_t master_key_digest_iterations;
86 uint8_t uuid[40];
88 struct luks_keyslot keyslot[LUKS_NUMKEYS]; /* Key slots. */
89 } __attribute__((__packed__));
91 /* Block cipher mode of operation.
92 * https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
94 enum cipher_mode {
95 CIPHER_MODE_ECB, CIPHER_MODE_CBC, CIPHER_MODE_XTS, CIPHER_MODE_CTR,
98 static enum cipher_mode
99 lookup_cipher_mode (const char *str)
101 if (strcmp (str, "ecb") == 0)
102 return CIPHER_MODE_ECB;
103 if (strcmp (str, "cbc") == 0)
104 return CIPHER_MODE_CBC;
105 if (strcmp (str, "xts") == 0)
106 return CIPHER_MODE_XTS;
107 if (strcmp (str, "ctr") == 0)
108 return CIPHER_MODE_CTR;
109 nbdkit_error ("unknown cipher mode: %s "
110 "(expecting \"ecb\", \"cbc\", \"xts\" or \"ctr\")", str);
111 return -1;
114 static const char *
115 cipher_mode_to_string (enum cipher_mode v)
117 switch (v) {
118 case CIPHER_MODE_ECB: return "ecb";
119 case CIPHER_MODE_CBC: return "cbc";
120 case CIPHER_MODE_XTS: return "xts";
121 case CIPHER_MODE_CTR: return "ctr";
122 default: abort ();
126 /* Methods used by LUKS to generate initial vectors.
128 * ESSIV is a bit more complicated to implement. It is supported by
129 * qemu but not by us.
131 enum ivgen {
132 IVGEN_PLAIN, IVGEN_PLAIN64, /* IVGEN_ESSIV, */
135 static enum ivgen
136 lookup_ivgen (const char *str)
138 if (strcmp (str, "plain") == 0)
139 return IVGEN_PLAIN;
140 if (strcmp (str, "plain64") == 0)
141 return IVGEN_PLAIN64;
143 if (strcmp (str, "essiv") == 0)
144 return IVGEN_ESSIV;
146 nbdkit_error ("unknown IV generation algorithm: %s "
147 "(expecting \"plain\", \"plain64\" etc)", str);
148 return -1;
151 static const char *
152 ivgen_to_string (enum ivgen v)
154 switch (v) {
155 case IVGEN_PLAIN: return "plain";
156 case IVGEN_PLAIN64: return "plain64";
157 /*case IVGEN_ESSIV: return "essiv";*/
158 default: abort ();
162 static void
163 calculate_iv (enum ivgen v, uint8_t *iv, size_t ivlen, uint64_t sector)
165 size_t prefixlen;
166 uint32_t sector32;
168 switch (v) {
169 case IVGEN_PLAIN:
170 prefixlen = 4; /* 32 bits */
171 if (prefixlen > ivlen)
172 prefixlen = ivlen;
173 sector32 = (uint32_t) sector; /* truncate to only lower bits */
174 sector32 = htole32 (sector32);
175 memcpy (iv, &sector32, prefixlen);
176 memset (iv + prefixlen, 0, ivlen - prefixlen);
177 break;
179 case IVGEN_PLAIN64:
180 prefixlen = 8; /* 64 bits */
181 if (prefixlen > ivlen)
182 prefixlen = ivlen;
183 sector = htole64 (sector);
184 memcpy (iv, &sector, prefixlen);
185 memset (iv + prefixlen, 0, ivlen - prefixlen);
186 break;
188 /*case IVGEN_ESSIV:*/
189 default: abort ();
193 /* Cipher algorithm.
195 * qemu in theory supports many more, but with the GnuTLS backend only
196 * AES is supported. The kernel seems to only support AES for LUKSv1.
198 enum cipher_alg {
199 CIPHER_ALG_AES_128, CIPHER_ALG_AES_192, CIPHER_ALG_AES_256,
202 static enum cipher_alg
203 lookup_cipher_alg (const char *str, enum cipher_mode mode, int key_bytes)
205 if (mode == CIPHER_MODE_XTS)
206 key_bytes /= 2;
208 if (strcmp (str, "aes") == 0) {
209 if (key_bytes == 16)
210 return CIPHER_ALG_AES_128;
211 if (key_bytes == 24)
212 return CIPHER_ALG_AES_192;
213 if (key_bytes == 32)
214 return CIPHER_ALG_AES_256;
216 nbdkit_error ("unknown cipher algorithm: %s (expecting \"aes\", etc)", str);
217 return -1;
220 static const char *
221 cipher_alg_to_string (enum cipher_alg v)
223 switch (v) {
224 case CIPHER_ALG_AES_128: return "aes-128";
225 case CIPHER_ALG_AES_192: return "aes-192";
226 case CIPHER_ALG_AES_256: return "aes-256";
227 default: abort ();
231 #if 0
232 static int
233 cipher_alg_key_bytes (enum cipher_alg v)
235 switch (v) {
236 case CIPHER_ALG_AES_128: return 16;
237 case CIPHER_ALG_AES_192: return 24;
238 case CIPHER_ALG_AES_256: return 32;
239 default: abort ();
242 #endif
244 static int
245 cipher_alg_iv_len (enum cipher_alg v, enum cipher_mode mode)
247 if (CIPHER_MODE_ECB)
248 return 0; /* Don't need an IV in this mode. */
250 switch (v) {
251 case CIPHER_ALG_AES_128:
252 case CIPHER_ALG_AES_192:
253 case CIPHER_ALG_AES_256:
254 return 16;
255 default: abort ();
259 /* Hash, eg.MD5, SHA1 etc.
261 * We reuse the GnuTLS digest algorithm enum here since it supports at
262 * least all the ones that LUKSv1 does.
264 static gnutls_digest_algorithm_t
265 lookup_hash (const char *str)
267 if (strcmp (str, "md5") == 0)
268 return GNUTLS_DIG_MD5;
269 if (strcmp (str, "sha1") == 0)
270 return GNUTLS_DIG_SHA1;
271 if (strcmp (str, "sha224") == 0)
272 return GNUTLS_DIG_SHA224;
273 if (strcmp (str, "sha256") == 0)
274 return GNUTLS_DIG_SHA256;
275 if (strcmp (str, "sha384") == 0)
276 return GNUTLS_DIG_SHA384;
277 if (strcmp (str, "sha512") == 0)
278 return GNUTLS_DIG_SHA512;
279 if (strcmp (str, "ripemd160") == 0)
280 return GNUTLS_DIG_RMD160;
281 nbdkit_error ("unknown hash algorithm: %s "
282 "(expecting \"md5\", \"sha1\", \"sha224\", etc)", str);
283 return -1;
286 static const char *
287 hash_to_string (gnutls_digest_algorithm_t v)
289 switch (v) {
290 case GNUTLS_DIG_UNKNOWN: return "unknown";
291 case GNUTLS_DIG_MD5: return "md5";
292 case GNUTLS_DIG_SHA1: return "sha1";
293 case GNUTLS_DIG_SHA224: return "sha224";
294 case GNUTLS_DIG_SHA256: return "sha256";
295 case GNUTLS_DIG_SHA384: return "sha384";
296 case GNUTLS_DIG_SHA512: return "sha512";
297 case GNUTLS_DIG_RMD160: return "ripemd160";
298 default: abort ();
302 #if 0
303 /* See qemu & dm-crypt implementations for an explanation of what's
304 * going on here.
306 enum cipher_alg
307 lookup_essiv_cipher (enum cipher_alg cipher_alg,
308 gnutls_digest_algorithm_t ivgen_hash_alg)
310 int digest_bytes = gnutls_hash_get_len (ivgen_hash_alg);
311 int key_bytes = cipher_alg_key_bytes (cipher_alg);
313 if (digest_bytes == key_bytes)
314 return cipher_alg;
316 switch (cipher_alg) {
317 case CIPHER_ALG_AES_128:
318 case CIPHER_ALG_AES_192:
319 case CIPHER_ALG_AES_256:
320 if (digest_bytes == 16) return CIPHER_ALG_AES_128;
321 if (digest_bytes == 24) return CIPHER_ALG_AES_192;
322 if (digest_bytes == 32) return CIPHER_ALG_AES_256;
323 nbdkit_error ("no %s cipher available with key size %d",
324 "AES", digest_bytes);
325 return -1;
326 default:
327 nbdkit_error ("ESSIV does not support cipher %s",
328 cipher_alg_to_string (cipher_alg));
329 return -1;
332 #endif
334 /* Per-connection data. */
335 struct luks_data {
336 /* LUKS header, if necessary byte-swapped into host order. */
337 struct luks_phdr phdr;
339 /* Decoded algorithm etc. */
340 enum cipher_alg cipher_alg;
341 enum cipher_mode cipher_mode;
342 gnutls_digest_algorithm_t hash_alg;
343 enum ivgen ivgen_alg;
344 gnutls_digest_algorithm_t ivgen_hash_alg;
345 enum cipher_alg ivgen_cipher_alg;
347 /* GnuTLS algorithm. */
348 gnutls_cipher_algorithm_t gnutls_cipher;
350 /* If we managed to decrypt one of the keyslots using the passphrase
351 * then this contains the master key, otherwise NULL.
353 uint8_t *masterkey;
356 /* Parse the header fields containing cipher algorithm, mode, etc. */
357 static int
358 parse_cipher_strings (struct luks_data *h)
360 char cipher_name[33], cipher_mode[33], hash_spec[33];
361 char *ivgen, *ivhash;
363 /* Copy the header fields locally and ensure they are \0 terminated. */
364 memcpy (cipher_name, h->phdr.cipher_name, 32);
365 cipher_name[32] = 0;
366 memcpy (cipher_mode, h->phdr.cipher_mode, 32);
367 cipher_mode[32] = 0;
368 memcpy (hash_spec, h->phdr.hash_spec, 32);
369 hash_spec[32] = 0;
371 nbdkit_debug ("LUKS v%" PRIu16 " cipher: %s mode: %s hash: %s "
372 "master key: %" PRIu32 " bits",
373 h->phdr.version, cipher_name, cipher_mode, hash_spec,
374 h->phdr.master_key_len * 8);
376 /* The cipher_mode header has the form: "ciphermode-ivgen[:ivhash]"
377 * QEmu writes: "xts-plain64"
379 ivgen = strchr (cipher_mode, '-');
380 if (!ivgen) {
381 nbdkit_error ("incorrect cipher_mode header, "
382 "expecting mode-ivgenerator but got \"%s\"", cipher_mode);
383 return -1;
385 *ivgen = '\0';
386 ivgen++;
388 ivhash = strchr (ivgen, ':');
389 if (!ivhash)
390 h->ivgen_hash_alg = GNUTLS_DIG_UNKNOWN;
391 else {
392 *ivhash = '\0';
393 ivhash++;
395 h->ivgen_hash_alg = lookup_hash (ivhash);
396 if (h->ivgen_hash_alg == -1)
397 return -1;
400 h->cipher_mode = lookup_cipher_mode (cipher_mode);
401 if (h->cipher_mode == -1)
402 return -1;
404 h->cipher_alg = lookup_cipher_alg (cipher_name, h->cipher_mode,
405 h->phdr.master_key_len);
406 if (h->cipher_alg == -1)
407 return -1;
409 h->hash_alg = lookup_hash (hash_spec);
410 if (h->hash_alg == -1)
411 return -1;
413 h->ivgen_alg = lookup_ivgen (ivgen);
414 if (h->ivgen_alg == -1)
415 return -1;
417 #if 0
418 if (h->ivgen_alg == IVGEN_ESSIV) {
419 if (!ivhash) {
420 nbdkit_error ("incorrect IV generator hash specification");
421 return -1;
423 h->ivgen_cipher_alg = lookup_essiv_cipher (h->cipher_alg,
424 h->ivgen_hash_alg);
425 if (h->ivgen_cipher_alg == -1)
426 return -1;
428 else
429 #endif
430 h->ivgen_cipher_alg = h->cipher_alg;
432 nbdkit_debug ("LUKS parsed ciphers: %s %s %s %s %s %s",
433 cipher_alg_to_string (h->cipher_alg),
434 cipher_mode_to_string (h->cipher_mode),
435 hash_to_string (h->hash_alg),
436 ivgen_to_string (h->ivgen_alg),
437 hash_to_string (h->ivgen_hash_alg),
438 cipher_alg_to_string (h->ivgen_cipher_alg));
440 /* GnuTLS combines cipher and block mode into a single value. Not
441 * all possible combinations are available in GnuTLS. See:
442 * https://www.gnutls.org/manual/html_node/Supported-ciphersuites.html
444 h->gnutls_cipher = GNUTLS_CIPHER_NULL;
445 switch (h->cipher_mode) {
446 case CIPHER_MODE_XTS:
447 switch (h->cipher_alg) {
448 case CIPHER_ALG_AES_128:
449 h->gnutls_cipher = GNUTLS_CIPHER_AES_128_XTS;
450 break;
451 case CIPHER_ALG_AES_256:
452 h->gnutls_cipher = GNUTLS_CIPHER_AES_256_XTS;
453 break;
454 default: break;
456 break;
457 case CIPHER_MODE_CBC:
458 switch (h->cipher_alg) {
459 case CIPHER_ALG_AES_128:
460 h->gnutls_cipher = GNUTLS_CIPHER_AES_128_CBC;
461 break;
462 case CIPHER_ALG_AES_192:
463 h->gnutls_cipher = GNUTLS_CIPHER_AES_192_CBC;
464 break;
465 case CIPHER_ALG_AES_256:
466 h->gnutls_cipher = GNUTLS_CIPHER_AES_256_CBC;
467 break;
468 default: break;
470 default: break;
472 if (h->gnutls_cipher == GNUTLS_CIPHER_NULL) {
473 nbdkit_error ("cipher algorithm %s in mode %s is not supported by GnuTLS",
474 cipher_alg_to_string (h->cipher_alg),
475 cipher_mode_to_string (h->cipher_mode));
476 return -1;
479 return 0;
482 /* Anti-Forensic merge operation. */
483 static void
484 xor (const uint8_t *in1, const uint8_t *in2, uint8_t *out, size_t len)
486 size_t i;
488 for (i = 0; i < len; ++i)
489 out[i] = in1[i] ^ in2[i];
492 static int
493 af_hash (gnutls_digest_algorithm_t hash_alg, uint8_t *block, size_t len)
495 size_t digest_bytes = gnutls_hash_get_len (hash_alg);
496 size_t nr_blocks, last_block_len;
497 size_t i;
498 int r;
499 gnutls_hash_hd_t hash;
500 CLEANUP_FREE uint8_t *temp;
502 temp = malloc (digest_bytes);
503 if (!temp) {
504 nbdkit_error ("malloc: %m");
505 return -1;
508 nr_blocks = len / digest_bytes;
509 last_block_len = len % digest_bytes;
510 if (last_block_len != 0)
511 nr_blocks++;
512 else
513 last_block_len = digest_bytes;
515 for (i = 0; i < nr_blocks; ++i) {
516 const uint32_t iv = htobe32 (i);
517 const size_t blen = i < nr_blocks - 1 ? digest_bytes : last_block_len;
519 /* Hash iv + i'th block into temp. */
520 r = gnutls_hash_init (&hash, hash_alg);
521 if (r != 0) {
522 nbdkit_error ("gnutls_hash_init: %s", gnutls_strerror (r));
523 return -1;
525 gnutls_hash (hash, &iv, sizeof iv);
526 gnutls_hash (hash, &block[i*digest_bytes], blen);
527 gnutls_hash_deinit (hash, temp);
529 memcpy (&block[i*digest_bytes], temp, blen);
532 return 0;
535 static int
536 afmerge (gnutls_digest_algorithm_t hash_alg, uint32_t stripes,
537 const uint8_t *in, uint8_t *out, size_t outlen)
539 CLEANUP_FREE uint8_t *block = calloc (1, outlen);
540 size_t i;
542 /* NB: input size is stripes * master_key_len where
543 * master_key_len == outlen
545 for (i = 0; i < stripes-1; ++i) {
546 xor (&in[i*outlen], block, block, outlen);
547 if (af_hash (hash_alg, block, outlen) == -1)
548 return -1;
550 xor (&in[i*outlen], block, out, outlen);
551 return 0;
554 /* Length of key material in key slot i (sectors).
556 * This is basically copied from qemu because the spec description is
557 * unintelligible and apparently doesn't match reality.
559 static uint64_t
560 key_material_length_in_sectors (struct luks_data *h, size_t i)
562 uint64_t len, r;
564 len = (uint64_t) h->phdr.master_key_len * h->phdr.keyslot[i].stripes;
565 r = DIV_ROUND_UP (len, LUKS_SECTOR_SIZE);
566 r = ROUND_UP (r, LUKS_ALIGN_KEYSLOTS / LUKS_SECTOR_SIZE);
567 return r;
570 /* Try the passphrase in key slot i. If this returns true then the
571 * passphrase was able to decrypt the master key, and the master key
572 * has been stored in h->masterkey.
574 static int
575 try_passphrase_in_keyslot (nbdkit_next *next, struct luks_data *h,
576 size_t i, const char *passphrase)
578 /* I believe this is supposed to be safe, looking at the GnuTLS
579 * header file.
581 const gnutls_mac_algorithm_t mac = (gnutls_mac_algorithm_t) h->hash_alg;
582 struct luks_keyslot *ks = &h->phdr.keyslot[i];
583 size_t split_key_len;
584 CLEANUP_FREE uint8_t *split_key = NULL;
585 CLEANUP_FREE uint8_t *masterkey = NULL;
586 const gnutls_datum_t key =
587 { (unsigned char *) passphrase, strlen (passphrase) };
588 const gnutls_datum_t salt =
589 { (unsigned char *) ks->password_salt, LUKS_SALTSIZE };
590 const gnutls_datum_t msalt =
591 { (unsigned char *) h->phdr.master_key_salt, LUKS_SALTSIZE };
592 gnutls_datum_t mkey;
593 gnutls_cipher_hd_t cipher;
594 int r, err = 0;
595 uint64_t start;
596 uint8_t key_digest[LUKS_DIGESTSIZE];
598 if (ks->active != LUKS_KEY_ENABLED)
599 return 0;
601 split_key_len = h->phdr.master_key_len * ks->stripes;
602 split_key = malloc (split_key_len);
603 if (split_key == NULL) {
604 nbdkit_error ("malloc: %m");
605 return -1;
607 masterkey = malloc (h->phdr.master_key_len);
608 if (masterkey == NULL) {
609 nbdkit_error ("malloc: %m");
610 return -1;
613 /* Hash the passphrase to make a possible masterkey. */
614 r = gnutls_pbkdf2 (mac, &key, &salt, ks->password_iterations,
615 masterkey, h->phdr.master_key_len);
616 if (r != 0) {
617 nbdkit_error ("gnutls_pbkdf2: %s", gnutls_strerror (r));
618 return -1;
621 /* Read master key material from plugin. */
622 start = (uint64_t) ks->key_material_offset * LUKS_SECTOR_SIZE;
623 if (next->pread (next, split_key, split_key_len, start, 0, &err) == -1) {
624 errno = err;
625 return -1;
628 /* Decrypt the (still AFsplit) master key material. */
629 mkey.data = (unsigned char *) masterkey;
630 mkey.size = h->phdr.master_key_len;
631 r = gnutls_cipher_init (&cipher, h->gnutls_cipher, &mkey, NULL);
632 if (r != 0) {
633 nbdkit_error ("gnutls_cipher_init: %s", gnutls_strerror (r));
634 return -1;
637 r = do_decrypt (h, cipher, 0, split_key, split_key_len / LUKS_SECTOR_SIZE);
638 gnutls_cipher_deinit (cipher);
639 if (r == -1)
640 return -1;
642 /* Decode AFsplit key to a possible masterkey. */
643 if (afmerge (h->hash_alg, ks->stripes, split_key,
644 masterkey, h->phdr.master_key_len) == -1)
645 return -1;
647 /* Check if the masterkey is correct by comparing hash of the
648 * masterkey with LUKS header.
650 r = gnutls_pbkdf2 (mac, &mkey, &msalt,
651 h->phdr.master_key_digest_iterations,
652 key_digest, LUKS_DIGESTSIZE);
653 if (r != 0) {
654 nbdkit_error ("gnutls_pbkdf2: %s", gnutls_strerror (r));
655 return -1;
658 if (memcmp (key_digest, h->phdr.master_key_digest, LUKS_DIGESTSIZE) == 0) {
659 /* The passphrase is correct so save the master key in the handle. */
660 h->masterkey = malloc (h->phdr.master_key_len);
661 if (h->masterkey == NULL) {
662 nbdkit_error ("malloc: %m");
663 return -1;
665 memcpy (h->masterkey, masterkey, h->phdr.master_key_len);
666 return 1;
669 return 0;
672 struct luks_data *
673 load_header (nbdkit_next *next, const char *passphrase)
675 static const char expected_magic[] = LUKS_MAGIC;
676 struct luks_data *h;
677 int64_t size;
678 int err = 0, r;
679 size_t i;
680 struct luks_keyslot *ks;
681 char uuid[41];
683 h = calloc (1, sizeof *h);
684 if (h == NULL) {
685 nbdkit_error ("calloc: %m");
686 return NULL;
689 /* Check the struct size matches the documentation. */
690 assert (sizeof (struct luks_phdr) == 592);
692 /* Check this is a LUKSv1 disk. */
693 size = next->get_size (next);
694 if (size == -1) {
695 free (h);
696 return NULL;
698 if (size < 16384) {
699 nbdkit_error ("disk is too small to be LUKS-encrypted");
700 free (h);
701 return NULL;
704 /* Read the phdr. */
705 if (next->pread (next, &h->phdr, sizeof h->phdr, 0, 0, &err) == -1) {
706 free (h);
707 errno = err;
708 return NULL;
711 if (memcmp (h->phdr.magic, expected_magic, LUKS_MAGIC_LEN) != 0) {
712 nbdkit_error ("this disk does not contain a LUKS header");
713 free (h);
714 return NULL;
716 h->phdr.version = be16toh (h->phdr.version);
717 if (h->phdr.version != 1) {
718 nbdkit_error ("this disk contains a LUKS version %" PRIu16 " header, "
719 "but this filter only supports LUKSv1",
720 h->phdr.version);
721 free (h);
722 return NULL;
725 /* Byte-swap the rest of the header. */
726 h->phdr.payload_offset = be32toh (h->phdr.payload_offset);
727 h->phdr.master_key_len = be32toh (h->phdr.master_key_len);
728 h->phdr.master_key_digest_iterations =
729 be32toh (h->phdr.master_key_digest_iterations);
731 for (i = 0; i < LUKS_NUMKEYS; ++i) {
732 ks = &h->phdr.keyslot[i];
733 ks->active = be32toh (ks->active);
734 ks->password_iterations = be32toh (ks->password_iterations);
735 ks->key_material_offset = be32toh (ks->key_material_offset);
736 ks->stripes = be32toh (ks->stripes);
739 /* Sanity check some fields. */
740 if (h->phdr.payload_offset >= size / LUKS_SECTOR_SIZE) {
741 nbdkit_error ("bad LUKSv1 header: payload offset points beyond "
742 "the end of the disk");
743 free (h);
744 return NULL;
747 if (h->phdr.master_key_digest_iterations == 0) {
748 nbdkit_error ("bad LUKSv1 header: master key iterations is 0");
749 free (h);
750 return NULL;
753 /* We derive several allocations from master_key_len so make sure
754 * it's not insane.
756 if (h->phdr.master_key_len > 1024) {
757 nbdkit_error ("bad LUKSv1 header: master key is too long");
758 free (h);
759 return NULL;
762 for (i = 0; i < LUKS_NUMKEYS; ++i) {
763 uint64_t start, len;
765 ks = &h->phdr.keyslot[i];
766 switch (ks->active) {
767 case LUKS_KEY_ENABLED:
768 if (!ks->stripes) {
769 nbdkit_error ("bad LUKSv1 header: key slot %zu is corrupted", i);
770 free (h);
771 return NULL;
773 if (ks->stripes >= 10000) {
774 nbdkit_error ("bad LUKSv1 header: key slot %zu stripes too large", i);
775 free (h);
776 return NULL;
778 if (ks->password_iterations == 0) {
779 nbdkit_error ("bad LUKSv1 header: key slot %zu iterations is 0", i);
780 free (h);
781 return NULL;
783 start = ks->key_material_offset;
784 len = key_material_length_in_sectors (h, i);
785 if (len > 4096) /* bound it at something reasonable */ {
786 nbdkit_error ("bad LUKSv1 header: key slot %zu key material length "
787 "is too large", i);
788 free (h);
789 return NULL;
791 if (start * LUKS_SECTOR_SIZE >= size ||
792 (start + len) * LUKS_SECTOR_SIZE >= size) {
793 nbdkit_error ("bad LUKSv1 header: key slot %zu key material offset "
794 "points beyond the end of the disk", i);
795 free (h);
796 return NULL;
798 /*FALLTHROUGH*/
799 case LUKS_KEY_DISABLED:
800 break;
802 default:
803 nbdkit_error ("bad LUKSv1 header: key slot %zu has "
804 "an invalid active flag", i);
805 return NULL;
809 /* Decode the ciphers. */
810 if (parse_cipher_strings (h) == -1) {
811 free (h);
812 return NULL;
815 /* Dump some information about the header. */
816 memcpy (uuid, h->phdr.uuid, 40);
817 uuid[40] = 0;
818 nbdkit_debug ("LUKS UUID: %s", uuid);
820 for (i = 0; i < LUKS_NUMKEYS; ++i) {
821 uint64_t start, len;
823 ks = &h->phdr.keyslot[i];
824 if (ks->active == LUKS_KEY_ENABLED) {
825 start = ks->key_material_offset;
826 len = key_material_length_in_sectors (h, i);
827 nbdkit_debug ("LUKS key slot %zu: key material in sectors %" PRIu64
828 "..%" PRIu64,
829 i, start, start+len-1);
833 /* Now try to unlock the master key. */
834 for (i = 0; i < LUKS_NUMKEYS; ++i) {
835 r = try_passphrase_in_keyslot (next, h, i, passphrase);
836 if (r == -1) {
837 free (h);
838 return NULL;
840 if (r > 0)
841 goto unlocked;
843 nbdkit_error ("LUKS passphrase is not correct, "
844 "no key slot could be unlocked");
845 free (h);
846 return NULL;
848 unlocked:
849 assert (h->masterkey != NULL);
850 nbdkit_debug ("LUKS unlocked block device with passphrase");
852 return h;
855 /* Free fields in the handle that might have been set by load_header. */
856 void
857 free_luks_data (struct luks_data *h)
859 if (h) {
860 if (h->masterkey) {
861 memset (h->masterkey, 0, h->phdr.master_key_len);
862 free (h->masterkey);
864 free (h);
868 uint64_t
869 get_payload_offset (struct luks_data *h)
871 return h->phdr.payload_offset;
874 gnutls_cipher_hd_t
875 create_cipher (struct luks_data *h)
877 gnutls_datum_t mkey;
878 gnutls_cipher_hd_t cipher;
879 int r;
881 assert (h->masterkey != NULL);
883 mkey.data = (unsigned char *) h->masterkey;
884 mkey.size = h->phdr.master_key_len;
885 r = gnutls_cipher_init (&cipher, h->gnutls_cipher, &mkey, NULL);
886 if (r != 0) {
887 nbdkit_error ("gnutls_cipher_init: %s", gnutls_strerror (r));
888 return NULL;
890 return cipher;
893 /* Perform decryption of a block of data in memory. */
895 do_decrypt (struct luks_data *h, gnutls_cipher_hd_t cipher,
896 uint64_t sector, uint8_t *buf, size_t nr_sectors)
898 int r;
899 const size_t ivlen = cipher_alg_iv_len (h->cipher_alg, h->cipher_mode);
900 CLEANUP_FREE uint8_t *iv;
902 iv = malloc (ivlen);
903 if (!iv) {
904 nbdkit_error ("malloc: %m");
905 return -1;
908 while (nr_sectors) {
909 calculate_iv (h->ivgen_alg, iv, ivlen, sector);
910 gnutls_cipher_set_iv (cipher, iv, ivlen);
911 r = gnutls_cipher_decrypt2 (cipher,
912 buf, LUKS_SECTOR_SIZE, /* ciphertext */
913 buf, LUKS_SECTOR_SIZE /* plaintext */);
914 if (r != 0) {
915 nbdkit_error ("gnutls_cipher_decrypt2: %s", gnutls_strerror (r));
916 return -1;
919 buf += LUKS_SECTOR_SIZE;
920 nr_sectors--;
921 sector++;
924 return 0;
927 /* Perform encryption of a block of data in memory. */
929 do_encrypt (struct luks_data *h, gnutls_cipher_hd_t cipher,
930 uint64_t sector, uint8_t *buf, size_t nr_sectors)
932 int r;
933 const size_t ivlen = cipher_alg_iv_len (h->cipher_alg, h->cipher_mode);
934 CLEANUP_FREE uint8_t *iv;
936 iv = malloc (ivlen);
937 if (!iv) {
938 nbdkit_error ("malloc: %m");
939 return -1;
942 while (nr_sectors) {
943 calculate_iv (h->ivgen_alg, iv, ivlen, sector);
944 gnutls_cipher_set_iv (cipher, iv, ivlen);
945 r = gnutls_cipher_encrypt2 (cipher,
946 buf, LUKS_SECTOR_SIZE, /* plaintext */
947 buf, LUKS_SECTOR_SIZE /* ciphertext */);
948 if (r != 0) {
949 nbdkit_error ("gnutls_cipher_decrypt2: %s", gnutls_strerror (r));
950 return -1;
953 buf += LUKS_SECTOR_SIZE;
954 nr_sectors--;
955 sector++;
958 return 0;