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