]> git.proxmox.com Git - mirror_qemu.git/blob - crypto/block-luks.c
migration/yank: Use channel features
[mirror_qemu.git] / crypto / block-luks.c
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
9 * version 2.1 of the License, or (at your option) any later version.
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"
22 #include "qapi/error.h"
23 #include "qemu/bswap.h"
24
25 #include "block-luks.h"
26 #include "block-luks-priv.h"
27
28 #include "crypto/hash.h"
29 #include "crypto/afsplit.h"
30 #include "crypto/pbkdf.h"
31 #include "crypto/secret.h"
32 #include "crypto/random.h"
33 #include "qemu/uuid.h"
34
35 #include "qemu/bitmap.h"
36
37 /*
38 * Reference for the LUKS format implemented here is
39 *
40 * docs/on-disk-format.pdf
41 *
42 * in 'cryptsetup' package source code
43 *
44 * This file implements the 1.2.1 specification, dated
45 * Oct 16, 2011.
46 */
47
48 typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
49
50 typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
51 struct QCryptoBlockLUKSNameMap {
52 const char *name;
53 int id;
54 };
55
56 typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
57 struct QCryptoBlockLUKSCipherSizeMap {
58 uint32_t key_bytes;
59 int id;
60 };
61 typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
62 struct QCryptoBlockLUKSCipherNameMap {
63 const char *name;
64 const QCryptoBlockLUKSCipherSizeMap *sizes;
65 };
66
67
68 static const QCryptoBlockLUKSCipherSizeMap
69 qcrypto_block_luks_cipher_size_map_aes[] = {
70 { 16, QCRYPTO_CIPHER_ALG_AES_128 },
71 { 24, QCRYPTO_CIPHER_ALG_AES_192 },
72 { 32, QCRYPTO_CIPHER_ALG_AES_256 },
73 { 0, 0 },
74 };
75
76 static const QCryptoBlockLUKSCipherSizeMap
77 qcrypto_block_luks_cipher_size_map_cast5[] = {
78 { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
79 { 0, 0 },
80 };
81
82 static const QCryptoBlockLUKSCipherSizeMap
83 qcrypto_block_luks_cipher_size_map_serpent[] = {
84 { 16, QCRYPTO_CIPHER_ALG_SERPENT_128 },
85 { 24, QCRYPTO_CIPHER_ALG_SERPENT_192 },
86 { 32, QCRYPTO_CIPHER_ALG_SERPENT_256 },
87 { 0, 0 },
88 };
89
90 static const QCryptoBlockLUKSCipherSizeMap
91 qcrypto_block_luks_cipher_size_map_twofish[] = {
92 { 16, QCRYPTO_CIPHER_ALG_TWOFISH_128 },
93 { 24, QCRYPTO_CIPHER_ALG_TWOFISH_192 },
94 { 32, QCRYPTO_CIPHER_ALG_TWOFISH_256 },
95 { 0, 0 },
96 };
97
98 static const QCryptoBlockLUKSCipherNameMap
99 qcrypto_block_luks_cipher_name_map[] = {
100 { "aes", qcrypto_block_luks_cipher_size_map_aes },
101 { "cast5", qcrypto_block_luks_cipher_size_map_cast5 },
102 { "serpent", qcrypto_block_luks_cipher_size_map_serpent },
103 { "twofish", qcrypto_block_luks_cipher_size_map_twofish },
104 };
105
106 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSKeySlot) != 48);
107 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSHeader) != 592);
108
109
110 struct QCryptoBlockLUKS {
111 QCryptoBlockLUKSHeader header;
112
113 /* Main encryption algorithm used for encryption*/
114 QCryptoCipherAlgorithm cipher_alg;
115
116 /* Mode of encryption for the selected encryption algorithm */
117 QCryptoCipherMode cipher_mode;
118
119 /* Initialization vector generation algorithm */
120 QCryptoIVGenAlgorithm ivgen_alg;
121
122 /* Hash algorithm used for IV generation*/
123 QCryptoHashAlgorithm ivgen_hash_alg;
124
125 /*
126 * Encryption algorithm used for IV generation.
127 * Usually the same as main encryption algorithm
128 */
129 QCryptoCipherAlgorithm ivgen_cipher_alg;
130
131 /* Hash algorithm used in pbkdf2 function */
132 QCryptoHashAlgorithm hash_alg;
133
134 /* Name of the secret that was used to open the image */
135 char *secret;
136 };
137
138
139 static int qcrypto_block_luks_cipher_name_lookup(const char *name,
140 QCryptoCipherMode mode,
141 uint32_t key_bytes,
142 Error **errp)
143 {
144 const QCryptoBlockLUKSCipherNameMap *map =
145 qcrypto_block_luks_cipher_name_map;
146 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
147 size_t i, j;
148
149 if (mode == QCRYPTO_CIPHER_MODE_XTS) {
150 key_bytes /= 2;
151 }
152
153 for (i = 0; i < maplen; i++) {
154 if (!g_str_equal(map[i].name, name)) {
155 continue;
156 }
157 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
158 if (map[i].sizes[j].key_bytes == key_bytes) {
159 return map[i].sizes[j].id;
160 }
161 }
162 }
163
164 error_setg(errp, "Algorithm '%s' with key size %d bytes not supported",
165 name, key_bytes);
166 return 0;
167 }
168
169 static const char *
170 qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
171 Error **errp)
172 {
173 const QCryptoBlockLUKSCipherNameMap *map =
174 qcrypto_block_luks_cipher_name_map;
175 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
176 size_t i, j;
177 for (i = 0; i < maplen; i++) {
178 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
179 if (map[i].sizes[j].id == alg) {
180 return map[i].name;
181 }
182 }
183 }
184
185 error_setg(errp, "Algorithm '%s' not supported",
186 QCryptoCipherAlgorithm_str(alg));
187 return NULL;
188 }
189
190 /* XXX replace with qapi_enum_parse() in future, when we can
191 * make that function emit a more friendly error message */
192 static int qcrypto_block_luks_name_lookup(const char *name,
193 const QEnumLookup *map,
194 const char *type,
195 Error **errp)
196 {
197 int ret = qapi_enum_parse(map, name, -1, NULL);
198
199 if (ret < 0) {
200 error_setg(errp, "%s '%s' not supported", type, name);
201 return 0;
202 }
203 return ret;
204 }
205
206 #define qcrypto_block_luks_cipher_mode_lookup(name, errp) \
207 qcrypto_block_luks_name_lookup(name, \
208 &QCryptoCipherMode_lookup, \
209 "Cipher mode", \
210 errp)
211
212 #define qcrypto_block_luks_hash_name_lookup(name, errp) \
213 qcrypto_block_luks_name_lookup(name, \
214 &QCryptoHashAlgorithm_lookup, \
215 "Hash algorithm", \
216 errp)
217
218 #define qcrypto_block_luks_ivgen_name_lookup(name, errp) \
219 qcrypto_block_luks_name_lookup(name, \
220 &QCryptoIVGenAlgorithm_lookup, \
221 "IV generator", \
222 errp)
223
224
225 static bool
226 qcrypto_block_luks_has_format(const uint8_t *buf,
227 size_t buf_size)
228 {
229 const QCryptoBlockLUKSHeader *luks_header = (const void *)buf;
230
231 if (buf_size >= offsetof(QCryptoBlockLUKSHeader, cipher_name) &&
232 memcmp(luks_header->magic, qcrypto_block_luks_magic,
233 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) == 0 &&
234 be16_to_cpu(luks_header->version) == QCRYPTO_BLOCK_LUKS_VERSION) {
235 return true;
236 } else {
237 return false;
238 }
239 }
240
241
242 /**
243 * Deal with a quirk of dm-crypt usage of ESSIV.
244 *
245 * When calculating ESSIV IVs, the cipher length used by ESSIV
246 * may be different from the cipher length used for the block
247 * encryption, because dm-crypt uses the hash digest length
248 * as the key size. ie, if you have AES 128 as the block cipher
249 * and SHA 256 as ESSIV hash, then ESSIV will use AES 256 as
250 * the cipher since that gets a key length matching the digest
251 * size, not AES 128 with truncated digest as might be imagined
252 */
253 static QCryptoCipherAlgorithm
254 qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
255 QCryptoHashAlgorithm hash,
256 Error **errp)
257 {
258 size_t digestlen = qcrypto_hash_digest_len(hash);
259 size_t keylen = qcrypto_cipher_get_key_len(cipher);
260 if (digestlen == keylen) {
261 return cipher;
262 }
263
264 switch (cipher) {
265 case QCRYPTO_CIPHER_ALG_AES_128:
266 case QCRYPTO_CIPHER_ALG_AES_192:
267 case QCRYPTO_CIPHER_ALG_AES_256:
268 if (digestlen == qcrypto_cipher_get_key_len(
269 QCRYPTO_CIPHER_ALG_AES_128)) {
270 return QCRYPTO_CIPHER_ALG_AES_128;
271 } else if (digestlen == qcrypto_cipher_get_key_len(
272 QCRYPTO_CIPHER_ALG_AES_192)) {
273 return QCRYPTO_CIPHER_ALG_AES_192;
274 } else if (digestlen == qcrypto_cipher_get_key_len(
275 QCRYPTO_CIPHER_ALG_AES_256)) {
276 return QCRYPTO_CIPHER_ALG_AES_256;
277 } else {
278 error_setg(errp, "No AES cipher with key size %zu available",
279 digestlen);
280 return 0;
281 }
282 break;
283 case QCRYPTO_CIPHER_ALG_SERPENT_128:
284 case QCRYPTO_CIPHER_ALG_SERPENT_192:
285 case QCRYPTO_CIPHER_ALG_SERPENT_256:
286 if (digestlen == qcrypto_cipher_get_key_len(
287 QCRYPTO_CIPHER_ALG_SERPENT_128)) {
288 return QCRYPTO_CIPHER_ALG_SERPENT_128;
289 } else if (digestlen == qcrypto_cipher_get_key_len(
290 QCRYPTO_CIPHER_ALG_SERPENT_192)) {
291 return QCRYPTO_CIPHER_ALG_SERPENT_192;
292 } else if (digestlen == qcrypto_cipher_get_key_len(
293 QCRYPTO_CIPHER_ALG_SERPENT_256)) {
294 return QCRYPTO_CIPHER_ALG_SERPENT_256;
295 } else {
296 error_setg(errp, "No Serpent cipher with key size %zu available",
297 digestlen);
298 return 0;
299 }
300 break;
301 case QCRYPTO_CIPHER_ALG_TWOFISH_128:
302 case QCRYPTO_CIPHER_ALG_TWOFISH_192:
303 case QCRYPTO_CIPHER_ALG_TWOFISH_256:
304 if (digestlen == qcrypto_cipher_get_key_len(
305 QCRYPTO_CIPHER_ALG_TWOFISH_128)) {
306 return QCRYPTO_CIPHER_ALG_TWOFISH_128;
307 } else if (digestlen == qcrypto_cipher_get_key_len(
308 QCRYPTO_CIPHER_ALG_TWOFISH_192)) {
309 return QCRYPTO_CIPHER_ALG_TWOFISH_192;
310 } else if (digestlen == qcrypto_cipher_get_key_len(
311 QCRYPTO_CIPHER_ALG_TWOFISH_256)) {
312 return QCRYPTO_CIPHER_ALG_TWOFISH_256;
313 } else {
314 error_setg(errp, "No Twofish cipher with key size %zu available",
315 digestlen);
316 return 0;
317 }
318 break;
319 default:
320 error_setg(errp, "Cipher %s not supported with essiv",
321 QCryptoCipherAlgorithm_str(cipher));
322 return 0;
323 }
324 }
325
326 /*
327 * Returns number of sectors needed to store the key material
328 * given number of anti forensic stripes
329 */
330 static int
331 qcrypto_block_luks_splitkeylen_sectors(const QCryptoBlockLUKS *luks,
332 unsigned int header_sectors,
333 unsigned int stripes)
334 {
335 /*
336 * This calculation doesn't match that shown in the spec,
337 * but instead follows the cryptsetup implementation.
338 */
339
340 size_t splitkeylen = luks->header.master_key_len * stripes;
341
342 /* First align the key material size to block size*/
343 size_t splitkeylen_sectors =
344 DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE);
345
346 /* Then also align the key material size to the size of the header */
347 return ROUND_UP(splitkeylen_sectors, header_sectors);
348 }
349
350
351 void
352 qcrypto_block_luks_to_disk_endian(QCryptoBlockLUKSHeader *hdr)
353 {
354 size_t i;
355
356 /*
357 * Everything on disk uses Big Endian (tm), so flip header fields
358 * before writing them
359 */
360 cpu_to_be16s(&hdr->version);
361 cpu_to_be32s(&hdr->payload_offset_sector);
362 cpu_to_be32s(&hdr->master_key_len);
363 cpu_to_be32s(&hdr->master_key_iterations);
364
365 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
366 cpu_to_be32s(&hdr->key_slots[i].active);
367 cpu_to_be32s(&hdr->key_slots[i].iterations);
368 cpu_to_be32s(&hdr->key_slots[i].key_offset_sector);
369 cpu_to_be32s(&hdr->key_slots[i].stripes);
370 }
371 }
372
373 void
374 qcrypto_block_luks_from_disk_endian(QCryptoBlockLUKSHeader *hdr)
375 {
376 size_t i;
377
378 /*
379 * The header is always stored in big-endian format, so
380 * convert everything to native
381 */
382 be16_to_cpus(&hdr->version);
383 be32_to_cpus(&hdr->payload_offset_sector);
384 be32_to_cpus(&hdr->master_key_len);
385 be32_to_cpus(&hdr->master_key_iterations);
386
387 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
388 be32_to_cpus(&hdr->key_slots[i].active);
389 be32_to_cpus(&hdr->key_slots[i].iterations);
390 be32_to_cpus(&hdr->key_slots[i].key_offset_sector);
391 be32_to_cpus(&hdr->key_slots[i].stripes);
392 }
393 }
394
395 /*
396 * Stores the main LUKS header, taking care of endianness
397 */
398 static int
399 qcrypto_block_luks_store_header(QCryptoBlock *block,
400 QCryptoBlockWriteFunc writefunc,
401 void *opaque,
402 Error **errp)
403 {
404 const QCryptoBlockLUKS *luks = block->opaque;
405 Error *local_err = NULL;
406 g_autofree QCryptoBlockLUKSHeader *hdr_copy = NULL;
407
408 /* Create a copy of the header */
409 hdr_copy = g_new0(QCryptoBlockLUKSHeader, 1);
410 memcpy(hdr_copy, &luks->header, sizeof(QCryptoBlockLUKSHeader));
411
412 qcrypto_block_luks_to_disk_endian(hdr_copy);
413
414 /* Write out the partition header and key slot headers */
415 writefunc(block, 0, (const uint8_t *)hdr_copy, sizeof(*hdr_copy),
416 opaque, &local_err);
417
418 if (local_err) {
419 error_propagate(errp, local_err);
420 return -1;
421 }
422 return 0;
423 }
424
425 /*
426 * Loads the main LUKS header, and byteswaps it to native endianness
427 * And run basic sanity checks on it
428 */
429 static int
430 qcrypto_block_luks_load_header(QCryptoBlock *block,
431 QCryptoBlockReadFunc readfunc,
432 void *opaque,
433 Error **errp)
434 {
435 int rv;
436 QCryptoBlockLUKS *luks = block->opaque;
437
438 /*
439 * Read the entire LUKS header, minus the key material from
440 * the underlying device
441 */
442 rv = readfunc(block, 0,
443 (uint8_t *)&luks->header,
444 sizeof(luks->header),
445 opaque,
446 errp);
447 if (rv < 0) {
448 return rv;
449 }
450
451 qcrypto_block_luks_from_disk_endian(&luks->header);
452
453 return 0;
454 }
455
456 /*
457 * Does basic sanity checks on the LUKS header
458 */
459 static int
460 qcrypto_block_luks_check_header(const QCryptoBlockLUKS *luks, Error **errp)
461 {
462 size_t i, j;
463
464 unsigned int header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
465 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
466
467 if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
468 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
469 error_setg(errp, "Volume is not in LUKS format");
470 return -1;
471 }
472
473 if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
474 error_setg(errp, "LUKS version %" PRIu32 " is not supported",
475 luks->header.version);
476 return -1;
477 }
478
479 if (!memchr(luks->header.cipher_name, '\0',
480 sizeof(luks->header.cipher_name))) {
481 error_setg(errp, "LUKS header cipher name is not NUL terminated");
482 return -1;
483 }
484
485 if (!memchr(luks->header.cipher_mode, '\0',
486 sizeof(luks->header.cipher_mode))) {
487 error_setg(errp, "LUKS header cipher mode is not NUL terminated");
488 return -1;
489 }
490
491 if (!memchr(luks->header.hash_spec, '\0',
492 sizeof(luks->header.hash_spec))) {
493 error_setg(errp, "LUKS header hash spec is not NUL terminated");
494 return -1;
495 }
496
497 if (luks->header.payload_offset_sector <
498 DIV_ROUND_UP(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET,
499 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) {
500 error_setg(errp, "LUKS payload is overlapping with the header");
501 return -1;
502 }
503
504 if (luks->header.master_key_iterations == 0) {
505 error_setg(errp, "LUKS key iteration count is zero");
506 return -1;
507 }
508
509 /* Check all keyslots for corruption */
510 for (i = 0 ; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; i++) {
511
512 const QCryptoBlockLUKSKeySlot *slot1 = &luks->header.key_slots[i];
513 unsigned int start1 = slot1->key_offset_sector;
514 unsigned int len1 =
515 qcrypto_block_luks_splitkeylen_sectors(luks,
516 header_sectors,
517 slot1->stripes);
518
519 if (slot1->stripes != QCRYPTO_BLOCK_LUKS_STRIPES) {
520 error_setg(errp, "Keyslot %zu is corrupted (stripes %d != %d)",
521 i, slot1->stripes, QCRYPTO_BLOCK_LUKS_STRIPES);
522 return -1;
523 }
524
525 if (slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED &&
526 slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
527 error_setg(errp,
528 "Keyslot %zu state (active/disable) is corrupted", i);
529 return -1;
530 }
531
532 if (slot1->active == QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED &&
533 slot1->iterations == 0) {
534 error_setg(errp, "Keyslot %zu iteration count is zero", i);
535 return -1;
536 }
537
538 if (start1 < DIV_ROUND_UP(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET,
539 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) {
540 error_setg(errp,
541 "Keyslot %zu is overlapping with the LUKS header",
542 i);
543 return -1;
544 }
545
546 if (start1 + len1 > luks->header.payload_offset_sector) {
547 error_setg(errp,
548 "Keyslot %zu is overlapping with the encrypted payload",
549 i);
550 return -1;
551 }
552
553 for (j = i + 1 ; j < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; j++) {
554 const QCryptoBlockLUKSKeySlot *slot2 = &luks->header.key_slots[j];
555 unsigned int start2 = slot2->key_offset_sector;
556 unsigned int len2 =
557 qcrypto_block_luks_splitkeylen_sectors(luks,
558 header_sectors,
559 slot2->stripes);
560
561 if (start1 + len1 > start2 && start2 + len2 > start1) {
562 error_setg(errp,
563 "Keyslots %zu and %zu are overlapping in the header",
564 i, j);
565 return -1;
566 }
567 }
568
569 }
570 return 0;
571 }
572
573 /*
574 * Parses the crypto parameters that are stored in the LUKS header
575 */
576
577 static int
578 qcrypto_block_luks_parse_header(QCryptoBlockLUKS *luks, Error **errp)
579 {
580 g_autofree char *cipher_mode = g_strdup(luks->header.cipher_mode);
581 char *ivgen_name, *ivhash_name;
582 Error *local_err = NULL;
583
584 /*
585 * The cipher_mode header contains a string that we have
586 * to further parse, of the format
587 *
588 * <cipher-mode>-<iv-generator>[:<iv-hash>]
589 *
590 * eg cbc-essiv:sha256, cbc-plain64
591 */
592 ivgen_name = strchr(cipher_mode, '-');
593 if (!ivgen_name) {
594 error_setg(errp, "Unexpected cipher mode string format '%s'",
595 luks->header.cipher_mode);
596 return -1;
597 }
598 *ivgen_name = '\0';
599 ivgen_name++;
600
601 ivhash_name = strchr(ivgen_name, ':');
602 if (!ivhash_name) {
603 luks->ivgen_hash_alg = 0;
604 } else {
605 *ivhash_name = '\0';
606 ivhash_name++;
607
608 luks->ivgen_hash_alg = qcrypto_block_luks_hash_name_lookup(ivhash_name,
609 &local_err);
610 if (local_err) {
611 error_propagate(errp, local_err);
612 return -1;
613 }
614 }
615
616 luks->cipher_mode = qcrypto_block_luks_cipher_mode_lookup(cipher_mode,
617 &local_err);
618 if (local_err) {
619 error_propagate(errp, local_err);
620 return -1;
621 }
622
623 luks->cipher_alg =
624 qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
625 luks->cipher_mode,
626 luks->header.master_key_len,
627 &local_err);
628 if (local_err) {
629 error_propagate(errp, local_err);
630 return -1;
631 }
632
633 luks->hash_alg =
634 qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
635 &local_err);
636 if (local_err) {
637 error_propagate(errp, local_err);
638 return -1;
639 }
640
641 luks->ivgen_alg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
642 &local_err);
643 if (local_err) {
644 error_propagate(errp, local_err);
645 return -1;
646 }
647
648 if (luks->ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
649 if (!ivhash_name) {
650 error_setg(errp, "Missing IV generator hash specification");
651 return -1;
652 }
653 luks->ivgen_cipher_alg =
654 qcrypto_block_luks_essiv_cipher(luks->cipher_alg,
655 luks->ivgen_hash_alg,
656 &local_err);
657 if (local_err) {
658 error_propagate(errp, local_err);
659 return -1;
660 }
661 } else {
662
663 /*
664 * Note we parsed the ivhash_name earlier in the cipher_mode
665 * spec string even with plain/plain64 ivgens, but we
666 * will ignore it, since it is irrelevant for these ivgens.
667 * This is for compat with dm-crypt which will silently
668 * ignore hash names with these ivgens rather than report
669 * an error about the invalid usage
670 */
671 luks->ivgen_cipher_alg = luks->cipher_alg;
672 }
673 return 0;
674 }
675
676 /*
677 * Given a key slot, user password, and the master key,
678 * will store the encrypted master key there, and update the
679 * in-memory header. User must then write the in-memory header
680 *
681 * Returns:
682 * 0 if the keyslot was written successfully
683 * with the provided password
684 * -1 if a fatal error occurred while storing the key
685 */
686 static int
687 qcrypto_block_luks_store_key(QCryptoBlock *block,
688 unsigned int slot_idx,
689 const char *password,
690 uint8_t *masterkey,
691 uint64_t iter_time,
692 QCryptoBlockWriteFunc writefunc,
693 void *opaque,
694 Error **errp)
695 {
696 QCryptoBlockLUKS *luks = block->opaque;
697 QCryptoBlockLUKSKeySlot *slot;
698 g_autofree uint8_t *splitkey = NULL;
699 size_t splitkeylen;
700 g_autofree uint8_t *slotkey = NULL;
701 g_autoptr(QCryptoCipher) cipher = NULL;
702 g_autoptr(QCryptoIVGen) ivgen = NULL;
703 Error *local_err = NULL;
704 uint64_t iters;
705 int ret = -1;
706
707 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
708 slot = &luks->header.key_slots[slot_idx];
709 splitkeylen = luks->header.master_key_len * slot->stripes;
710
711 if (qcrypto_random_bytes(slot->salt,
712 QCRYPTO_BLOCK_LUKS_SALT_LEN,
713 errp) < 0) {
714 goto cleanup;
715 }
716
717 /*
718 * Determine how many iterations are required to
719 * hash the user password while consuming 1 second of compute
720 * time
721 */
722 iters = qcrypto_pbkdf2_count_iters(luks->hash_alg,
723 (uint8_t *)password, strlen(password),
724 slot->salt,
725 QCRYPTO_BLOCK_LUKS_SALT_LEN,
726 luks->header.master_key_len,
727 &local_err);
728 if (local_err) {
729 error_propagate(errp, local_err);
730 goto cleanup;
731 }
732
733 if (iters > (ULLONG_MAX / iter_time)) {
734 error_setg_errno(errp, ERANGE,
735 "PBKDF iterations %llu too large to scale",
736 (unsigned long long)iters);
737 goto cleanup;
738 }
739
740 /* iter_time was in millis, but count_iters reported for secs */
741 iters = iters * iter_time / 1000;
742
743 if (iters > UINT32_MAX) {
744 error_setg_errno(errp, ERANGE,
745 "PBKDF iterations %llu larger than %u",
746 (unsigned long long)iters, UINT32_MAX);
747 goto cleanup;
748 }
749
750 slot->iterations =
751 MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
752
753
754 /*
755 * Generate a key that we'll use to encrypt the master
756 * key, from the user's password
757 */
758 slotkey = g_new0(uint8_t, luks->header.master_key_len);
759 if (qcrypto_pbkdf2(luks->hash_alg,
760 (uint8_t *)password, strlen(password),
761 slot->salt,
762 QCRYPTO_BLOCK_LUKS_SALT_LEN,
763 slot->iterations,
764 slotkey, luks->header.master_key_len,
765 errp) < 0) {
766 goto cleanup;
767 }
768
769
770 /*
771 * Setup the encryption objects needed to encrypt the
772 * master key material
773 */
774 cipher = qcrypto_cipher_new(luks->cipher_alg,
775 luks->cipher_mode,
776 slotkey, luks->header.master_key_len,
777 errp);
778 if (!cipher) {
779 goto cleanup;
780 }
781
782 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
783 luks->ivgen_cipher_alg,
784 luks->ivgen_hash_alg,
785 slotkey, luks->header.master_key_len,
786 errp);
787 if (!ivgen) {
788 goto cleanup;
789 }
790
791 /*
792 * Before storing the master key, we need to vastly
793 * increase its size, as protection against forensic
794 * disk data recovery
795 */
796 splitkey = g_new0(uint8_t, splitkeylen);
797
798 if (qcrypto_afsplit_encode(luks->hash_alg,
799 luks->header.master_key_len,
800 slot->stripes,
801 masterkey,
802 splitkey,
803 errp) < 0) {
804 goto cleanup;
805 }
806
807 /*
808 * Now we encrypt the split master key with the key generated
809 * from the user's password, before storing it
810 */
811 if (qcrypto_block_cipher_encrypt_helper(cipher, block->niv, ivgen,
812 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
813 0,
814 splitkey,
815 splitkeylen,
816 errp) < 0) {
817 goto cleanup;
818 }
819
820 /* Write out the slot's master key material. */
821 if (writefunc(block,
822 slot->key_offset_sector *
823 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
824 splitkey, splitkeylen,
825 opaque,
826 errp) < 0) {
827 goto cleanup;
828 }
829
830 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
831
832 if (qcrypto_block_luks_store_header(block, writefunc, opaque, errp) < 0) {
833 goto cleanup;
834 }
835
836 ret = 0;
837
838 cleanup:
839 if (slotkey) {
840 memset(slotkey, 0, luks->header.master_key_len);
841 }
842 if (splitkey) {
843 memset(splitkey, 0, splitkeylen);
844 }
845 return ret;
846 }
847
848 /*
849 * Given a key slot, and user password, this will attempt to unlock
850 * the master encryption key from the key slot.
851 *
852 * Returns:
853 * 0 if the key slot is disabled, or key could not be decrypted
854 * with the provided password
855 * 1 if the key slot is enabled, and key decrypted successfully
856 * with the provided password
857 * -1 if a fatal error occurred loading the key
858 */
859 static int
860 qcrypto_block_luks_load_key(QCryptoBlock *block,
861 size_t slot_idx,
862 const char *password,
863 uint8_t *masterkey,
864 QCryptoBlockReadFunc readfunc,
865 void *opaque,
866 Error **errp)
867 {
868 QCryptoBlockLUKS *luks = block->opaque;
869 const QCryptoBlockLUKSKeySlot *slot;
870 g_autofree uint8_t *splitkey = NULL;
871 size_t splitkeylen;
872 g_autofree uint8_t *possiblekey = NULL;
873 int rv;
874 g_autoptr(QCryptoCipher) cipher = NULL;
875 uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
876 g_autoptr(QCryptoIVGen) ivgen = NULL;
877 size_t niv;
878
879 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
880 slot = &luks->header.key_slots[slot_idx];
881 if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
882 return 0;
883 }
884
885 splitkeylen = luks->header.master_key_len * slot->stripes;
886 splitkey = g_new0(uint8_t, splitkeylen);
887 possiblekey = g_new0(uint8_t, luks->header.master_key_len);
888
889 /*
890 * The user password is used to generate a (possible)
891 * decryption key. This may or may not successfully
892 * decrypt the master key - we just blindly assume
893 * the key is correct and validate the results of
894 * decryption later.
895 */
896 if (qcrypto_pbkdf2(luks->hash_alg,
897 (const uint8_t *)password, strlen(password),
898 slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
899 slot->iterations,
900 possiblekey, luks->header.master_key_len,
901 errp) < 0) {
902 return -1;
903 }
904
905 /*
906 * We need to read the master key material from the
907 * LUKS key material header. What we're reading is
908 * not the raw master key, but rather the data after
909 * it has been passed through AFSplit and the result
910 * then encrypted.
911 */
912 rv = readfunc(block,
913 slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
914 splitkey, splitkeylen,
915 opaque,
916 errp);
917 if (rv < 0) {
918 return -1;
919 }
920
921
922 /* Setup the cipher/ivgen that we'll use to try to decrypt
923 * the split master key material */
924 cipher = qcrypto_cipher_new(luks->cipher_alg,
925 luks->cipher_mode,
926 possiblekey,
927 luks->header.master_key_len,
928 errp);
929 if (!cipher) {
930 return -1;
931 }
932
933 niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
934 luks->cipher_mode);
935
936 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
937 luks->ivgen_cipher_alg,
938 luks->ivgen_hash_alg,
939 possiblekey,
940 luks->header.master_key_len,
941 errp);
942 if (!ivgen) {
943 return -1;
944 }
945
946
947 /*
948 * The master key needs to be decrypted in the same
949 * way that the block device payload will be decrypted
950 * later. In particular we'll be using the IV generator
951 * to reset the encryption cipher every time the master
952 * key crosses a sector boundary.
953 */
954 if (qcrypto_block_cipher_decrypt_helper(cipher,
955 niv,
956 ivgen,
957 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
958 0,
959 splitkey,
960 splitkeylen,
961 errp) < 0) {
962 return -1;
963 }
964
965 /*
966 * Now we've decrypted the split master key, join
967 * it back together to get the actual master key.
968 */
969 if (qcrypto_afsplit_decode(luks->hash_alg,
970 luks->header.master_key_len,
971 slot->stripes,
972 splitkey,
973 masterkey,
974 errp) < 0) {
975 return -1;
976 }
977
978
979 /*
980 * We still don't know that the masterkey we got is valid,
981 * because we just blindly assumed the user's password
982 * was correct. This is where we now verify it. We are
983 * creating a hash of the master key using PBKDF and
984 * then comparing that to the hash stored in the key slot
985 * header
986 */
987 if (qcrypto_pbkdf2(luks->hash_alg,
988 masterkey,
989 luks->header.master_key_len,
990 luks->header.master_key_salt,
991 QCRYPTO_BLOCK_LUKS_SALT_LEN,
992 luks->header.master_key_iterations,
993 keydigest,
994 G_N_ELEMENTS(keydigest),
995 errp) < 0) {
996 return -1;
997 }
998
999 if (memcmp(keydigest, luks->header.master_key_digest,
1000 QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
1001 /* Success, we got the right master key */
1002 return 1;
1003 }
1004
1005 /* Fail, user's password was not valid for this key slot,
1006 * tell caller to try another slot */
1007 return 0;
1008 }
1009
1010
1011 /*
1012 * Given a user password, this will iterate over all key
1013 * slots and try to unlock each active key slot using the
1014 * password until it successfully obtains a master key.
1015 *
1016 * Returns 0 if a key was loaded, -1 if no keys could be loaded
1017 */
1018 static int
1019 qcrypto_block_luks_find_key(QCryptoBlock *block,
1020 const char *password,
1021 uint8_t *masterkey,
1022 QCryptoBlockReadFunc readfunc,
1023 void *opaque,
1024 Error **errp)
1025 {
1026 size_t i;
1027 int rv;
1028
1029 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1030 rv = qcrypto_block_luks_load_key(block,
1031 i,
1032 password,
1033 masterkey,
1034 readfunc,
1035 opaque,
1036 errp);
1037 if (rv < 0) {
1038 goto error;
1039 }
1040 if (rv == 1) {
1041 return 0;
1042 }
1043 }
1044
1045 error_setg(errp, "Invalid password, cannot unlock any keyslot");
1046 error:
1047 return -1;
1048 }
1049
1050 /*
1051 * Returns true if a slot i is marked as active
1052 * (contains encrypted copy of the master key)
1053 */
1054 static bool
1055 qcrypto_block_luks_slot_active(const QCryptoBlockLUKS *luks,
1056 unsigned int slot_idx)
1057 {
1058 uint32_t val;
1059
1060 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1061 val = luks->header.key_slots[slot_idx].active;
1062 return val == QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
1063 }
1064
1065 /*
1066 * Returns the number of slots that are marked as active
1067 * (slots that contain encrypted copy of the master key)
1068 */
1069 static unsigned int
1070 qcrypto_block_luks_count_active_slots(const QCryptoBlockLUKS *luks)
1071 {
1072 size_t i = 0;
1073 unsigned int ret = 0;
1074
1075 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1076 if (qcrypto_block_luks_slot_active(luks, i)) {
1077 ret++;
1078 }
1079 }
1080 return ret;
1081 }
1082
1083 /*
1084 * Finds first key slot which is not active
1085 * Returns the key slot index, or -1 if it doesn't exist
1086 */
1087 static int
1088 qcrypto_block_luks_find_free_keyslot(const QCryptoBlockLUKS *luks)
1089 {
1090 size_t i;
1091
1092 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1093 if (!qcrypto_block_luks_slot_active(luks, i)) {
1094 return i;
1095 }
1096 }
1097 return -1;
1098 }
1099
1100 /*
1101 * Erases an keyslot given its index
1102 * Returns:
1103 * 0 if the keyslot was erased successfully
1104 * -1 if a error occurred while erasing the keyslot
1105 *
1106 */
1107 static int
1108 qcrypto_block_luks_erase_key(QCryptoBlock *block,
1109 unsigned int slot_idx,
1110 QCryptoBlockWriteFunc writefunc,
1111 void *opaque,
1112 Error **errp)
1113 {
1114 QCryptoBlockLUKS *luks = block->opaque;
1115 QCryptoBlockLUKSKeySlot *slot;
1116 g_autofree uint8_t *garbagesplitkey = NULL;
1117 size_t splitkeylen;
1118 size_t i;
1119 Error *local_err = NULL;
1120 int ret;
1121
1122 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1123 slot = &luks->header.key_slots[slot_idx];
1124
1125 splitkeylen = luks->header.master_key_len * slot->stripes;
1126 assert(splitkeylen > 0);
1127
1128 garbagesplitkey = g_new0(uint8_t, splitkeylen);
1129
1130 /* Reset the key slot header */
1131 memset(slot->salt, 0, QCRYPTO_BLOCK_LUKS_SALT_LEN);
1132 slot->iterations = 0;
1133 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1134
1135 ret = qcrypto_block_luks_store_header(block, writefunc,
1136 opaque, &local_err);
1137
1138 if (ret < 0) {
1139 error_propagate(errp, local_err);
1140 }
1141 /*
1142 * Now try to erase the key material, even if the header
1143 * update failed
1144 */
1145 for (i = 0; i < QCRYPTO_BLOCK_LUKS_ERASE_ITERATIONS; i++) {
1146 if (qcrypto_random_bytes(garbagesplitkey,
1147 splitkeylen, &local_err) < 0) {
1148 /*
1149 * If we failed to get the random data, still write
1150 * at least zeros to the key slot at least once
1151 */
1152 error_propagate(errp, local_err);
1153
1154 if (i > 0) {
1155 return -1;
1156 }
1157 }
1158 if (writefunc(block,
1159 slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1160 garbagesplitkey,
1161 splitkeylen,
1162 opaque,
1163 &local_err) < 0) {
1164 error_propagate(errp, local_err);
1165 return -1;
1166 }
1167 }
1168 return ret;
1169 }
1170
1171 static int
1172 qcrypto_block_luks_open(QCryptoBlock *block,
1173 QCryptoBlockOpenOptions *options,
1174 const char *optprefix,
1175 QCryptoBlockReadFunc readfunc,
1176 void *opaque,
1177 unsigned int flags,
1178 size_t n_threads,
1179 Error **errp)
1180 {
1181 QCryptoBlockLUKS *luks = NULL;
1182 g_autofree uint8_t *masterkey = NULL;
1183 g_autofree char *password = NULL;
1184
1185 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1186 if (!options->u.luks.key_secret) {
1187 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1188 optprefix ? optprefix : "");
1189 return -1;
1190 }
1191 password = qcrypto_secret_lookup_as_utf8(
1192 options->u.luks.key_secret, errp);
1193 if (!password) {
1194 return -1;
1195 }
1196 }
1197
1198 luks = g_new0(QCryptoBlockLUKS, 1);
1199 block->opaque = luks;
1200 luks->secret = g_strdup(options->u.luks.key_secret);
1201
1202 if (qcrypto_block_luks_load_header(block, readfunc, opaque, errp) < 0) {
1203 goto fail;
1204 }
1205
1206 if (qcrypto_block_luks_check_header(luks, errp) < 0) {
1207 goto fail;
1208 }
1209
1210 if (qcrypto_block_luks_parse_header(luks, errp) < 0) {
1211 goto fail;
1212 }
1213
1214 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1215 /* Try to find which key slot our password is valid for
1216 * and unlock the master key from that slot.
1217 */
1218
1219 masterkey = g_new0(uint8_t, luks->header.master_key_len);
1220
1221 if (qcrypto_block_luks_find_key(block,
1222 password,
1223 masterkey,
1224 readfunc, opaque,
1225 errp) < 0) {
1226 goto fail;
1227 }
1228
1229 /* We have a valid master key now, so can setup the
1230 * block device payload decryption objects
1231 */
1232 block->kdfhash = luks->hash_alg;
1233 block->niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
1234 luks->cipher_mode);
1235
1236 block->ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
1237 luks->ivgen_cipher_alg,
1238 luks->ivgen_hash_alg,
1239 masterkey,
1240 luks->header.master_key_len,
1241 errp);
1242 if (!block->ivgen) {
1243 goto fail;
1244 }
1245
1246 if (qcrypto_block_init_cipher(block,
1247 luks->cipher_alg,
1248 luks->cipher_mode,
1249 masterkey,
1250 luks->header.master_key_len,
1251 n_threads,
1252 errp) < 0) {
1253 goto fail;
1254 }
1255 }
1256
1257 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1258 block->payload_offset = luks->header.payload_offset_sector *
1259 block->sector_size;
1260
1261 return 0;
1262
1263 fail:
1264 qcrypto_block_free_cipher(block);
1265 qcrypto_ivgen_free(block->ivgen);
1266 g_free(luks->secret);
1267 g_free(luks);
1268 return -1;
1269 }
1270
1271
1272 static void
1273 qcrypto_block_luks_uuid_gen(uint8_t *uuidstr)
1274 {
1275 QemuUUID uuid;
1276 qemu_uuid_generate(&uuid);
1277 qemu_uuid_unparse(&uuid, (char *)uuidstr);
1278 }
1279
1280 static int
1281 qcrypto_block_luks_create(QCryptoBlock *block,
1282 QCryptoBlockCreateOptions *options,
1283 const char *optprefix,
1284 QCryptoBlockInitFunc initfunc,
1285 QCryptoBlockWriteFunc writefunc,
1286 void *opaque,
1287 Error **errp)
1288 {
1289 QCryptoBlockLUKS *luks;
1290 QCryptoBlockCreateOptionsLUKS luks_opts;
1291 Error *local_err = NULL;
1292 g_autofree uint8_t *masterkey = NULL;
1293 size_t header_sectors;
1294 size_t split_key_sectors;
1295 size_t i;
1296 g_autofree char *password = NULL;
1297 const char *cipher_alg;
1298 const char *cipher_mode;
1299 const char *ivgen_alg;
1300 const char *ivgen_hash_alg = NULL;
1301 const char *hash_alg;
1302 g_autofree char *cipher_mode_spec = NULL;
1303 uint64_t iters;
1304
1305 memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
1306 if (!luks_opts.has_iter_time) {
1307 luks_opts.iter_time = QCRYPTO_BLOCK_LUKS_DEFAULT_ITER_TIME_MS;
1308 }
1309 if (!luks_opts.has_cipher_alg) {
1310 luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
1311 }
1312 if (!luks_opts.has_cipher_mode) {
1313 luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
1314 }
1315 if (!luks_opts.has_ivgen_alg) {
1316 luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
1317 }
1318 if (!luks_opts.has_hash_alg) {
1319 luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
1320 }
1321 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1322 if (!luks_opts.has_ivgen_hash_alg) {
1323 luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
1324 luks_opts.has_ivgen_hash_alg = true;
1325 }
1326 }
1327
1328 luks = g_new0(QCryptoBlockLUKS, 1);
1329 block->opaque = luks;
1330
1331 luks->cipher_alg = luks_opts.cipher_alg;
1332 luks->cipher_mode = luks_opts.cipher_mode;
1333 luks->ivgen_alg = luks_opts.ivgen_alg;
1334 luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
1335 luks->hash_alg = luks_opts.hash_alg;
1336
1337
1338 /* Note we're allowing ivgen_hash_alg to be set even for
1339 * non-essiv iv generators that don't need a hash. It will
1340 * be silently ignored, for compatibility with dm-crypt */
1341
1342 if (!options->u.luks.key_secret) {
1343 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1344 optprefix ? optprefix : "");
1345 goto error;
1346 }
1347 luks->secret = g_strdup(options->u.luks.key_secret);
1348
1349 password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
1350 if (!password) {
1351 goto error;
1352 }
1353
1354
1355 memcpy(luks->header.magic, qcrypto_block_luks_magic,
1356 QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
1357
1358 /* We populate the header in native endianness initially and
1359 * then convert everything to big endian just before writing
1360 * it out to disk
1361 */
1362 luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
1363 qcrypto_block_luks_uuid_gen(luks->header.uuid);
1364
1365 cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
1366 errp);
1367 if (!cipher_alg) {
1368 goto error;
1369 }
1370
1371 cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
1372 ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
1373 if (luks_opts.has_ivgen_hash_alg) {
1374 ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
1375 cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
1376 ivgen_hash_alg);
1377 } else {
1378 cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
1379 }
1380 hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
1381
1382
1383 if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
1384 error_setg(errp, "Cipher name '%s' is too long for LUKS header",
1385 cipher_alg);
1386 goto error;
1387 }
1388 if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
1389 error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
1390 cipher_mode_spec);
1391 goto error;
1392 }
1393 if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
1394 error_setg(errp, "Hash name '%s' is too long for LUKS header",
1395 hash_alg);
1396 goto error;
1397 }
1398
1399 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1400 luks->ivgen_cipher_alg =
1401 qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
1402 luks_opts.ivgen_hash_alg,
1403 &local_err);
1404 if (local_err) {
1405 error_propagate(errp, local_err);
1406 goto error;
1407 }
1408 } else {
1409 luks->ivgen_cipher_alg = luks_opts.cipher_alg;
1410 }
1411
1412 strcpy(luks->header.cipher_name, cipher_alg);
1413 strcpy(luks->header.cipher_mode, cipher_mode_spec);
1414 strcpy(luks->header.hash_spec, hash_alg);
1415
1416 luks->header.master_key_len =
1417 qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
1418
1419 if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
1420 luks->header.master_key_len *= 2;
1421 }
1422
1423 /* Generate the salt used for hashing the master key
1424 * with PBKDF later
1425 */
1426 if (qcrypto_random_bytes(luks->header.master_key_salt,
1427 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1428 errp) < 0) {
1429 goto error;
1430 }
1431
1432 /* Generate random master key */
1433 masterkey = g_new0(uint8_t, luks->header.master_key_len);
1434 if (qcrypto_random_bytes(masterkey,
1435 luks->header.master_key_len, errp) < 0) {
1436 goto error;
1437 }
1438
1439
1440 /* Setup the block device payload encryption objects */
1441 if (qcrypto_block_init_cipher(block, luks_opts.cipher_alg,
1442 luks_opts.cipher_mode, masterkey,
1443 luks->header.master_key_len, 1, errp) < 0) {
1444 goto error;
1445 }
1446
1447 block->kdfhash = luks_opts.hash_alg;
1448 block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1449 luks_opts.cipher_mode);
1450 block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1451 luks->ivgen_cipher_alg,
1452 luks_opts.ivgen_hash_alg,
1453 masterkey, luks->header.master_key_len,
1454 errp);
1455
1456 if (!block->ivgen) {
1457 goto error;
1458 }
1459
1460
1461 /* Determine how many iterations we need to hash the master
1462 * key, in order to have 1 second of compute time used
1463 */
1464 iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1465 masterkey, luks->header.master_key_len,
1466 luks->header.master_key_salt,
1467 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1468 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1469 &local_err);
1470 if (local_err) {
1471 error_propagate(errp, local_err);
1472 goto error;
1473 }
1474
1475 if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1476 error_setg_errno(errp, ERANGE,
1477 "PBKDF iterations %llu too large to scale",
1478 (unsigned long long)iters);
1479 goto error;
1480 }
1481
1482 /* iter_time was in millis, but count_iters reported for secs */
1483 iters = iters * luks_opts.iter_time / 1000;
1484
1485 /* Why /= 8 ? That matches cryptsetup, but there's no
1486 * explanation why they chose /= 8... Probably so that
1487 * if all 8 keyslots are active we only spend 1 second
1488 * in total time to check all keys */
1489 iters /= 8;
1490 if (iters > UINT32_MAX) {
1491 error_setg_errno(errp, ERANGE,
1492 "PBKDF iterations %llu larger than %u",
1493 (unsigned long long)iters, UINT32_MAX);
1494 goto error;
1495 }
1496 iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1497 luks->header.master_key_iterations = iters;
1498
1499 /* Hash the master key, saving the result in the LUKS
1500 * header. This hash is used when opening the encrypted
1501 * device to verify that the user password unlocked a
1502 * valid master key
1503 */
1504 if (qcrypto_pbkdf2(luks_opts.hash_alg,
1505 masterkey, luks->header.master_key_len,
1506 luks->header.master_key_salt,
1507 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1508 luks->header.master_key_iterations,
1509 luks->header.master_key_digest,
1510 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1511 errp) < 0) {
1512 goto error;
1513 }
1514
1515 /* start with the sector that follows the header*/
1516 header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1517 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1518
1519 split_key_sectors =
1520 qcrypto_block_luks_splitkeylen_sectors(luks,
1521 header_sectors,
1522 QCRYPTO_BLOCK_LUKS_STRIPES);
1523
1524 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1525 QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[i];
1526 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1527
1528 slot->key_offset_sector = header_sectors + i * split_key_sectors;
1529 slot->stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
1530 }
1531
1532 /* The total size of the LUKS headers is the partition header + key
1533 * slot headers, rounded up to the nearest sector, combined with
1534 * the size of each master key material region, also rounded up
1535 * to the nearest sector */
1536 luks->header.payload_offset_sector = header_sectors +
1537 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS * split_key_sectors;
1538
1539 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1540 block->payload_offset = luks->header.payload_offset_sector *
1541 block->sector_size;
1542
1543 /* Reserve header space to match payload offset */
1544 initfunc(block, block->payload_offset, opaque, &local_err);
1545 if (local_err) {
1546 error_propagate(errp, local_err);
1547 goto error;
1548 }
1549
1550
1551 /* populate the slot 0 with the password encrypted master key*/
1552 /* This will also store the header */
1553 if (qcrypto_block_luks_store_key(block,
1554 0,
1555 password,
1556 masterkey,
1557 luks_opts.iter_time,
1558 writefunc,
1559 opaque,
1560 errp) < 0) {
1561 goto error;
1562 }
1563
1564 memset(masterkey, 0, luks->header.master_key_len);
1565
1566 return 0;
1567
1568 error:
1569 if (masterkey) {
1570 memset(masterkey, 0, luks->header.master_key_len);
1571 }
1572
1573 qcrypto_block_free_cipher(block);
1574 qcrypto_ivgen_free(block->ivgen);
1575
1576 g_free(luks->secret);
1577 g_free(luks);
1578 return -1;
1579 }
1580
1581 static int
1582 qcrypto_block_luks_amend_add_keyslot(QCryptoBlock *block,
1583 QCryptoBlockReadFunc readfunc,
1584 QCryptoBlockWriteFunc writefunc,
1585 void *opaque,
1586 QCryptoBlockAmendOptionsLUKS *opts_luks,
1587 bool force,
1588 Error **errp)
1589 {
1590 QCryptoBlockLUKS *luks = block->opaque;
1591 uint64_t iter_time = opts_luks->has_iter_time ?
1592 opts_luks->iter_time :
1593 QCRYPTO_BLOCK_LUKS_DEFAULT_ITER_TIME_MS;
1594 int keyslot;
1595 g_autofree char *old_password = NULL;
1596 g_autofree char *new_password = NULL;
1597 g_autofree uint8_t *master_key = NULL;
1598
1599 char *secret = opts_luks->secret ?: luks->secret;
1600
1601 if (!opts_luks->new_secret) {
1602 error_setg(errp, "'new-secret' is required to activate a keyslot");
1603 return -1;
1604 }
1605 if (opts_luks->old_secret) {
1606 error_setg(errp,
1607 "'old-secret' must not be given when activating keyslots");
1608 return -1;
1609 }
1610
1611 if (opts_luks->has_keyslot) {
1612 keyslot = opts_luks->keyslot;
1613 if (keyslot < 0 || keyslot >= QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS) {
1614 error_setg(errp,
1615 "Invalid keyslot %u specified, must be between 0 and %u",
1616 keyslot, QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS - 1);
1617 return -1;
1618 }
1619 } else {
1620 keyslot = qcrypto_block_luks_find_free_keyslot(luks);
1621 if (keyslot == -1) {
1622 error_setg(errp,
1623 "Can't add a keyslot - all keyslots are in use");
1624 return -1;
1625 }
1626 }
1627
1628 if (!force && qcrypto_block_luks_slot_active(luks, keyslot)) {
1629 error_setg(errp,
1630 "Refusing to overwrite active keyslot %i - "
1631 "please erase it first",
1632 keyslot);
1633 return -1;
1634 }
1635
1636 /* Locate the password that will be used to retrieve the master key */
1637 old_password = qcrypto_secret_lookup_as_utf8(secret, errp);
1638 if (!old_password) {
1639 return -1;
1640 }
1641
1642 /* Retrieve the master key */
1643 master_key = g_new0(uint8_t, luks->header.master_key_len);
1644
1645 if (qcrypto_block_luks_find_key(block, old_password, master_key,
1646 readfunc, opaque, errp) < 0) {
1647 error_append_hint(errp, "Failed to retrieve the master key");
1648 return -1;
1649 }
1650
1651 /* Locate the new password*/
1652 new_password = qcrypto_secret_lookup_as_utf8(opts_luks->new_secret, errp);
1653 if (!new_password) {
1654 return -1;
1655 }
1656
1657 /* Now set the new keyslots */
1658 if (qcrypto_block_luks_store_key(block, keyslot, new_password, master_key,
1659 iter_time, writefunc, opaque, errp)) {
1660 error_append_hint(errp, "Failed to write to keyslot %i", keyslot);
1661 return -1;
1662 }
1663 return 0;
1664 }
1665
1666 static int
1667 qcrypto_block_luks_amend_erase_keyslots(QCryptoBlock *block,
1668 QCryptoBlockReadFunc readfunc,
1669 QCryptoBlockWriteFunc writefunc,
1670 void *opaque,
1671 QCryptoBlockAmendOptionsLUKS *opts_luks,
1672 bool force,
1673 Error **errp)
1674 {
1675 QCryptoBlockLUKS *luks = block->opaque;
1676 g_autofree uint8_t *tmpkey = NULL;
1677 g_autofree char *old_password = NULL;
1678
1679 if (opts_luks->new_secret) {
1680 error_setg(errp,
1681 "'new-secret' must not be given when erasing keyslots");
1682 return -1;
1683 }
1684 if (opts_luks->has_iter_time) {
1685 error_setg(errp,
1686 "'iter-time' must not be given when erasing keyslots");
1687 return -1;
1688 }
1689 if (opts_luks->secret) {
1690 error_setg(errp,
1691 "'secret' must not be given when erasing keyslots");
1692 return -1;
1693 }
1694
1695 /* Load the old password if given */
1696 if (opts_luks->old_secret) {
1697 old_password = qcrypto_secret_lookup_as_utf8(opts_luks->old_secret,
1698 errp);
1699 if (!old_password) {
1700 return -1;
1701 }
1702
1703 /*
1704 * Allocate a temporary key buffer that we will need when
1705 * checking if slot matches the given old password
1706 */
1707 tmpkey = g_new0(uint8_t, luks->header.master_key_len);
1708 }
1709
1710 /* Erase an explicitly given keyslot */
1711 if (opts_luks->has_keyslot) {
1712 int keyslot = opts_luks->keyslot;
1713
1714 if (keyslot < 0 || keyslot >= QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS) {
1715 error_setg(errp,
1716 "Invalid keyslot %i specified, must be between 0 and %i",
1717 keyslot, QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS - 1);
1718 return -1;
1719 }
1720
1721 if (opts_luks->old_secret) {
1722 int rv = qcrypto_block_luks_load_key(block,
1723 keyslot,
1724 old_password,
1725 tmpkey,
1726 readfunc,
1727 opaque,
1728 errp);
1729 if (rv == -1) {
1730 return -1;
1731 } else if (rv == 0) {
1732 error_setg(errp,
1733 "Given keyslot %i doesn't contain the given "
1734 "old password for erase operation",
1735 keyslot);
1736 return -1;
1737 }
1738 }
1739
1740 if (!force && !qcrypto_block_luks_slot_active(luks, keyslot)) {
1741 error_setg(errp,
1742 "Given keyslot %i is already erased (inactive) ",
1743 keyslot);
1744 return -1;
1745 }
1746
1747 if (!force && qcrypto_block_luks_count_active_slots(luks) == 1) {
1748 error_setg(errp,
1749 "Attempt to erase the only active keyslot %i "
1750 "which will erase all the data in the image "
1751 "irreversibly - refusing operation",
1752 keyslot);
1753 return -1;
1754 }
1755
1756 if (qcrypto_block_luks_erase_key(block, keyslot,
1757 writefunc, opaque, errp)) {
1758 error_append_hint(errp, "Failed to erase keyslot %i", keyslot);
1759 return -1;
1760 }
1761
1762 /* Erase all keyslots that match the given old password */
1763 } else if (opts_luks->old_secret) {
1764
1765 unsigned long slots_to_erase_bitmap = 0;
1766 size_t i;
1767 int slot_count;
1768
1769 assert(QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS <=
1770 sizeof(slots_to_erase_bitmap) * 8);
1771
1772 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1773 int rv = qcrypto_block_luks_load_key(block,
1774 i,
1775 old_password,
1776 tmpkey,
1777 readfunc,
1778 opaque,
1779 errp);
1780 if (rv == -1) {
1781 return -1;
1782 } else if (rv == 1) {
1783 bitmap_set(&slots_to_erase_bitmap, i, 1);
1784 }
1785 }
1786
1787 slot_count = bitmap_count_one(&slots_to_erase_bitmap,
1788 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1789 if (slot_count == 0) {
1790 error_setg(errp,
1791 "No keyslots match given (old) password for erase operation");
1792 return -1;
1793 }
1794
1795 if (!force &&
1796 slot_count == qcrypto_block_luks_count_active_slots(luks)) {
1797 error_setg(errp,
1798 "All the active keyslots match the (old) password that "
1799 "was given and erasing them will erase all the data in "
1800 "the image irreversibly - refusing operation");
1801 return -1;
1802 }
1803
1804 /* Now apply the update */
1805 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1806 if (!test_bit(i, &slots_to_erase_bitmap)) {
1807 continue;
1808 }
1809 if (qcrypto_block_luks_erase_key(block, i, writefunc,
1810 opaque, errp)) {
1811 error_append_hint(errp, "Failed to erase keyslot %zu", i);
1812 return -1;
1813 }
1814 }
1815 } else {
1816 error_setg(errp,
1817 "To erase keyslot(s), either explicit keyslot index "
1818 "or the password currently contained in them must be given");
1819 return -1;
1820 }
1821 return 0;
1822 }
1823
1824 static int
1825 qcrypto_block_luks_amend_options(QCryptoBlock *block,
1826 QCryptoBlockReadFunc readfunc,
1827 QCryptoBlockWriteFunc writefunc,
1828 void *opaque,
1829 QCryptoBlockAmendOptions *options,
1830 bool force,
1831 Error **errp)
1832 {
1833 QCryptoBlockAmendOptionsLUKS *opts_luks = &options->u.luks;
1834
1835 switch (opts_luks->state) {
1836 case Q_CRYPTO_BLOCKLUKS_KEYSLOT_STATE_ACTIVE:
1837 return qcrypto_block_luks_amend_add_keyslot(block, readfunc,
1838 writefunc, opaque,
1839 opts_luks, force, errp);
1840 case Q_CRYPTO_BLOCKLUKS_KEYSLOT_STATE_INACTIVE:
1841 return qcrypto_block_luks_amend_erase_keyslots(block, readfunc,
1842 writefunc, opaque,
1843 opts_luks, force, errp);
1844 default:
1845 g_assert_not_reached();
1846 }
1847 }
1848
1849 static int qcrypto_block_luks_get_info(QCryptoBlock *block,
1850 QCryptoBlockInfo *info,
1851 Error **errp)
1852 {
1853 QCryptoBlockLUKS *luks = block->opaque;
1854 QCryptoBlockInfoLUKSSlot *slot;
1855 QCryptoBlockInfoLUKSSlotList **tail = &info->u.luks.slots;
1856 size_t i;
1857
1858 info->u.luks.cipher_alg = luks->cipher_alg;
1859 info->u.luks.cipher_mode = luks->cipher_mode;
1860 info->u.luks.ivgen_alg = luks->ivgen_alg;
1861 if (info->u.luks.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1862 info->u.luks.has_ivgen_hash_alg = true;
1863 info->u.luks.ivgen_hash_alg = luks->ivgen_hash_alg;
1864 }
1865 info->u.luks.hash_alg = luks->hash_alg;
1866 info->u.luks.payload_offset = block->payload_offset;
1867 info->u.luks.master_key_iters = luks->header.master_key_iterations;
1868 info->u.luks.uuid = g_strndup((const char *)luks->header.uuid,
1869 sizeof(luks->header.uuid));
1870
1871 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1872 slot = g_new0(QCryptoBlockInfoLUKSSlot, 1);
1873 slot->active = luks->header.key_slots[i].active ==
1874 QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
1875 slot->key_offset = luks->header.key_slots[i].key_offset_sector
1876 * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1877 if (slot->active) {
1878 slot->has_iters = true;
1879 slot->iters = luks->header.key_slots[i].iterations;
1880 slot->has_stripes = true;
1881 slot->stripes = luks->header.key_slots[i].stripes;
1882 }
1883
1884 QAPI_LIST_APPEND(tail, slot);
1885 }
1886
1887 return 0;
1888 }
1889
1890
1891 static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1892 {
1893 QCryptoBlockLUKS *luks = block->opaque;
1894 if (luks) {
1895 g_free(luks->secret);
1896 g_free(luks);
1897 }
1898 }
1899
1900
1901 static int
1902 qcrypto_block_luks_decrypt(QCryptoBlock *block,
1903 uint64_t offset,
1904 uint8_t *buf,
1905 size_t len,
1906 Error **errp)
1907 {
1908 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1909 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1910 return qcrypto_block_decrypt_helper(block,
1911 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1912 offset, buf, len, errp);
1913 }
1914
1915
1916 static int
1917 qcrypto_block_luks_encrypt(QCryptoBlock *block,
1918 uint64_t offset,
1919 uint8_t *buf,
1920 size_t len,
1921 Error **errp)
1922 {
1923 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1924 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1925 return qcrypto_block_encrypt_helper(block,
1926 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1927 offset, buf, len, errp);
1928 }
1929
1930
1931 const QCryptoBlockDriver qcrypto_block_driver_luks = {
1932 .open = qcrypto_block_luks_open,
1933 .create = qcrypto_block_luks_create,
1934 .amend = qcrypto_block_luks_amend_options,
1935 .get_info = qcrypto_block_luks_get_info,
1936 .cleanup = qcrypto_block_luks_cleanup,
1937 .decrypt = qcrypto_block_luks_decrypt,
1938 .encrypt = qcrypto_block_luks_encrypt,
1939 .has_format = qcrypto_block_luks_has_format,
1940 };