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