]> git.proxmox.com Git - mirror_qemu.git/blame - crypto/block-luks.c
qcrypto-luks: simplify the math used for keyslot locations
[mirror_qemu.git] / crypto / block-luks.c
CommitLineData
3e308f20
DB
1/*
2 * QEMU Crypto block device encryption LUKS format
3 *
4 * Copyright (c) 2015-2016 Red Hat, Inc.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
b7cbb874 9 * version 2.1 of the License, or (at your option) any later version.
3e308f20
DB
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21#include "qemu/osdep.h"
da34e65c 22#include "qapi/error.h"
58369e22 23#include "qemu/bswap.h"
3e308f20 24
986bc8de 25#include "block-luks.h"
3e308f20
DB
26
27#include "crypto/hash.h"
28#include "crypto/afsplit.h"
29#include "crypto/pbkdf.h"
30#include "crypto/secret.h"
31#include "crypto/random.h"
2ef950f9 32#include "qemu/uuid.h"
3e308f20
DB
33
34#include "qemu/coroutine.h"
35
36/*
37 * Reference for the LUKS format implemented here is
38 *
39 * docs/on-disk-format.pdf
40 *
41 * in 'cryptsetup' package source code
42 *
43 * This file implements the 1.2.1 specification, dated
44 * Oct 16, 2011.
45 */
46
47typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
48typedef struct QCryptoBlockLUKSHeader QCryptoBlockLUKSHeader;
49typedef struct QCryptoBlockLUKSKeySlot QCryptoBlockLUKSKeySlot;
50
51
52/* The following constants are all defined by the LUKS spec */
53#define QCRYPTO_BLOCK_LUKS_VERSION 1
54
55#define QCRYPTO_BLOCK_LUKS_MAGIC_LEN 6
56#define QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN 32
57#define QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN 32
58#define QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN 32
59#define QCRYPTO_BLOCK_LUKS_DIGEST_LEN 20
60#define QCRYPTO_BLOCK_LUKS_SALT_LEN 32
61#define QCRYPTO_BLOCK_LUKS_UUID_LEN 40
62#define QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS 8
63#define QCRYPTO_BLOCK_LUKS_STRIPES 4000
64#define QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS 1000
65#define QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS 1000
66#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET 4096
67
68#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED 0x0000DEAD
69#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED 0x00AC71F3
70
71#define QCRYPTO_BLOCK_LUKS_SECTOR_SIZE 512LL
72
73static const char qcrypto_block_luks_magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN] = {
74 'L', 'U', 'K', 'S', 0xBA, 0xBE
75};
76
77typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
78struct QCryptoBlockLUKSNameMap {
79 const char *name;
80 int id;
81};
82
83typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
84struct QCryptoBlockLUKSCipherSizeMap {
85 uint32_t key_bytes;
86 int id;
87};
88typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
89struct QCryptoBlockLUKSCipherNameMap {
90 const char *name;
91 const QCryptoBlockLUKSCipherSizeMap *sizes;
92};
93
94
95static const QCryptoBlockLUKSCipherSizeMap
96qcrypto_block_luks_cipher_size_map_aes[] = {
97 { 16, QCRYPTO_CIPHER_ALG_AES_128 },
98 { 24, QCRYPTO_CIPHER_ALG_AES_192 },
99 { 32, QCRYPTO_CIPHER_ALG_AES_256 },
100 { 0, 0 },
101};
102
103static const QCryptoBlockLUKSCipherSizeMap
104qcrypto_block_luks_cipher_size_map_cast5[] = {
105 { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
106 { 0, 0 },
107};
108
109static const QCryptoBlockLUKSCipherSizeMap
110qcrypto_block_luks_cipher_size_map_serpent[] = {
111 { 16, QCRYPTO_CIPHER_ALG_SERPENT_128 },
112 { 24, QCRYPTO_CIPHER_ALG_SERPENT_192 },
113 { 32, QCRYPTO_CIPHER_ALG_SERPENT_256 },
114 { 0, 0 },
115};
116
117static const QCryptoBlockLUKSCipherSizeMap
118qcrypto_block_luks_cipher_size_map_twofish[] = {
119 { 16, QCRYPTO_CIPHER_ALG_TWOFISH_128 },
120 { 24, QCRYPTO_CIPHER_ALG_TWOFISH_192 },
121 { 32, QCRYPTO_CIPHER_ALG_TWOFISH_256 },
122 { 0, 0 },
123};
124
125static const QCryptoBlockLUKSCipherNameMap
126qcrypto_block_luks_cipher_name_map[] = {
127 { "aes", qcrypto_block_luks_cipher_size_map_aes },
128 { "cast5", qcrypto_block_luks_cipher_size_map_cast5 },
129 { "serpent", qcrypto_block_luks_cipher_size_map_serpent },
130 { "twofish", qcrypto_block_luks_cipher_size_map_twofish },
131};
132
133
134/*
135 * This struct is written to disk in big-endian format,
136 * but operated upon in native-endian format.
137 */
138struct QCryptoBlockLUKSKeySlot {
139 /* state of keyslot, enabled/disable */
140 uint32_t active;
141 /* iterations for PBKDF2 */
142 uint32_t iterations;
143 /* salt for PBKDF2 */
144 uint8_t salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
145 /* start sector of key material */
f0d3c362 146 uint32_t key_offset_sector;
3e308f20
DB
147 /* number of anti-forensic stripes */
148 uint32_t stripes;
5993e3be 149};
3e308f20
DB
150
151QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSKeySlot) != 48);
152
153
154/*
155 * This struct is written to disk in big-endian format,
156 * but operated upon in native-endian format.
157 */
158struct QCryptoBlockLUKSHeader {
159 /* 'L', 'U', 'K', 'S', '0xBA', '0xBE' */
160 char magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN];
161
162 /* LUKS version, currently 1 */
163 uint16_t version;
164
165 /* cipher name specification (aes, etc) */
166 char cipher_name[QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN];
167
168 /* cipher mode specification (cbc-plain, xts-essiv:sha256, etc) */
169 char cipher_mode[QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN];
170
171 /* hash specification (sha256, etc) */
172 char hash_spec[QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN];
173
174 /* start offset of the volume data (in 512 byte sectors) */
f0d3c362 175 uint32_t payload_offset_sector;
3e308f20
DB
176
177 /* Number of key bytes */
f0d3c362 178 uint32_t master_key_len;
3e308f20
DB
179
180 /* master key checksum after PBKDF2 */
181 uint8_t master_key_digest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
182
183 /* salt for master key PBKDF2 */
184 uint8_t master_key_salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
185
186 /* iterations for master key PBKDF2 */
187 uint32_t master_key_iterations;
188
189 /* UUID of the partition in standard ASCII representation */
190 uint8_t uuid[QCRYPTO_BLOCK_LUKS_UUID_LEN];
191
192 /* key slots */
193 QCryptoBlockLUKSKeySlot key_slots[QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS];
5993e3be 194};
3e308f20
DB
195
196QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSHeader) != 592);
197
198
199struct QCryptoBlockLUKS {
200 QCryptoBlockLUKSHeader header;
40c85028 201
9d80e59d 202 /* Main encryption algorithm used for encryption*/
40c85028 203 QCryptoCipherAlgorithm cipher_alg;
9d80e59d
ML
204
205 /* Mode of encryption for the selected encryption algorithm */
40c85028 206 QCryptoCipherMode cipher_mode;
9d80e59d
ML
207
208 /* Initialization vector generation algorithm */
40c85028 209 QCryptoIVGenAlgorithm ivgen_alg;
9d80e59d
ML
210
211 /* Hash algorithm used for IV generation*/
40c85028 212 QCryptoHashAlgorithm ivgen_hash_alg;
9d80e59d
ML
213
214 /*
215 * Encryption algorithm used for IV generation.
216 * Usually the same as main encryption algorithm
217 */
218 QCryptoCipherAlgorithm ivgen_cipher_alg;
219
220 /* Hash algorithm used in pbkdf2 function */
40c85028 221 QCryptoHashAlgorithm hash_alg;
3e308f20
DB
222};
223
224
225static int qcrypto_block_luks_cipher_name_lookup(const char *name,
226 QCryptoCipherMode mode,
227 uint32_t key_bytes,
228 Error **errp)
229{
230 const QCryptoBlockLUKSCipherNameMap *map =
231 qcrypto_block_luks_cipher_name_map;
232 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
233 size_t i, j;
234
235 if (mode == QCRYPTO_CIPHER_MODE_XTS) {
236 key_bytes /= 2;
237 }
238
239 for (i = 0; i < maplen; i++) {
240 if (!g_str_equal(map[i].name, name)) {
241 continue;
242 }
243 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
244 if (map[i].sizes[j].key_bytes == key_bytes) {
245 return map[i].sizes[j].id;
246 }
247 }
248 }
249
250 error_setg(errp, "Algorithm %s with key size %d bytes not supported",
251 name, key_bytes);
252 return 0;
253}
254
255static const char *
256qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
257 Error **errp)
258{
259 const QCryptoBlockLUKSCipherNameMap *map =
260 qcrypto_block_luks_cipher_name_map;
261 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
262 size_t i, j;
263 for (i = 0; i < maplen; i++) {
264 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
265 if (map[i].sizes[j].id == alg) {
266 return map[i].name;
267 }
268 }
269 }
270
271 error_setg(errp, "Algorithm '%s' not supported",
977c736f 272 QCryptoCipherAlgorithm_str(alg));
3e308f20
DB
273 return NULL;
274}
275
276/* XXX replace with qapi_enum_parse() in future, when we can
277 * make that function emit a more friendly error message */
278static int qcrypto_block_luks_name_lookup(const char *name,
f7abe0ec 279 const QEnumLookup *map,
3e308f20
DB
280 const char *type,
281 Error **errp)
282{
9ae33079 283 int ret = qapi_enum_parse(map, name, -1, NULL);
3e308f20 284
9ae33079
MA
285 if (ret < 0) {
286 error_setg(errp, "%s %s not supported", type, name);
287 return 0;
288 }
289 return ret;
3e308f20
DB
290}
291
292#define qcrypto_block_luks_cipher_mode_lookup(name, errp) \
293 qcrypto_block_luks_name_lookup(name, \
f7abe0ec 294 &QCryptoCipherMode_lookup, \
3e308f20
DB
295 "Cipher mode", \
296 errp)
297
298#define qcrypto_block_luks_hash_name_lookup(name, errp) \
299 qcrypto_block_luks_name_lookup(name, \
f7abe0ec 300 &QCryptoHashAlgorithm_lookup, \
3e308f20
DB
301 "Hash algorithm", \
302 errp)
303
304#define qcrypto_block_luks_ivgen_name_lookup(name, errp) \
305 qcrypto_block_luks_name_lookup(name, \
f7abe0ec 306 &QCryptoIVGenAlgorithm_lookup, \
3e308f20
DB
307 "IV generator", \
308 errp)
309
310
311static bool
312qcrypto_block_luks_has_format(const uint8_t *buf,
313 size_t buf_size)
314{
315 const QCryptoBlockLUKSHeader *luks_header = (const void *)buf;
316
317 if (buf_size >= offsetof(QCryptoBlockLUKSHeader, cipher_name) &&
318 memcmp(luks_header->magic, qcrypto_block_luks_magic,
319 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) == 0 &&
320 be16_to_cpu(luks_header->version) == QCRYPTO_BLOCK_LUKS_VERSION) {
321 return true;
322 } else {
323 return false;
324 }
325}
326
327
328/**
329 * Deal with a quirk of dm-crypt usage of ESSIV.
330 *
331 * When calculating ESSIV IVs, the cipher length used by ESSIV
332 * may be different from the cipher length used for the block
333 * encryption, becauses dm-crypt uses the hash digest length
334 * as the key size. ie, if you have AES 128 as the block cipher
335 * and SHA 256 as ESSIV hash, then ESSIV will use AES 256 as
336 * the cipher since that gets a key length matching the digest
337 * size, not AES 128 with truncated digest as might be imagined
338 */
339static QCryptoCipherAlgorithm
340qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
341 QCryptoHashAlgorithm hash,
342 Error **errp)
343{
344 size_t digestlen = qcrypto_hash_digest_len(hash);
345 size_t keylen = qcrypto_cipher_get_key_len(cipher);
346 if (digestlen == keylen) {
347 return cipher;
348 }
349
350 switch (cipher) {
351 case QCRYPTO_CIPHER_ALG_AES_128:
352 case QCRYPTO_CIPHER_ALG_AES_192:
353 case QCRYPTO_CIPHER_ALG_AES_256:
354 if (digestlen == qcrypto_cipher_get_key_len(
355 QCRYPTO_CIPHER_ALG_AES_128)) {
356 return QCRYPTO_CIPHER_ALG_AES_128;
357 } else if (digestlen == qcrypto_cipher_get_key_len(
358 QCRYPTO_CIPHER_ALG_AES_192)) {
359 return QCRYPTO_CIPHER_ALG_AES_192;
360 } else if (digestlen == qcrypto_cipher_get_key_len(
361 QCRYPTO_CIPHER_ALG_AES_256)) {
362 return QCRYPTO_CIPHER_ALG_AES_256;
363 } else {
364 error_setg(errp, "No AES cipher with key size %zu available",
365 digestlen);
366 return 0;
367 }
368 break;
369 case QCRYPTO_CIPHER_ALG_SERPENT_128:
370 case QCRYPTO_CIPHER_ALG_SERPENT_192:
371 case QCRYPTO_CIPHER_ALG_SERPENT_256:
372 if (digestlen == qcrypto_cipher_get_key_len(
373 QCRYPTO_CIPHER_ALG_SERPENT_128)) {
374 return QCRYPTO_CIPHER_ALG_SERPENT_128;
375 } else if (digestlen == qcrypto_cipher_get_key_len(
376 QCRYPTO_CIPHER_ALG_SERPENT_192)) {
377 return QCRYPTO_CIPHER_ALG_SERPENT_192;
378 } else if (digestlen == qcrypto_cipher_get_key_len(
379 QCRYPTO_CIPHER_ALG_SERPENT_256)) {
380 return QCRYPTO_CIPHER_ALG_SERPENT_256;
381 } else {
382 error_setg(errp, "No Serpent cipher with key size %zu available",
383 digestlen);
384 return 0;
385 }
386 break;
387 case QCRYPTO_CIPHER_ALG_TWOFISH_128:
388 case QCRYPTO_CIPHER_ALG_TWOFISH_192:
389 case QCRYPTO_CIPHER_ALG_TWOFISH_256:
390 if (digestlen == qcrypto_cipher_get_key_len(
391 QCRYPTO_CIPHER_ALG_TWOFISH_128)) {
392 return QCRYPTO_CIPHER_ALG_TWOFISH_128;
393 } else if (digestlen == qcrypto_cipher_get_key_len(
394 QCRYPTO_CIPHER_ALG_TWOFISH_192)) {
395 return QCRYPTO_CIPHER_ALG_TWOFISH_192;
396 } else if (digestlen == qcrypto_cipher_get_key_len(
397 QCRYPTO_CIPHER_ALG_TWOFISH_256)) {
398 return QCRYPTO_CIPHER_ALG_TWOFISH_256;
399 } else {
400 error_setg(errp, "No Twofish cipher with key size %zu available",
401 digestlen);
402 return 0;
403 }
404 break;
405 default:
406 error_setg(errp, "Cipher %s not supported with essiv",
977c736f 407 QCryptoCipherAlgorithm_str(cipher));
3e308f20
DB
408 return 0;
409 }
410}
411
bd56a55a
ML
412/*
413 * Returns number of sectors needed to store the key material
414 * given number of anti forensic stripes
415 */
416static int
417qcrypto_block_luks_splitkeylen_sectors(const QCryptoBlockLUKS *luks,
418 unsigned int header_sectors,
419 unsigned int stripes)
420{
421 /*
422 * This calculation doesn't match that shown in the spec,
423 * but instead follows the cryptsetup implementation.
424 */
425
426 size_t splitkeylen = luks->header.master_key_len * stripes;
427
428 /* First align the key material size to block size*/
429 size_t splitkeylen_sectors =
430 DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE);
431
432 /* Then also align the key material size to the size of the header */
433 return ROUND_UP(splitkeylen_sectors, header_sectors);
434}
435
dde2c5af
ML
436/*
437 * Stores the main LUKS header, taking care of endianess
438 */
439static int
440qcrypto_block_luks_store_header(QCryptoBlock *block,
441 QCryptoBlockWriteFunc writefunc,
442 void *opaque,
443 Error **errp)
444{
445 const QCryptoBlockLUKS *luks = block->opaque;
446 Error *local_err = NULL;
447 size_t i;
448 g_autofree QCryptoBlockLUKSHeader *hdr_copy = NULL;
449
450 /* Create a copy of the header */
451 hdr_copy = g_new0(QCryptoBlockLUKSHeader, 1);
452 memcpy(hdr_copy, &luks->header, sizeof(QCryptoBlockLUKSHeader));
453
454 /*
455 * Everything on disk uses Big Endian (tm), so flip header fields
456 * before writing them
457 */
458 cpu_to_be16s(&hdr_copy->version);
459 cpu_to_be32s(&hdr_copy->payload_offset_sector);
460 cpu_to_be32s(&hdr_copy->master_key_len);
461 cpu_to_be32s(&hdr_copy->master_key_iterations);
462
463 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
464 cpu_to_be32s(&hdr_copy->key_slots[i].active);
465 cpu_to_be32s(&hdr_copy->key_slots[i].iterations);
466 cpu_to_be32s(&hdr_copy->key_slots[i].key_offset_sector);
467 cpu_to_be32s(&hdr_copy->key_slots[i].stripes);
468 }
469
470 /* Write out the partition header and key slot headers */
471 writefunc(block, 0, (const uint8_t *)hdr_copy, sizeof(*hdr_copy),
472 opaque, &local_err);
473
474 if (local_err) {
475 error_propagate(errp, local_err);
476 return -1;
477 }
478 return 0;
479}
480
481/*
482 * Loads the main LUKS header,and byteswaps it to native endianess
483 * And run basic sanity checks on it
484 */
485static int
486qcrypto_block_luks_load_header(QCryptoBlock *block,
487 QCryptoBlockReadFunc readfunc,
488 void *opaque,
489 Error **errp)
490{
491 ssize_t rv;
492 size_t i;
493 QCryptoBlockLUKS *luks = block->opaque;
494
495 /*
496 * Read the entire LUKS header, minus the key material from
497 * the underlying device
498 */
499 rv = readfunc(block, 0,
500 (uint8_t *)&luks->header,
501 sizeof(luks->header),
502 opaque,
503 errp);
504 if (rv < 0) {
505 return rv;
506 }
507
508 /*
509 * The header is always stored in big-endian format, so
510 * convert everything to native
511 */
512 be16_to_cpus(&luks->header.version);
513 be32_to_cpus(&luks->header.payload_offset_sector);
514 be32_to_cpus(&luks->header.master_key_len);
515 be32_to_cpus(&luks->header.master_key_iterations);
516
517 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
518 be32_to_cpus(&luks->header.key_slots[i].active);
519 be32_to_cpus(&luks->header.key_slots[i].iterations);
520 be32_to_cpus(&luks->header.key_slots[i].key_offset_sector);
521 be32_to_cpus(&luks->header.key_slots[i].stripes);
522 }
523
524 return 0;
525}
526
9fa9c1c2
ML
527/*
528 * Does basic sanity checks on the LUKS header
529 */
530static int
531qcrypto_block_luks_check_header(const QCryptoBlockLUKS *luks, Error **errp)
532{
533 if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
534 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
535 error_setg(errp, "Volume is not in LUKS format");
536 return -1;
537 }
538
539 if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
540 error_setg(errp, "LUKS version %" PRIu32 " is not supported",
541 luks->header.version);
542 return -1;
543 }
544 return 0;
545}
546
547/*
548 * Parses the crypto parameters that are stored in the LUKS header
549 */
550
551static int
552qcrypto_block_luks_parse_header(QCryptoBlockLUKS *luks, Error **errp)
553{
554 g_autofree char *cipher_mode = g_strdup(luks->header.cipher_mode);
555 char *ivgen_name, *ivhash_name;
556 Error *local_err = NULL;
557
558 /*
559 * The cipher_mode header contains a string that we have
560 * to further parse, of the format
561 *
562 * <cipher-mode>-<iv-generator>[:<iv-hash>]
563 *
564 * eg cbc-essiv:sha256, cbc-plain64
565 */
566 ivgen_name = strchr(cipher_mode, '-');
567 if (!ivgen_name) {
568 error_setg(errp, "Unexpected cipher mode string format %s",
569 luks->header.cipher_mode);
570 return -1;
571 }
572 *ivgen_name = '\0';
573 ivgen_name++;
574
575 ivhash_name = strchr(ivgen_name, ':');
576 if (!ivhash_name) {
577 luks->ivgen_hash_alg = 0;
578 } else {
579 *ivhash_name = '\0';
580 ivhash_name++;
581
582 luks->ivgen_hash_alg = qcrypto_block_luks_hash_name_lookup(ivhash_name,
583 &local_err);
584 if (local_err) {
585 error_propagate(errp, local_err);
586 return -1;
587 }
588 }
589
590 luks->cipher_mode = qcrypto_block_luks_cipher_mode_lookup(cipher_mode,
591 &local_err);
592 if (local_err) {
593 error_propagate(errp, local_err);
594 return -1;
595 }
596
597 luks->cipher_alg =
598 qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
599 luks->cipher_mode,
600 luks->header.master_key_len,
601 &local_err);
602 if (local_err) {
603 error_propagate(errp, local_err);
604 return -1;
605 }
606
607 luks->hash_alg =
608 qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
609 &local_err);
610 if (local_err) {
611 error_propagate(errp, local_err);
612 return -1;
613 }
614
615 luks->ivgen_alg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
616 &local_err);
617 if (local_err) {
618 error_propagate(errp, local_err);
619 return -1;
620 }
621
622 if (luks->ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
623 if (!ivhash_name) {
624 error_setg(errp, "Missing IV generator hash specification");
625 return -1;
626 }
627 luks->ivgen_cipher_alg =
628 qcrypto_block_luks_essiv_cipher(luks->cipher_alg,
629 luks->ivgen_hash_alg,
630 &local_err);
631 if (local_err) {
632 error_propagate(errp, local_err);
633 return -1;
634 }
635 } else {
636
637 /*
638 * Note we parsed the ivhash_name earlier in the cipher_mode
639 * spec string even with plain/plain64 ivgens, but we
640 * will ignore it, since it is irrelevant for these ivgens.
641 * This is for compat with dm-crypt which will silently
642 * ignore hash names with these ivgens rather than report
643 * an error about the invalid usage
644 */
645 luks->ivgen_cipher_alg = luks->cipher_alg;
646 }
647 return 0;
648}
649
3994a7c9
ML
650/*
651 * Given a key slot, user password, and the master key,
652 * will store the encrypted master key there, and update the
653 * in-memory header. User must then write the in-memory header
654 *
655 * Returns:
656 * 0 if the keyslot was written successfully
657 * with the provided password
658 * -1 if a fatal error occurred while storing the key
659 */
660static int
661qcrypto_block_luks_store_key(QCryptoBlock *block,
662 unsigned int slot_idx,
663 const char *password,
664 uint8_t *masterkey,
665 uint64_t iter_time,
666 QCryptoBlockWriteFunc writefunc,
667 void *opaque,
668 Error **errp)
669{
670 QCryptoBlockLUKS *luks = block->opaque;
671 QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[slot_idx];
672 g_autofree uint8_t *splitkey = NULL;
673 size_t splitkeylen;
674 g_autofree uint8_t *slotkey = NULL;
675 g_autoptr(QCryptoCipher) cipher = NULL;
676 g_autoptr(QCryptoIVGen) ivgen = NULL;
677 Error *local_err = NULL;
678 uint64_t iters;
679 int ret = -1;
680
681 if (qcrypto_random_bytes(slot->salt,
682 QCRYPTO_BLOCK_LUKS_SALT_LEN,
683 errp) < 0) {
684 goto cleanup;
685 }
686
687 splitkeylen = luks->header.master_key_len * slot->stripes;
688
689 /*
690 * Determine how many iterations are required to
691 * hash the user password while consuming 1 second of compute
692 * time
693 */
694 iters = qcrypto_pbkdf2_count_iters(luks->hash_alg,
695 (uint8_t *)password, strlen(password),
696 slot->salt,
697 QCRYPTO_BLOCK_LUKS_SALT_LEN,
698 luks->header.master_key_len,
699 &local_err);
700 if (local_err) {
701 error_propagate(errp, local_err);
702 goto cleanup;
703 }
704
705 if (iters > (ULLONG_MAX / iter_time)) {
706 error_setg_errno(errp, ERANGE,
707 "PBKDF iterations %llu too large to scale",
708 (unsigned long long)iters);
709 goto cleanup;
710 }
711
712 /* iter_time was in millis, but count_iters reported for secs */
713 iters = iters * iter_time / 1000;
714
715 if (iters > UINT32_MAX) {
716 error_setg_errno(errp, ERANGE,
717 "PBKDF iterations %llu larger than %u",
718 (unsigned long long)iters, UINT32_MAX);
719 goto cleanup;
720 }
721
722 slot->iterations =
723 MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
724
725
726 /*
727 * Generate a key that we'll use to encrypt the master
728 * key, from the user's password
729 */
730 slotkey = g_new0(uint8_t, luks->header.master_key_len);
731 if (qcrypto_pbkdf2(luks->hash_alg,
732 (uint8_t *)password, strlen(password),
733 slot->salt,
734 QCRYPTO_BLOCK_LUKS_SALT_LEN,
735 slot->iterations,
736 slotkey, luks->header.master_key_len,
737 errp) < 0) {
738 goto cleanup;
739 }
740
741
742 /*
743 * Setup the encryption objects needed to encrypt the
744 * master key material
745 */
746 cipher = qcrypto_cipher_new(luks->cipher_alg,
747 luks->cipher_mode,
748 slotkey, luks->header.master_key_len,
749 errp);
750 if (!cipher) {
751 goto cleanup;
752 }
753
754 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
755 luks->ivgen_cipher_alg,
756 luks->ivgen_hash_alg,
757 slotkey, luks->header.master_key_len,
758 errp);
759 if (!ivgen) {
760 goto cleanup;
761 }
762
763 /*
764 * Before storing the master key, we need to vastly
765 * increase its size, as protection against forensic
766 * disk data recovery
767 */
768 splitkey = g_new0(uint8_t, splitkeylen);
769
770 if (qcrypto_afsplit_encode(luks->hash_alg,
771 luks->header.master_key_len,
772 slot->stripes,
773 masterkey,
774 splitkey,
775 errp) < 0) {
776 goto cleanup;
777 }
778
779 /*
780 * Now we encrypt the split master key with the key generated
781 * from the user's password, before storing it
782 */
783 if (qcrypto_block_cipher_encrypt_helper(cipher, block->niv, ivgen,
784 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
785 0,
786 splitkey,
787 splitkeylen,
788 errp) < 0) {
789 goto cleanup;
790 }
791
792 /* Write out the slot's master key material. */
793 if (writefunc(block,
794 slot->key_offset_sector *
795 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
796 splitkey, splitkeylen,
797 opaque,
798 errp) != splitkeylen) {
799 goto cleanup;
800 }
801
802 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
803
804 if (qcrypto_block_luks_store_header(block, writefunc, opaque, errp) < 0) {
805 goto cleanup;
806 }
807
808 ret = 0;
809
810cleanup:
811 if (slotkey) {
812 memset(slotkey, 0, luks->header.master_key_len);
813 }
814 if (splitkey) {
815 memset(splitkey, 0, splitkeylen);
816 }
817 return ret;
818}
819
3e308f20
DB
820/*
821 * Given a key slot, and user password, this will attempt to unlock
822 * the master encryption key from the key slot.
823 *
824 * Returns:
825 * 0 if the key slot is disabled, or key could not be decrypted
826 * with the provided password
827 * 1 if the key slot is enabled, and key decrypted successfully
828 * with the provided password
829 * -1 if a fatal error occurred loading the key
830 */
831static int
832qcrypto_block_luks_load_key(QCryptoBlock *block,
7e60a6f5 833 size_t slot_idx,
3e308f20 834 const char *password,
3e308f20 835 uint8_t *masterkey,
3e308f20
DB
836 QCryptoBlockReadFunc readfunc,
837 void *opaque,
838 Error **errp)
839{
840 QCryptoBlockLUKS *luks = block->opaque;
7e60a6f5 841 const QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[slot_idx];
57b9f113 842 g_autofree uint8_t *splitkey = NULL;
3e308f20 843 size_t splitkeylen;
57b9f113 844 g_autofree uint8_t *possiblekey = NULL;
3e308f20 845 ssize_t rv;
57b9f113 846 g_autoptr(QCryptoCipher) cipher = NULL;
3e308f20 847 uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
57b9f113 848 g_autoptr(QCryptoIVGen) ivgen = NULL;
3e308f20
DB
849 size_t niv;
850
851 if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
852 return 0;
853 }
854
1ddd52e4 855 splitkeylen = luks->header.master_key_len * slot->stripes;
3e308f20 856 splitkey = g_new0(uint8_t, splitkeylen);
1ddd52e4 857 possiblekey = g_new0(uint8_t, luks->header.master_key_len);
3e308f20
DB
858
859 /*
860 * The user password is used to generate a (possible)
861 * decryption key. This may or may not successfully
862 * decrypt the master key - we just blindly assume
863 * the key is correct and validate the results of
864 * decryption later.
865 */
9d80e59d 866 if (qcrypto_pbkdf2(luks->hash_alg,
3e308f20
DB
867 (const uint8_t *)password, strlen(password),
868 slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
869 slot->iterations,
1ddd52e4 870 possiblekey, luks->header.master_key_len,
3e308f20 871 errp) < 0) {
57b9f113 872 return -1;
3e308f20
DB
873 }
874
875 /*
876 * We need to read the master key material from the
877 * LUKS key material header. What we're reading is
878 * not the raw master key, but rather the data after
879 * it has been passed through AFSplit and the result
880 * then encrypted.
881 */
882 rv = readfunc(block,
f0d3c362 883 slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
3e308f20 884 splitkey, splitkeylen,
e4a3507e 885 opaque,
37509233 886 errp);
3e308f20 887 if (rv < 0) {
57b9f113 888 return -1;
3e308f20
DB
889 }
890
891
892 /* Setup the cipher/ivgen that we'll use to try to decrypt
893 * the split master key material */
9d80e59d
ML
894 cipher = qcrypto_cipher_new(luks->cipher_alg,
895 luks->cipher_mode,
896 possiblekey,
897 luks->header.master_key_len,
3e308f20
DB
898 errp);
899 if (!cipher) {
57b9f113 900 return -1;
3e308f20
DB
901 }
902
9d80e59d
ML
903 niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
904 luks->cipher_mode);
905
906 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
907 luks->ivgen_cipher_alg,
908 luks->ivgen_hash_alg,
909 possiblekey,
910 luks->header.master_key_len,
3e308f20
DB
911 errp);
912 if (!ivgen) {
57b9f113 913 return -1;
3e308f20
DB
914 }
915
916
917 /*
918 * The master key needs to be decrypted in the same
919 * way that the block device payload will be decrypted
920 * later. In particular we'll be using the IV generator
921 * to reset the encryption cipher every time the master
922 * key crosses a sector boundary.
923 */
0270417c
VSO
924 if (qcrypto_block_cipher_decrypt_helper(cipher,
925 niv,
926 ivgen,
927 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
928 0,
929 splitkey,
930 splitkeylen,
931 errp) < 0) {
57b9f113 932 return -1;
3e308f20
DB
933 }
934
935 /*
936 * Now we've decrypted the split master key, join
937 * it back together to get the actual master key.
938 */
9d80e59d 939 if (qcrypto_afsplit_decode(luks->hash_alg,
1ddd52e4 940 luks->header.master_key_len,
3e308f20
DB
941 slot->stripes,
942 splitkey,
943 masterkey,
944 errp) < 0) {
57b9f113 945 return -1;
3e308f20
DB
946 }
947
948
949 /*
950 * We still don't know that the masterkey we got is valid,
951 * because we just blindly assumed the user's password
952 * was correct. This is where we now verify it. We are
953 * creating a hash of the master key using PBKDF and
954 * then comparing that to the hash stored in the key slot
955 * header
956 */
9d80e59d 957 if (qcrypto_pbkdf2(luks->hash_alg,
1ddd52e4
ML
958 masterkey,
959 luks->header.master_key_len,
3e308f20
DB
960 luks->header.master_key_salt,
961 QCRYPTO_BLOCK_LUKS_SALT_LEN,
962 luks->header.master_key_iterations,
1ddd52e4
ML
963 keydigest,
964 G_N_ELEMENTS(keydigest),
3e308f20 965 errp) < 0) {
57b9f113 966 return -1;
3e308f20
DB
967 }
968
969 if (memcmp(keydigest, luks->header.master_key_digest,
970 QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
971 /* Success, we got the right master key */
57b9f113 972 return 1;
3e308f20
DB
973 }
974
975 /* Fail, user's password was not valid for this key slot,
976 * tell caller to try another slot */
57b9f113 977 return 0;
3e308f20
DB
978}
979
980
981/*
982 * Given a user password, this will iterate over all key
983 * slots and try to unlock each active key slot using the
984 * password until it successfully obtains a master key.
985 *
986 * Returns 0 if a key was loaded, -1 if no keys could be loaded
987 */
988static int
989qcrypto_block_luks_find_key(QCryptoBlock *block,
990 const char *password,
1ddd52e4 991 uint8_t *masterkey,
3e308f20
DB
992 QCryptoBlockReadFunc readfunc,
993 void *opaque,
994 Error **errp)
995{
3e308f20
DB
996 size_t i;
997 int rv;
998
3e308f20
DB
999 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1000 rv = qcrypto_block_luks_load_key(block,
7e60a6f5 1001 i,
3e308f20 1002 password,
1ddd52e4 1003 masterkey,
3e308f20
DB
1004 readfunc,
1005 opaque,
1006 errp);
1007 if (rv < 0) {
1008 goto error;
1009 }
1010 if (rv == 1) {
1011 return 0;
1012 }
1013 }
1014
1015 error_setg(errp, "Invalid password, cannot unlock any keyslot");
3e308f20 1016 error:
3e308f20
DB
1017 return -1;
1018}
1019
1020
1021static int
1022qcrypto_block_luks_open(QCryptoBlock *block,
1023 QCryptoBlockOpenOptions *options,
1cd9a787 1024 const char *optprefix,
3e308f20
DB
1025 QCryptoBlockReadFunc readfunc,
1026 void *opaque,
1027 unsigned int flags,
c972fa12 1028 size_t n_threads,
3e308f20
DB
1029 Error **errp)
1030{
9d80e59d 1031 QCryptoBlockLUKS *luks = NULL;
57b9f113 1032 g_autofree uint8_t *masterkey = NULL;
57b9f113 1033 g_autofree char *password = NULL;
3e308f20
DB
1034
1035 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1036 if (!options->u.luks.key_secret) {
1cd9a787
DB
1037 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1038 optprefix ? optprefix : "");
3e308f20
DB
1039 return -1;
1040 }
1041 password = qcrypto_secret_lookup_as_utf8(
1042 options->u.luks.key_secret, errp);
1043 if (!password) {
1044 return -1;
1045 }
1046 }
1047
1048 luks = g_new0(QCryptoBlockLUKS, 1);
1049 block->opaque = luks;
1050
dde2c5af 1051 if (qcrypto_block_luks_load_header(block, readfunc, opaque, errp) < 0) {
3e308f20
DB
1052 goto fail;
1053 }
1054
9fa9c1c2 1055 if (qcrypto_block_luks_check_header(luks, errp) < 0) {
3e308f20
DB
1056 goto fail;
1057 }
1058
9fa9c1c2 1059 if (qcrypto_block_luks_parse_header(luks, errp) < 0) {
3e308f20
DB
1060 goto fail;
1061 }
3e308f20
DB
1062
1063 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1064 /* Try to find which key slot our password is valid for
1065 * and unlock the master key from that slot.
1066 */
1ddd52e4
ML
1067
1068 masterkey = g_new0(uint8_t, luks->header.master_key_len);
1069
3e308f20
DB
1070 if (qcrypto_block_luks_find_key(block,
1071 password,
1ddd52e4 1072 masterkey,
3e308f20
DB
1073 readfunc, opaque,
1074 errp) < 0) {
3e308f20
DB
1075 goto fail;
1076 }
1077
1078 /* We have a valid master key now, so can setup the
1079 * block device payload decryption objects
1080 */
9d80e59d
ML
1081 block->kdfhash = luks->hash_alg;
1082 block->niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
1083 luks->cipher_mode);
1084
1085 block->ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
1086 luks->ivgen_cipher_alg,
1087 luks->ivgen_hash_alg,
1ddd52e4
ML
1088 masterkey,
1089 luks->header.master_key_len,
3e308f20
DB
1090 errp);
1091 if (!block->ivgen) {
3e308f20
DB
1092 goto fail;
1093 }
1094
61dd8a9a
ML
1095 if (qcrypto_block_init_cipher(block,
1096 luks->cipher_alg,
1097 luks->cipher_mode,
1098 masterkey,
1099 luks->header.master_key_len,
1100 n_threads,
1101 errp) < 0) {
3e308f20
DB
1102 goto fail;
1103 }
1104 }
1105
850f49de 1106 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
f0d3c362 1107 block->payload_offset = luks->header.payload_offset_sector *
850f49de 1108 block->sector_size;
3e308f20 1109
3e308f20
DB
1110 return 0;
1111
1112 fail:
c972fa12 1113 qcrypto_block_free_cipher(block);
3e308f20
DB
1114 qcrypto_ivgen_free(block->ivgen);
1115 g_free(luks);
61dd8a9a 1116 return -1;
3e308f20
DB
1117}
1118
1119
2ef950f9
FZ
1120static void
1121qcrypto_block_luks_uuid_gen(uint8_t *uuidstr)
3e308f20 1122{
2ef950f9
FZ
1123 QemuUUID uuid;
1124 qemu_uuid_generate(&uuid);
1125 qemu_uuid_unparse(&uuid, (char *)uuidstr);
3e308f20
DB
1126}
1127
1128static int
1129qcrypto_block_luks_create(QCryptoBlock *block,
1130 QCryptoBlockCreateOptions *options,
1cd9a787 1131 const char *optprefix,
3e308f20
DB
1132 QCryptoBlockInitFunc initfunc,
1133 QCryptoBlockWriteFunc writefunc,
1134 void *opaque,
1135 Error **errp)
1136{
1137 QCryptoBlockLUKS *luks;
1138 QCryptoBlockCreateOptionsLUKS luks_opts;
1139 Error *local_err = NULL;
57b9f113 1140 g_autofree uint8_t *masterkey = NULL;
bd56a55a
ML
1141 size_t header_sectors;
1142 size_t split_key_sectors;
3e308f20 1143 size_t i;
57b9f113 1144 g_autofree char *password = NULL;
3e308f20
DB
1145 const char *cipher_alg;
1146 const char *cipher_mode;
1147 const char *ivgen_alg;
1148 const char *ivgen_hash_alg = NULL;
1149 const char *hash_alg;
57b9f113 1150 g_autofree char *cipher_mode_spec = NULL;
59b060be 1151 uint64_t iters;
3e308f20
DB
1152
1153 memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
3bd18890 1154 if (!luks_opts.has_iter_time) {
2ab66cd5 1155 luks_opts.iter_time = 2000;
3bd18890 1156 }
3e308f20
DB
1157 if (!luks_opts.has_cipher_alg) {
1158 luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
1159 }
1160 if (!luks_opts.has_cipher_mode) {
1161 luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
1162 }
1163 if (!luks_opts.has_ivgen_alg) {
1164 luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
1165 }
1166 if (!luks_opts.has_hash_alg) {
1167 luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
1168 }
8b7cdba3
DB
1169 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1170 if (!luks_opts.has_ivgen_hash_alg) {
1171 luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
1172 luks_opts.has_ivgen_hash_alg = true;
1173 }
1174 }
9d80e59d
ML
1175
1176 luks = g_new0(QCryptoBlockLUKS, 1);
1177 block->opaque = luks;
1178
1179 luks->cipher_alg = luks_opts.cipher_alg;
1180 luks->cipher_mode = luks_opts.cipher_mode;
1181 luks->ivgen_alg = luks_opts.ivgen_alg;
1182 luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
1183 luks->hash_alg = luks_opts.hash_alg;
1184
1185
8b7cdba3
DB
1186 /* Note we're allowing ivgen_hash_alg to be set even for
1187 * non-essiv iv generators that don't need a hash. It will
1188 * be silently ignored, for compatibility with dm-crypt */
3e308f20
DB
1189
1190 if (!options->u.luks.key_secret) {
1cd9a787
DB
1191 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1192 optprefix ? optprefix : "");
9d80e59d 1193 goto error;
3e308f20
DB
1194 }
1195 password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
1196 if (!password) {
9d80e59d 1197 goto error;
3e308f20
DB
1198 }
1199
3e308f20
DB
1200
1201 memcpy(luks->header.magic, qcrypto_block_luks_magic,
1202 QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
1203
1204 /* We populate the header in native endianness initially and
1205 * then convert everything to big endian just before writing
1206 * it out to disk
1207 */
1208 luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
2ef950f9 1209 qcrypto_block_luks_uuid_gen(luks->header.uuid);
3e308f20
DB
1210
1211 cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
1212 errp);
1213 if (!cipher_alg) {
1214 goto error;
1215 }
1216
977c736f
MA
1217 cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
1218 ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
3e308f20 1219 if (luks_opts.has_ivgen_hash_alg) {
977c736f 1220 ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
3e308f20
DB
1221 cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
1222 ivgen_hash_alg);
1223 } else {
1224 cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
1225 }
977c736f 1226 hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
3e308f20
DB
1227
1228
1229 if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
1230 error_setg(errp, "Cipher name '%s' is too long for LUKS header",
1231 cipher_alg);
1232 goto error;
1233 }
1234 if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
1235 error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
1236 cipher_mode_spec);
1237 goto error;
1238 }
1239 if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
1240 error_setg(errp, "Hash name '%s' is too long for LUKS header",
1241 hash_alg);
1242 goto error;
1243 }
1244
1245 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
9d80e59d
ML
1246 luks->ivgen_cipher_alg =
1247 qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
1248 luks_opts.ivgen_hash_alg,
1249 &local_err);
3e308f20
DB
1250 if (local_err) {
1251 error_propagate(errp, local_err);
1252 goto error;
1253 }
1254 } else {
9d80e59d 1255 luks->ivgen_cipher_alg = luks_opts.cipher_alg;
3e308f20
DB
1256 }
1257
1258 strcpy(luks->header.cipher_name, cipher_alg);
1259 strcpy(luks->header.cipher_mode, cipher_mode_spec);
1260 strcpy(luks->header.hash_spec, hash_alg);
1261
f0d3c362
ML
1262 luks->header.master_key_len =
1263 qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
1264
3e308f20 1265 if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
f0d3c362 1266 luks->header.master_key_len *= 2;
3e308f20
DB
1267 }
1268
1269 /* Generate the salt used for hashing the master key
1270 * with PBKDF later
1271 */
1272 if (qcrypto_random_bytes(luks->header.master_key_salt,
1273 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1274 errp) < 0) {
1275 goto error;
1276 }
1277
1278 /* Generate random master key */
f0d3c362 1279 masterkey = g_new0(uint8_t, luks->header.master_key_len);
3e308f20 1280 if (qcrypto_random_bytes(masterkey,
f0d3c362 1281 luks->header.master_key_len, errp) < 0) {
3e308f20
DB
1282 goto error;
1283 }
1284
1285
1286 /* Setup the block device payload encryption objects */
c972fa12
VSO
1287 if (qcrypto_block_init_cipher(block, luks_opts.cipher_alg,
1288 luks_opts.cipher_mode, masterkey,
f0d3c362 1289 luks->header.master_key_len, 1, errp) < 0) {
3e308f20
DB
1290 goto error;
1291 }
1292
1293 block->kdfhash = luks_opts.hash_alg;
1294 block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1295 luks_opts.cipher_mode);
1296 block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
9d80e59d 1297 luks->ivgen_cipher_alg,
3e308f20 1298 luks_opts.ivgen_hash_alg,
f0d3c362 1299 masterkey, luks->header.master_key_len,
3e308f20
DB
1300 errp);
1301
1302 if (!block->ivgen) {
1303 goto error;
1304 }
1305
1306
1307 /* Determine how many iterations we need to hash the master
1308 * key, in order to have 1 second of compute time used
1309 */
59b060be 1310 iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
f0d3c362 1311 masterkey, luks->header.master_key_len,
59b060be
DB
1312 luks->header.master_key_salt,
1313 QCRYPTO_BLOCK_LUKS_SALT_LEN,
e74aabcf 1314 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
59b060be 1315 &local_err);
3e308f20
DB
1316 if (local_err) {
1317 error_propagate(errp, local_err);
1318 goto error;
1319 }
1320
3bd18890
DB
1321 if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1322 error_setg_errno(errp, ERANGE,
1323 "PBKDF iterations %llu too large to scale",
1324 (unsigned long long)iters);
1325 goto error;
1326 }
1327
1328 /* iter_time was in millis, but count_iters reported for secs */
1329 iters = iters * luks_opts.iter_time / 1000;
1330
3e308f20
DB
1331 /* Why /= 8 ? That matches cryptsetup, but there's no
1332 * explanation why they chose /= 8... Probably so that
1333 * if all 8 keyslots are active we only spend 1 second
1334 * in total time to check all keys */
59b060be
DB
1335 iters /= 8;
1336 if (iters > UINT32_MAX) {
1337 error_setg_errno(errp, ERANGE,
1338 "PBKDF iterations %llu larger than %u",
1339 (unsigned long long)iters, UINT32_MAX);
1340 goto error;
1341 }
1342 iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1343 luks->header.master_key_iterations = iters;
3e308f20
DB
1344
1345 /* Hash the master key, saving the result in the LUKS
1346 * header. This hash is used when opening the encrypted
1347 * device to verify that the user password unlocked a
1348 * valid master key
1349 */
1350 if (qcrypto_pbkdf2(luks_opts.hash_alg,
f0d3c362 1351 masterkey, luks->header.master_key_len,
3e308f20
DB
1352 luks->header.master_key_salt,
1353 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1354 luks->header.master_key_iterations,
1355 luks->header.master_key_digest,
1356 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1357 errp) < 0) {
1358 goto error;
1359 }
1360
bd56a55a
ML
1361 /* start with the sector that follows the header*/
1362 header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1363 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1364
1365 split_key_sectors =
1366 qcrypto_block_luks_splitkeylen_sectors(luks,
1367 header_sectors,
1368 QCRYPTO_BLOCK_LUKS_STRIPES);
3e308f20 1369
3e308f20 1370 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
bd56a55a
ML
1371 QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[i];
1372 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
3e308f20 1373
bd56a55a
ML
1374 slot->key_offset_sector = header_sectors + i * split_key_sectors;
1375 slot->stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
3e308f20
DB
1376 }
1377
3e308f20
DB
1378 /* The total size of the LUKS headers is the partition header + key
1379 * slot headers, rounded up to the nearest sector, combined with
1380 * the size of each master key material region, also rounded up
1381 * to the nearest sector */
bd56a55a
ML
1382 luks->header.payload_offset_sector = header_sectors +
1383 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS * split_key_sectors;
3e308f20 1384
850f49de 1385 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
f0d3c362 1386 block->payload_offset = luks->header.payload_offset_sector *
850f49de 1387 block->sector_size;
3e308f20
DB
1388
1389 /* Reserve header space to match payload offset */
e4a3507e 1390 initfunc(block, block->payload_offset, opaque, &local_err);
3e308f20
DB
1391 if (local_err) {
1392 error_propagate(errp, local_err);
1393 goto error;
1394 }
1395
3e308f20 1396
3994a7c9
ML
1397 /* populate the slot 0 with the password encrypted master key*/
1398 /* This will also store the header */
1399 if (qcrypto_block_luks_store_key(block,
1400 0,
1401 password,
1402 masterkey,
1403 luks_opts.iter_time,
1404 writefunc,
1405 opaque,
1406 errp) < 0) {
3e308f20
DB
1407 goto error;
1408 }
1409
f0d3c362 1410 memset(masterkey, 0, luks->header.master_key_len);
3e308f20
DB
1411
1412 return 0;
1413
1414 error:
1415 if (masterkey) {
f0d3c362 1416 memset(masterkey, 0, luks->header.master_key_len);
3e308f20 1417 }
3e308f20 1418
c972fa12 1419 qcrypto_block_free_cipher(block);
b640adca
VSO
1420 qcrypto_ivgen_free(block->ivgen);
1421
3e308f20
DB
1422 g_free(luks);
1423 return -1;
1424}
1425
1426
40c85028
DB
1427static int qcrypto_block_luks_get_info(QCryptoBlock *block,
1428 QCryptoBlockInfo *info,
1429 Error **errp)
1430{
1431 QCryptoBlockLUKS *luks = block->opaque;
1432 QCryptoBlockInfoLUKSSlot *slot;
1433 QCryptoBlockInfoLUKSSlotList *slots = NULL, **prev = &info->u.luks.slots;
1434 size_t i;
1435
1436 info->u.luks.cipher_alg = luks->cipher_alg;
1437 info->u.luks.cipher_mode = luks->cipher_mode;
1438 info->u.luks.ivgen_alg = luks->ivgen_alg;
1439 if (info->u.luks.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1440 info->u.luks.has_ivgen_hash_alg = true;
1441 info->u.luks.ivgen_hash_alg = luks->ivgen_hash_alg;
1442 }
1443 info->u.luks.hash_alg = luks->hash_alg;
1444 info->u.luks.payload_offset = block->payload_offset;
1445 info->u.luks.master_key_iters = luks->header.master_key_iterations;
1446 info->u.luks.uuid = g_strndup((const char *)luks->header.uuid,
1447 sizeof(luks->header.uuid));
1448
1449 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1450 slots = g_new0(QCryptoBlockInfoLUKSSlotList, 1);
1451 *prev = slots;
1452
1453 slots->value = slot = g_new0(QCryptoBlockInfoLUKSSlot, 1);
1454 slot->active = luks->header.key_slots[i].active ==
1455 QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
f0d3c362 1456 slot->key_offset = luks->header.key_slots[i].key_offset_sector
40c85028
DB
1457 * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1458 if (slot->active) {
1459 slot->has_iters = true;
1460 slot->iters = luks->header.key_slots[i].iterations;
1461 slot->has_stripes = true;
1462 slot->stripes = luks->header.key_slots[i].stripes;
1463 }
1464
1465 prev = &slots->next;
1466 }
1467
1468 return 0;
1469}
1470
1471
3e308f20
DB
1472static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1473{
1474 g_free(block->opaque);
1475}
1476
1477
1478static int
1479qcrypto_block_luks_decrypt(QCryptoBlock *block,
4609742a 1480 uint64_t offset,
3e308f20
DB
1481 uint8_t *buf,
1482 size_t len,
1483 Error **errp)
1484{
4609742a
DB
1485 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1486 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
0f0d596c
VSO
1487 return qcrypto_block_decrypt_helper(block,
1488 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1489 offset, buf, len, errp);
3e308f20
DB
1490}
1491
1492
1493static int
1494qcrypto_block_luks_encrypt(QCryptoBlock *block,
4609742a 1495 uint64_t offset,
3e308f20
DB
1496 uint8_t *buf,
1497 size_t len,
1498 Error **errp)
1499{
4609742a
DB
1500 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1501 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
0f0d596c
VSO
1502 return qcrypto_block_encrypt_helper(block,
1503 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1504 offset, buf, len, errp);
3e308f20
DB
1505}
1506
1507
1508const QCryptoBlockDriver qcrypto_block_driver_luks = {
1509 .open = qcrypto_block_luks_open,
1510 .create = qcrypto_block_luks_create,
40c85028 1511 .get_info = qcrypto_block_luks_get_info,
3e308f20
DB
1512 .cleanup = qcrypto_block_luks_cleanup,
1513 .decrypt = qcrypto_block_luks_decrypt,
1514 .encrypt = qcrypto_block_luks_encrypt,
1515 .has_format = qcrypto_block_luks_has_format,
1516};