xref: /openbmc/qemu/crypto/block-luks.c (revision 6c35ed68)
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 
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"
32 #include "qemu/uuid.h"
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 
47 typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
48 typedef struct QCryptoBlockLUKSHeader QCryptoBlockLUKSHeader;
49 typedef 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 
73 static const char qcrypto_block_luks_magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN] = {
74     'L', 'U', 'K', 'S', 0xBA, 0xBE
75 };
76 
77 typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
78 struct QCryptoBlockLUKSNameMap {
79     const char *name;
80     int id;
81 };
82 
83 typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
84 struct QCryptoBlockLUKSCipherSizeMap {
85     uint32_t key_bytes;
86     int id;
87 };
88 typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
89 struct QCryptoBlockLUKSCipherNameMap {
90     const char *name;
91     const QCryptoBlockLUKSCipherSizeMap *sizes;
92 };
93 
94 
95 static const QCryptoBlockLUKSCipherSizeMap
96 qcrypto_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 
103 static const QCryptoBlockLUKSCipherSizeMap
104 qcrypto_block_luks_cipher_size_map_cast5[] = {
105     { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
106     { 0, 0 },
107 };
108 
109 static const QCryptoBlockLUKSCipherSizeMap
110 qcrypto_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 
117 static const QCryptoBlockLUKSCipherSizeMap
118 qcrypto_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 
125 static const QCryptoBlockLUKSCipherNameMap
126 qcrypto_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  */
138 struct 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 */
146     uint32_t key_offset_sector;
147     /* number of anti-forensic stripes */
148     uint32_t stripes;
149 };
150 
151 QEMU_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  */
158 struct 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) */
175     uint32_t payload_offset_sector;
176 
177     /* Number of key bytes */
178     uint32_t master_key_len;
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];
194 };
195 
196 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSHeader) != 592);
197 
198 
199 struct QCryptoBlockLUKS {
200     QCryptoBlockLUKSHeader header;
201 
202     /* Main encryption algorithm used for encryption*/
203     QCryptoCipherAlgorithm cipher_alg;
204 
205     /* Mode of encryption for the selected encryption algorithm */
206     QCryptoCipherMode cipher_mode;
207 
208     /* Initialization vector generation algorithm */
209     QCryptoIVGenAlgorithm ivgen_alg;
210 
211     /* Hash algorithm used for IV generation*/
212     QCryptoHashAlgorithm ivgen_hash_alg;
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 */
221     QCryptoHashAlgorithm hash_alg;
222 };
223 
224 
225 static 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 
255 static const char *
256 qcrypto_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",
272                QCryptoCipherAlgorithm_str(alg));
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 */
278 static int qcrypto_block_luks_name_lookup(const char *name,
279                                           const QEnumLookup *map,
280                                           const char *type,
281                                           Error **errp)
282 {
283     int ret = qapi_enum_parse(map, name, -1, NULL);
284 
285     if (ret < 0) {
286         error_setg(errp, "%s %s not supported", type, name);
287         return 0;
288     }
289     return ret;
290 }
291 
292 #define qcrypto_block_luks_cipher_mode_lookup(name, errp)               \
293     qcrypto_block_luks_name_lookup(name,                                \
294                                    &QCryptoCipherMode_lookup,           \
295                                    "Cipher mode",                       \
296                                    errp)
297 
298 #define qcrypto_block_luks_hash_name_lookup(name, errp)                 \
299     qcrypto_block_luks_name_lookup(name,                                \
300                                    &QCryptoHashAlgorithm_lookup,        \
301                                    "Hash algorithm",                    \
302                                    errp)
303 
304 #define qcrypto_block_luks_ivgen_name_lookup(name, errp)                \
305     qcrypto_block_luks_name_lookup(name,                                \
306                                    &QCryptoIVGenAlgorithm_lookup,       \
307                                    "IV generator",                      \
308                                    errp)
309 
310 
311 static bool
312 qcrypto_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  */
339 static QCryptoCipherAlgorithm
340 qcrypto_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",
407                    QCryptoCipherAlgorithm_str(cipher));
408         return 0;
409     }
410 }
411 
412 /*
413  * Returns number of sectors needed to store the key material
414  * given number of anti forensic stripes
415  */
416 static int
417 qcrypto_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 
436 /*
437  * Stores the main LUKS header, taking care of endianess
438  */
439 static int
440 qcrypto_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  */
485 static int
486 qcrypto_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 
527 /*
528  * Does basic sanity checks on the LUKS header
529  */
530 static int
531 qcrypto_block_luks_check_header(const QCryptoBlockLUKS *luks, Error **errp)
532 {
533     size_t i, j;
534 
535     unsigned int header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
536         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
537 
538     if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
539                QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
540         error_setg(errp, "Volume is not in LUKS format");
541         return -1;
542     }
543 
544     if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
545         error_setg(errp, "LUKS version %" PRIu32 " is not supported",
546                    luks->header.version);
547         return -1;
548     }
549 
550     /* Check all keyslots for corruption  */
551     for (i = 0 ; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; i++) {
552 
553         const QCryptoBlockLUKSKeySlot *slot1 = &luks->header.key_slots[i];
554         unsigned int start1 = slot1->key_offset_sector;
555         unsigned int len1 =
556             qcrypto_block_luks_splitkeylen_sectors(luks,
557                                                    header_sectors,
558                                                    slot1->stripes);
559 
560         if (slot1->stripes == 0) {
561             error_setg(errp, "Keyslot %zu is corrupted (stripes == 0)", i);
562             return -1;
563         }
564 
565         if (slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED &&
566             slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
567             error_setg(errp,
568                        "Keyslot %zu state (active/disable) is corrupted", i);
569             return -1;
570         }
571 
572         if (start1 + len1 > luks->header.payload_offset_sector) {
573             error_setg(errp,
574                        "Keyslot %zu is overlapping with the encrypted payload",
575                        i);
576             return -1;
577         }
578 
579         for (j = i + 1 ; j < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; j++) {
580             const QCryptoBlockLUKSKeySlot *slot2 = &luks->header.key_slots[j];
581             unsigned int start2 = slot2->key_offset_sector;
582             unsigned int len2 =
583                 qcrypto_block_luks_splitkeylen_sectors(luks,
584                                                        header_sectors,
585                                                        slot2->stripes);
586 
587             if (start1 + len1 > start2 && start2 + len2 > start1) {
588                 error_setg(errp,
589                            "Keyslots %zu and %zu are overlapping in the header",
590                            i, j);
591                 return -1;
592             }
593         }
594 
595     }
596     return 0;
597 }
598 
599 /*
600  * Parses the crypto parameters that are stored in the LUKS header
601  */
602 
603 static int
604 qcrypto_block_luks_parse_header(QCryptoBlockLUKS *luks, Error **errp)
605 {
606     g_autofree char *cipher_mode = g_strdup(luks->header.cipher_mode);
607     char *ivgen_name, *ivhash_name;
608     Error *local_err = NULL;
609 
610     /*
611      * The cipher_mode header contains a string that we have
612      * to further parse, of the format
613      *
614      *    <cipher-mode>-<iv-generator>[:<iv-hash>]
615      *
616      * eg  cbc-essiv:sha256, cbc-plain64
617      */
618     ivgen_name = strchr(cipher_mode, '-');
619     if (!ivgen_name) {
620         error_setg(errp, "Unexpected cipher mode string format %s",
621                    luks->header.cipher_mode);
622         return -1;
623     }
624     *ivgen_name = '\0';
625     ivgen_name++;
626 
627     ivhash_name = strchr(ivgen_name, ':');
628     if (!ivhash_name) {
629         luks->ivgen_hash_alg = 0;
630     } else {
631         *ivhash_name = '\0';
632         ivhash_name++;
633 
634         luks->ivgen_hash_alg = qcrypto_block_luks_hash_name_lookup(ivhash_name,
635                                                                    &local_err);
636         if (local_err) {
637             error_propagate(errp, local_err);
638             return -1;
639         }
640     }
641 
642     luks->cipher_mode = qcrypto_block_luks_cipher_mode_lookup(cipher_mode,
643                                                               &local_err);
644     if (local_err) {
645         error_propagate(errp, local_err);
646         return -1;
647     }
648 
649     luks->cipher_alg =
650             qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
651                                                   luks->cipher_mode,
652                                                   luks->header.master_key_len,
653                                                   &local_err);
654     if (local_err) {
655         error_propagate(errp, local_err);
656         return -1;
657     }
658 
659     luks->hash_alg =
660             qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
661                                                 &local_err);
662     if (local_err) {
663         error_propagate(errp, local_err);
664         return -1;
665     }
666 
667     luks->ivgen_alg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
668                                                            &local_err);
669     if (local_err) {
670         error_propagate(errp, local_err);
671         return -1;
672     }
673 
674     if (luks->ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
675         if (!ivhash_name) {
676             error_setg(errp, "Missing IV generator hash specification");
677             return -1;
678         }
679         luks->ivgen_cipher_alg =
680                 qcrypto_block_luks_essiv_cipher(luks->cipher_alg,
681                                                 luks->ivgen_hash_alg,
682                                                 &local_err);
683         if (local_err) {
684             error_propagate(errp, local_err);
685             return -1;
686         }
687     } else {
688 
689         /*
690          * Note we parsed the ivhash_name earlier in the cipher_mode
691          * spec string even with plain/plain64 ivgens, but we
692          * will ignore it, since it is irrelevant for these ivgens.
693          * This is for compat with dm-crypt which will silently
694          * ignore hash names with these ivgens rather than report
695          * an error about the invalid usage
696          */
697         luks->ivgen_cipher_alg = luks->cipher_alg;
698     }
699     return 0;
700 }
701 
702 /*
703  * Given a key slot,  user password, and the master key,
704  * will store the encrypted master key there, and update the
705  * in-memory header. User must then write the in-memory header
706  *
707  * Returns:
708  *    0 if the keyslot was written successfully
709  *      with the provided password
710  *   -1 if a fatal error occurred while storing the key
711  */
712 static int
713 qcrypto_block_luks_store_key(QCryptoBlock *block,
714                              unsigned int slot_idx,
715                              const char *password,
716                              uint8_t *masterkey,
717                              uint64_t iter_time,
718                              QCryptoBlockWriteFunc writefunc,
719                              void *opaque,
720                              Error **errp)
721 {
722     QCryptoBlockLUKS *luks = block->opaque;
723     QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[slot_idx];
724     g_autofree uint8_t *splitkey = NULL;
725     size_t splitkeylen;
726     g_autofree uint8_t *slotkey = NULL;
727     g_autoptr(QCryptoCipher) cipher = NULL;
728     g_autoptr(QCryptoIVGen) ivgen = NULL;
729     Error *local_err = NULL;
730     uint64_t iters;
731     int ret = -1;
732 
733     if (qcrypto_random_bytes(slot->salt,
734                              QCRYPTO_BLOCK_LUKS_SALT_LEN,
735                              errp) < 0) {
736         goto cleanup;
737     }
738 
739     splitkeylen = luks->header.master_key_len * slot->stripes;
740 
741     /*
742      * Determine how many iterations are required to
743      * hash the user password while consuming 1 second of compute
744      * time
745      */
746     iters = qcrypto_pbkdf2_count_iters(luks->hash_alg,
747                                        (uint8_t *)password, strlen(password),
748                                        slot->salt,
749                                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
750                                        luks->header.master_key_len,
751                                        &local_err);
752     if (local_err) {
753         error_propagate(errp, local_err);
754         goto cleanup;
755     }
756 
757     if (iters > (ULLONG_MAX / iter_time)) {
758         error_setg_errno(errp, ERANGE,
759                          "PBKDF iterations %llu too large to scale",
760                          (unsigned long long)iters);
761         goto cleanup;
762     }
763 
764     /* iter_time was in millis, but count_iters reported for secs */
765     iters = iters * iter_time / 1000;
766 
767     if (iters > UINT32_MAX) {
768         error_setg_errno(errp, ERANGE,
769                          "PBKDF iterations %llu larger than %u",
770                          (unsigned long long)iters, UINT32_MAX);
771         goto cleanup;
772     }
773 
774     slot->iterations =
775         MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
776 
777 
778     /*
779      * Generate a key that we'll use to encrypt the master
780      * key, from the user's password
781      */
782     slotkey = g_new0(uint8_t, luks->header.master_key_len);
783     if (qcrypto_pbkdf2(luks->hash_alg,
784                        (uint8_t *)password, strlen(password),
785                        slot->salt,
786                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
787                        slot->iterations,
788                        slotkey, luks->header.master_key_len,
789                        errp) < 0) {
790         goto cleanup;
791     }
792 
793 
794     /*
795      * Setup the encryption objects needed to encrypt the
796      * master key material
797      */
798     cipher = qcrypto_cipher_new(luks->cipher_alg,
799                                 luks->cipher_mode,
800                                 slotkey, luks->header.master_key_len,
801                                 errp);
802     if (!cipher) {
803         goto cleanup;
804     }
805 
806     ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
807                               luks->ivgen_cipher_alg,
808                               luks->ivgen_hash_alg,
809                               slotkey, luks->header.master_key_len,
810                               errp);
811     if (!ivgen) {
812         goto cleanup;
813     }
814 
815     /*
816      * Before storing the master key, we need to vastly
817      * increase its size, as protection against forensic
818      * disk data recovery
819      */
820     splitkey = g_new0(uint8_t, splitkeylen);
821 
822     if (qcrypto_afsplit_encode(luks->hash_alg,
823                                luks->header.master_key_len,
824                                slot->stripes,
825                                masterkey,
826                                splitkey,
827                                errp) < 0) {
828         goto cleanup;
829     }
830 
831     /*
832      * Now we encrypt the split master key with the key generated
833      * from the user's password, before storing it
834      */
835     if (qcrypto_block_cipher_encrypt_helper(cipher, block->niv, ivgen,
836                                             QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
837                                             0,
838                                             splitkey,
839                                             splitkeylen,
840                                             errp) < 0) {
841         goto cleanup;
842     }
843 
844     /* Write out the slot's master key material. */
845     if (writefunc(block,
846                   slot->key_offset_sector *
847                   QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
848                   splitkey, splitkeylen,
849                   opaque,
850                   errp) != splitkeylen) {
851         goto cleanup;
852     }
853 
854     slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
855 
856     if (qcrypto_block_luks_store_header(block,  writefunc, opaque, errp) < 0) {
857         goto cleanup;
858     }
859 
860     ret = 0;
861 
862 cleanup:
863     if (slotkey) {
864         memset(slotkey, 0, luks->header.master_key_len);
865     }
866     if (splitkey) {
867         memset(splitkey, 0, splitkeylen);
868     }
869     return ret;
870 }
871 
872 /*
873  * Given a key slot, and user password, this will attempt to unlock
874  * the master encryption key from the key slot.
875  *
876  * Returns:
877  *    0 if the key slot is disabled, or key could not be decrypted
878  *      with the provided password
879  *    1 if the key slot is enabled, and key decrypted successfully
880  *      with the provided password
881  *   -1 if a fatal error occurred loading the key
882  */
883 static int
884 qcrypto_block_luks_load_key(QCryptoBlock *block,
885                             size_t slot_idx,
886                             const char *password,
887                             uint8_t *masterkey,
888                             QCryptoBlockReadFunc readfunc,
889                             void *opaque,
890                             Error **errp)
891 {
892     QCryptoBlockLUKS *luks = block->opaque;
893     const QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[slot_idx];
894     g_autofree uint8_t *splitkey = NULL;
895     size_t splitkeylen;
896     g_autofree uint8_t *possiblekey = NULL;
897     ssize_t rv;
898     g_autoptr(QCryptoCipher) cipher = NULL;
899     uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
900     g_autoptr(QCryptoIVGen) ivgen = NULL;
901     size_t niv;
902 
903     if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
904         return 0;
905     }
906 
907     splitkeylen = luks->header.master_key_len * slot->stripes;
908     splitkey = g_new0(uint8_t, splitkeylen);
909     possiblekey = g_new0(uint8_t, luks->header.master_key_len);
910 
911     /*
912      * The user password is used to generate a (possible)
913      * decryption key. This may or may not successfully
914      * decrypt the master key - we just blindly assume
915      * the key is correct and validate the results of
916      * decryption later.
917      */
918     if (qcrypto_pbkdf2(luks->hash_alg,
919                        (const uint8_t *)password, strlen(password),
920                        slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
921                        slot->iterations,
922                        possiblekey, luks->header.master_key_len,
923                        errp) < 0) {
924         return -1;
925     }
926 
927     /*
928      * We need to read the master key material from the
929      * LUKS key material header. What we're reading is
930      * not the raw master key, but rather the data after
931      * it has been passed through AFSplit and the result
932      * then encrypted.
933      */
934     rv = readfunc(block,
935                   slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
936                   splitkey, splitkeylen,
937                   opaque,
938                   errp);
939     if (rv < 0) {
940         return -1;
941     }
942 
943 
944     /* Setup the cipher/ivgen that we'll use to try to decrypt
945      * the split master key material */
946     cipher = qcrypto_cipher_new(luks->cipher_alg,
947                                 luks->cipher_mode,
948                                 possiblekey,
949                                 luks->header.master_key_len,
950                                 errp);
951     if (!cipher) {
952         return -1;
953     }
954 
955     niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
956                                     luks->cipher_mode);
957 
958     ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
959                               luks->ivgen_cipher_alg,
960                               luks->ivgen_hash_alg,
961                               possiblekey,
962                               luks->header.master_key_len,
963                               errp);
964     if (!ivgen) {
965         return -1;
966     }
967 
968 
969     /*
970      * The master key needs to be decrypted in the same
971      * way that the block device payload will be decrypted
972      * later. In particular we'll be using the IV generator
973      * to reset the encryption cipher every time the master
974      * key crosses a sector boundary.
975      */
976     if (qcrypto_block_cipher_decrypt_helper(cipher,
977                                             niv,
978                                             ivgen,
979                                             QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
980                                             0,
981                                             splitkey,
982                                             splitkeylen,
983                                             errp) < 0) {
984         return -1;
985     }
986 
987     /*
988      * Now we've decrypted the split master key, join
989      * it back together to get the actual master key.
990      */
991     if (qcrypto_afsplit_decode(luks->hash_alg,
992                                luks->header.master_key_len,
993                                slot->stripes,
994                                splitkey,
995                                masterkey,
996                                errp) < 0) {
997         return -1;
998     }
999 
1000 
1001     /*
1002      * We still don't know that the masterkey we got is valid,
1003      * because we just blindly assumed the user's password
1004      * was correct. This is where we now verify it. We are
1005      * creating a hash of the master key using PBKDF and
1006      * then comparing that to the hash stored in the key slot
1007      * header
1008      */
1009     if (qcrypto_pbkdf2(luks->hash_alg,
1010                        masterkey,
1011                        luks->header.master_key_len,
1012                        luks->header.master_key_salt,
1013                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1014                        luks->header.master_key_iterations,
1015                        keydigest,
1016                        G_N_ELEMENTS(keydigest),
1017                        errp) < 0) {
1018         return -1;
1019     }
1020 
1021     if (memcmp(keydigest, luks->header.master_key_digest,
1022                QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
1023         /* Success, we got the right master key */
1024         return 1;
1025     }
1026 
1027     /* Fail, user's password was not valid for this key slot,
1028      * tell caller to try another slot */
1029     return 0;
1030 }
1031 
1032 
1033 /*
1034  * Given a user password, this will iterate over all key
1035  * slots and try to unlock each active key slot using the
1036  * password until it successfully obtains a master key.
1037  *
1038  * Returns 0 if a key was loaded, -1 if no keys could be loaded
1039  */
1040 static int
1041 qcrypto_block_luks_find_key(QCryptoBlock *block,
1042                             const char *password,
1043                             uint8_t *masterkey,
1044                             QCryptoBlockReadFunc readfunc,
1045                             void *opaque,
1046                             Error **errp)
1047 {
1048     size_t i;
1049     int rv;
1050 
1051     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1052         rv = qcrypto_block_luks_load_key(block,
1053                                          i,
1054                                          password,
1055                                          masterkey,
1056                                          readfunc,
1057                                          opaque,
1058                                          errp);
1059         if (rv < 0) {
1060             goto error;
1061         }
1062         if (rv == 1) {
1063             return 0;
1064         }
1065     }
1066 
1067     error_setg(errp, "Invalid password, cannot unlock any keyslot");
1068  error:
1069     return -1;
1070 }
1071 
1072 
1073 static int
1074 qcrypto_block_luks_open(QCryptoBlock *block,
1075                         QCryptoBlockOpenOptions *options,
1076                         const char *optprefix,
1077                         QCryptoBlockReadFunc readfunc,
1078                         void *opaque,
1079                         unsigned int flags,
1080                         size_t n_threads,
1081                         Error **errp)
1082 {
1083     QCryptoBlockLUKS *luks = NULL;
1084     g_autofree uint8_t *masterkey = NULL;
1085     g_autofree char *password = NULL;
1086 
1087     if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1088         if (!options->u.luks.key_secret) {
1089             error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1090                        optprefix ? optprefix : "");
1091             return -1;
1092         }
1093         password = qcrypto_secret_lookup_as_utf8(
1094             options->u.luks.key_secret, errp);
1095         if (!password) {
1096             return -1;
1097         }
1098     }
1099 
1100     luks = g_new0(QCryptoBlockLUKS, 1);
1101     block->opaque = luks;
1102 
1103     if (qcrypto_block_luks_load_header(block, readfunc, opaque, errp) < 0) {
1104         goto fail;
1105     }
1106 
1107     if (qcrypto_block_luks_check_header(luks, errp) < 0) {
1108         goto fail;
1109     }
1110 
1111     if (qcrypto_block_luks_parse_header(luks, errp) < 0) {
1112         goto fail;
1113     }
1114 
1115     if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1116         /* Try to find which key slot our password is valid for
1117          * and unlock the master key from that slot.
1118          */
1119 
1120         masterkey = g_new0(uint8_t, luks->header.master_key_len);
1121 
1122         if (qcrypto_block_luks_find_key(block,
1123                                         password,
1124                                         masterkey,
1125                                         readfunc, opaque,
1126                                         errp) < 0) {
1127             goto fail;
1128         }
1129 
1130         /* We have a valid master key now, so can setup the
1131          * block device payload decryption objects
1132          */
1133         block->kdfhash = luks->hash_alg;
1134         block->niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
1135                                                luks->cipher_mode);
1136 
1137         block->ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
1138                                          luks->ivgen_cipher_alg,
1139                                          luks->ivgen_hash_alg,
1140                                          masterkey,
1141                                          luks->header.master_key_len,
1142                                          errp);
1143         if (!block->ivgen) {
1144             goto fail;
1145         }
1146 
1147         if (qcrypto_block_init_cipher(block,
1148                                       luks->cipher_alg,
1149                                       luks->cipher_mode,
1150                                       masterkey,
1151                                       luks->header.master_key_len,
1152                                       n_threads,
1153                                       errp) < 0) {
1154             goto fail;
1155         }
1156     }
1157 
1158     block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1159     block->payload_offset = luks->header.payload_offset_sector *
1160         block->sector_size;
1161 
1162     return 0;
1163 
1164  fail:
1165     qcrypto_block_free_cipher(block);
1166     qcrypto_ivgen_free(block->ivgen);
1167     g_free(luks);
1168     return -1;
1169 }
1170 
1171 
1172 static void
1173 qcrypto_block_luks_uuid_gen(uint8_t *uuidstr)
1174 {
1175     QemuUUID uuid;
1176     qemu_uuid_generate(&uuid);
1177     qemu_uuid_unparse(&uuid, (char *)uuidstr);
1178 }
1179 
1180 static int
1181 qcrypto_block_luks_create(QCryptoBlock *block,
1182                           QCryptoBlockCreateOptions *options,
1183                           const char *optprefix,
1184                           QCryptoBlockInitFunc initfunc,
1185                           QCryptoBlockWriteFunc writefunc,
1186                           void *opaque,
1187                           Error **errp)
1188 {
1189     QCryptoBlockLUKS *luks;
1190     QCryptoBlockCreateOptionsLUKS luks_opts;
1191     Error *local_err = NULL;
1192     g_autofree uint8_t *masterkey = NULL;
1193     size_t header_sectors;
1194     size_t split_key_sectors;
1195     size_t i;
1196     g_autofree char *password = NULL;
1197     const char *cipher_alg;
1198     const char *cipher_mode;
1199     const char *ivgen_alg;
1200     const char *ivgen_hash_alg = NULL;
1201     const char *hash_alg;
1202     g_autofree char *cipher_mode_spec = NULL;
1203     uint64_t iters;
1204 
1205     memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
1206     if (!luks_opts.has_iter_time) {
1207         luks_opts.iter_time = 2000;
1208     }
1209     if (!luks_opts.has_cipher_alg) {
1210         luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
1211     }
1212     if (!luks_opts.has_cipher_mode) {
1213         luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
1214     }
1215     if (!luks_opts.has_ivgen_alg) {
1216         luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
1217     }
1218     if (!luks_opts.has_hash_alg) {
1219         luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
1220     }
1221     if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1222         if (!luks_opts.has_ivgen_hash_alg) {
1223             luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
1224             luks_opts.has_ivgen_hash_alg = true;
1225         }
1226     }
1227 
1228     luks = g_new0(QCryptoBlockLUKS, 1);
1229     block->opaque = luks;
1230 
1231     luks->cipher_alg = luks_opts.cipher_alg;
1232     luks->cipher_mode = luks_opts.cipher_mode;
1233     luks->ivgen_alg = luks_opts.ivgen_alg;
1234     luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
1235     luks->hash_alg = luks_opts.hash_alg;
1236 
1237 
1238     /* Note we're allowing ivgen_hash_alg to be set even for
1239      * non-essiv iv generators that don't need a hash. It will
1240      * be silently ignored, for compatibility with dm-crypt */
1241 
1242     if (!options->u.luks.key_secret) {
1243         error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1244                    optprefix ? optprefix : "");
1245         goto error;
1246     }
1247     password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
1248     if (!password) {
1249         goto error;
1250     }
1251 
1252 
1253     memcpy(luks->header.magic, qcrypto_block_luks_magic,
1254            QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
1255 
1256     /* We populate the header in native endianness initially and
1257      * then convert everything to big endian just before writing
1258      * it out to disk
1259      */
1260     luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
1261     qcrypto_block_luks_uuid_gen(luks->header.uuid);
1262 
1263     cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
1264                                                       errp);
1265     if (!cipher_alg) {
1266         goto error;
1267     }
1268 
1269     cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
1270     ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
1271     if (luks_opts.has_ivgen_hash_alg) {
1272         ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
1273         cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
1274                                            ivgen_hash_alg);
1275     } else {
1276         cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
1277     }
1278     hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
1279 
1280 
1281     if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
1282         error_setg(errp, "Cipher name '%s' is too long for LUKS header",
1283                    cipher_alg);
1284         goto error;
1285     }
1286     if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
1287         error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
1288                    cipher_mode_spec);
1289         goto error;
1290     }
1291     if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
1292         error_setg(errp, "Hash name '%s' is too long for LUKS header",
1293                    hash_alg);
1294         goto error;
1295     }
1296 
1297     if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1298         luks->ivgen_cipher_alg =
1299                 qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
1300                                                 luks_opts.ivgen_hash_alg,
1301                                                 &local_err);
1302         if (local_err) {
1303             error_propagate(errp, local_err);
1304             goto error;
1305         }
1306     } else {
1307         luks->ivgen_cipher_alg = luks_opts.cipher_alg;
1308     }
1309 
1310     strcpy(luks->header.cipher_name, cipher_alg);
1311     strcpy(luks->header.cipher_mode, cipher_mode_spec);
1312     strcpy(luks->header.hash_spec, hash_alg);
1313 
1314     luks->header.master_key_len =
1315         qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
1316 
1317     if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
1318         luks->header.master_key_len *= 2;
1319     }
1320 
1321     /* Generate the salt used for hashing the master key
1322      * with PBKDF later
1323      */
1324     if (qcrypto_random_bytes(luks->header.master_key_salt,
1325                              QCRYPTO_BLOCK_LUKS_SALT_LEN,
1326                              errp) < 0) {
1327         goto error;
1328     }
1329 
1330     /* Generate random master key */
1331     masterkey = g_new0(uint8_t, luks->header.master_key_len);
1332     if (qcrypto_random_bytes(masterkey,
1333                              luks->header.master_key_len, errp) < 0) {
1334         goto error;
1335     }
1336 
1337 
1338     /* Setup the block device payload encryption objects */
1339     if (qcrypto_block_init_cipher(block, luks_opts.cipher_alg,
1340                                   luks_opts.cipher_mode, masterkey,
1341                                   luks->header.master_key_len, 1, errp) < 0) {
1342         goto error;
1343     }
1344 
1345     block->kdfhash = luks_opts.hash_alg;
1346     block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1347                                            luks_opts.cipher_mode);
1348     block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1349                                      luks->ivgen_cipher_alg,
1350                                      luks_opts.ivgen_hash_alg,
1351                                      masterkey, luks->header.master_key_len,
1352                                      errp);
1353 
1354     if (!block->ivgen) {
1355         goto error;
1356     }
1357 
1358 
1359     /* Determine how many iterations we need to hash the master
1360      * key, in order to have 1 second of compute time used
1361      */
1362     iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1363                                        masterkey, luks->header.master_key_len,
1364                                        luks->header.master_key_salt,
1365                                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1366                                        QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1367                                        &local_err);
1368     if (local_err) {
1369         error_propagate(errp, local_err);
1370         goto error;
1371     }
1372 
1373     if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1374         error_setg_errno(errp, ERANGE,
1375                          "PBKDF iterations %llu too large to scale",
1376                          (unsigned long long)iters);
1377         goto error;
1378     }
1379 
1380     /* iter_time was in millis, but count_iters reported for secs */
1381     iters = iters * luks_opts.iter_time / 1000;
1382 
1383     /* Why /= 8 ?  That matches cryptsetup, but there's no
1384      * explanation why they chose /= 8... Probably so that
1385      * if all 8 keyslots are active we only spend 1 second
1386      * in total time to check all keys */
1387     iters /= 8;
1388     if (iters > UINT32_MAX) {
1389         error_setg_errno(errp, ERANGE,
1390                          "PBKDF iterations %llu larger than %u",
1391                          (unsigned long long)iters, UINT32_MAX);
1392         goto error;
1393     }
1394     iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1395     luks->header.master_key_iterations = iters;
1396 
1397     /* Hash the master key, saving the result in the LUKS
1398      * header. This hash is used when opening the encrypted
1399      * device to verify that the user password unlocked a
1400      * valid master key
1401      */
1402     if (qcrypto_pbkdf2(luks_opts.hash_alg,
1403                        masterkey, luks->header.master_key_len,
1404                        luks->header.master_key_salt,
1405                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1406                        luks->header.master_key_iterations,
1407                        luks->header.master_key_digest,
1408                        QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1409                        errp) < 0) {
1410         goto error;
1411     }
1412 
1413     /* start with the sector that follows the header*/
1414     header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1415         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1416 
1417     split_key_sectors =
1418         qcrypto_block_luks_splitkeylen_sectors(luks,
1419                                                header_sectors,
1420                                                QCRYPTO_BLOCK_LUKS_STRIPES);
1421 
1422     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1423         QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[i];
1424         slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1425 
1426         slot->key_offset_sector = header_sectors + i * split_key_sectors;
1427         slot->stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
1428     }
1429 
1430     /* The total size of the LUKS headers is the partition header + key
1431      * slot headers, rounded up to the nearest sector, combined with
1432      * the size of each master key material region, also rounded up
1433      * to the nearest sector */
1434     luks->header.payload_offset_sector = header_sectors +
1435             QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS * split_key_sectors;
1436 
1437     block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1438     block->payload_offset = luks->header.payload_offset_sector *
1439         block->sector_size;
1440 
1441     /* Reserve header space to match payload offset */
1442     initfunc(block, block->payload_offset, opaque, &local_err);
1443     if (local_err) {
1444         error_propagate(errp, local_err);
1445         goto error;
1446     }
1447 
1448 
1449     /* populate the slot 0 with the password encrypted master key*/
1450     /* This will also store the header */
1451     if (qcrypto_block_luks_store_key(block,
1452                                      0,
1453                                      password,
1454                                      masterkey,
1455                                      luks_opts.iter_time,
1456                                      writefunc,
1457                                      opaque,
1458                                      errp) < 0) {
1459         goto error;
1460     }
1461 
1462     memset(masterkey, 0, luks->header.master_key_len);
1463 
1464     return 0;
1465 
1466  error:
1467     if (masterkey) {
1468         memset(masterkey, 0, luks->header.master_key_len);
1469     }
1470 
1471     qcrypto_block_free_cipher(block);
1472     qcrypto_ivgen_free(block->ivgen);
1473 
1474     g_free(luks);
1475     return -1;
1476 }
1477 
1478 
1479 static int qcrypto_block_luks_get_info(QCryptoBlock *block,
1480                                        QCryptoBlockInfo *info,
1481                                        Error **errp)
1482 {
1483     QCryptoBlockLUKS *luks = block->opaque;
1484     QCryptoBlockInfoLUKSSlot *slot;
1485     QCryptoBlockInfoLUKSSlotList *slots = NULL, **prev = &info->u.luks.slots;
1486     size_t i;
1487 
1488     info->u.luks.cipher_alg = luks->cipher_alg;
1489     info->u.luks.cipher_mode = luks->cipher_mode;
1490     info->u.luks.ivgen_alg = luks->ivgen_alg;
1491     if (info->u.luks.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1492         info->u.luks.has_ivgen_hash_alg = true;
1493         info->u.luks.ivgen_hash_alg = luks->ivgen_hash_alg;
1494     }
1495     info->u.luks.hash_alg = luks->hash_alg;
1496     info->u.luks.payload_offset = block->payload_offset;
1497     info->u.luks.master_key_iters = luks->header.master_key_iterations;
1498     info->u.luks.uuid = g_strndup((const char *)luks->header.uuid,
1499                                   sizeof(luks->header.uuid));
1500 
1501     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1502         slots = g_new0(QCryptoBlockInfoLUKSSlotList, 1);
1503         *prev = slots;
1504 
1505         slots->value = slot = g_new0(QCryptoBlockInfoLUKSSlot, 1);
1506         slot->active = luks->header.key_slots[i].active ==
1507             QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
1508         slot->key_offset = luks->header.key_slots[i].key_offset_sector
1509              * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1510         if (slot->active) {
1511             slot->has_iters = true;
1512             slot->iters = luks->header.key_slots[i].iterations;
1513             slot->has_stripes = true;
1514             slot->stripes = luks->header.key_slots[i].stripes;
1515         }
1516 
1517         prev = &slots->next;
1518     }
1519 
1520     return 0;
1521 }
1522 
1523 
1524 static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1525 {
1526     g_free(block->opaque);
1527 }
1528 
1529 
1530 static int
1531 qcrypto_block_luks_decrypt(QCryptoBlock *block,
1532                            uint64_t offset,
1533                            uint8_t *buf,
1534                            size_t len,
1535                            Error **errp)
1536 {
1537     assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1538     assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1539     return qcrypto_block_decrypt_helper(block,
1540                                         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1541                                         offset, buf, len, errp);
1542 }
1543 
1544 
1545 static int
1546 qcrypto_block_luks_encrypt(QCryptoBlock *block,
1547                            uint64_t offset,
1548                            uint8_t *buf,
1549                            size_t len,
1550                            Error **errp)
1551 {
1552     assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1553     assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1554     return qcrypto_block_encrypt_helper(block,
1555                                         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1556                                         offset, buf, len, errp);
1557 }
1558 
1559 
1560 const QCryptoBlockDriver qcrypto_block_driver_luks = {
1561     .open = qcrypto_block_luks_open,
1562     .create = qcrypto_block_luks_create,
1563     .get_info = qcrypto_block_luks_get_info,
1564     .cleanup = qcrypto_block_luks_cleanup,
1565     .decrypt = qcrypto_block_luks_decrypt,
1566     .encrypt = qcrypto_block_luks_encrypt,
1567     .has_format = qcrypto_block_luks_has_format,
1568 };
1569