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