xref: /openbmc/qemu/crypto/block-luks.c (revision 358f6348)
1 /*
2  * QEMU Crypto block device encryption LUKS format
3  *
4  * Copyright (c) 2015-2016 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 #include "qemu/osdep.h"
22 #include "qapi/error.h"
23 #include "qemu/bswap.h"
24 
25 #include "block-luks.h"
26 
27 #include "crypto/hash.h"
28 #include "crypto/afsplit.h"
29 #include "crypto/pbkdf.h"
30 #include "crypto/secret.h"
31 #include "crypto/random.h"
32 #include "qemu/uuid.h"
33 
34 #include "qemu/coroutine.h"
35 
36 /*
37  * Reference for the LUKS format implemented here is
38  *
39  *   docs/on-disk-format.pdf
40  *
41  * in 'cryptsetup' package source code
42  *
43  * This file implements the 1.2.1 specification, dated
44  * Oct 16, 2011.
45  */
46 
47 typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
48 typedef struct QCryptoBlockLUKSHeader QCryptoBlockLUKSHeader;
49 typedef struct QCryptoBlockLUKSKeySlot QCryptoBlockLUKSKeySlot;
50 
51 
52 /* The following constants are all defined by the LUKS spec */
53 #define QCRYPTO_BLOCK_LUKS_VERSION 1
54 
55 #define QCRYPTO_BLOCK_LUKS_MAGIC_LEN 6
56 #define QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN 32
57 #define QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN 32
58 #define QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN 32
59 #define QCRYPTO_BLOCK_LUKS_DIGEST_LEN 20
60 #define QCRYPTO_BLOCK_LUKS_SALT_LEN 32
61 #define QCRYPTO_BLOCK_LUKS_UUID_LEN 40
62 #define QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS 8
63 #define QCRYPTO_BLOCK_LUKS_STRIPES 4000
64 #define QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS 1000
65 #define QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS 1000
66 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET 4096
67 
68 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED 0x0000DEAD
69 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED 0x00AC71F3
70 
71 #define QCRYPTO_BLOCK_LUKS_SECTOR_SIZE 512LL
72 
73 static const char qcrypto_block_luks_magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN] = {
74     'L', 'U', 'K', 'S', 0xBA, 0xBE
75 };
76 
77 typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
78 struct QCryptoBlockLUKSNameMap {
79     const char *name;
80     int id;
81 };
82 
83 typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
84 struct QCryptoBlockLUKSCipherSizeMap {
85     uint32_t key_bytes;
86     int id;
87 };
88 typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
89 struct QCryptoBlockLUKSCipherNameMap {
90     const char *name;
91     const QCryptoBlockLUKSCipherSizeMap *sizes;
92 };
93 
94 
95 static const QCryptoBlockLUKSCipherSizeMap
96 qcrypto_block_luks_cipher_size_map_aes[] = {
97     { 16, QCRYPTO_CIPHER_ALG_AES_128 },
98     { 24, QCRYPTO_CIPHER_ALG_AES_192 },
99     { 32, QCRYPTO_CIPHER_ALG_AES_256 },
100     { 0, 0 },
101 };
102 
103 static const QCryptoBlockLUKSCipherSizeMap
104 qcrypto_block_luks_cipher_size_map_cast5[] = {
105     { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
106     { 0, 0 },
107 };
108 
109 static const QCryptoBlockLUKSCipherSizeMap
110 qcrypto_block_luks_cipher_size_map_serpent[] = {
111     { 16, QCRYPTO_CIPHER_ALG_SERPENT_128 },
112     { 24, QCRYPTO_CIPHER_ALG_SERPENT_192 },
113     { 32, QCRYPTO_CIPHER_ALG_SERPENT_256 },
114     { 0, 0 },
115 };
116 
117 static const QCryptoBlockLUKSCipherSizeMap
118 qcrypto_block_luks_cipher_size_map_twofish[] = {
119     { 16, QCRYPTO_CIPHER_ALG_TWOFISH_128 },
120     { 24, QCRYPTO_CIPHER_ALG_TWOFISH_192 },
121     { 32, QCRYPTO_CIPHER_ALG_TWOFISH_256 },
122     { 0, 0 },
123 };
124 
125 static const QCryptoBlockLUKSCipherNameMap
126 qcrypto_block_luks_cipher_name_map[] = {
127     { "aes", qcrypto_block_luks_cipher_size_map_aes },
128     { "cast5", qcrypto_block_luks_cipher_size_map_cast5 },
129     { "serpent", qcrypto_block_luks_cipher_size_map_serpent },
130     { "twofish", qcrypto_block_luks_cipher_size_map_twofish },
131 };
132 
133 
134 /*
135  * This struct is written to disk in big-endian format,
136  * but operated upon in native-endian format.
137  */
138 struct QCryptoBlockLUKSKeySlot {
139     /* state of keyslot, enabled/disable */
140     uint32_t active;
141     /* iterations for PBKDF2 */
142     uint32_t iterations;
143     /* salt for PBKDF2 */
144     uint8_t salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
145     /* start sector of key material */
146     uint32_t key_offset;
147     /* number of anti-forensic stripes */
148     uint32_t stripes;
149 };
150 
151 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSKeySlot) != 48);
152 
153 
154 /*
155  * This struct is written to disk in big-endian format,
156  * but operated upon in native-endian format.
157  */
158 struct QCryptoBlockLUKSHeader {
159     /* 'L', 'U', 'K', 'S', '0xBA', '0xBE' */
160     char magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN];
161 
162     /* LUKS version, currently 1 */
163     uint16_t version;
164 
165     /* cipher name specification (aes, etc) */
166     char cipher_name[QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN];
167 
168     /* cipher mode specification (cbc-plain, xts-essiv:sha256, etc) */
169     char cipher_mode[QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN];
170 
171     /* hash specification (sha256, etc) */
172     char hash_spec[QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN];
173 
174     /* start offset of the volume data (in 512 byte sectors) */
175     uint32_t payload_offset;
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 };
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     g_autofree uint8_t *splitkey = NULL;
429     size_t splitkeylen;
430     g_autofree uint8_t *possiblekey = NULL;
431     ssize_t rv;
432     g_autoptr(QCryptoCipher) cipher = NULL;
433     uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
434     g_autoptr(QCryptoIVGen) ivgen = NULL;
435     size_t niv;
436 
437     if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
438         return 0;
439     }
440 
441     splitkeylen = masterkeylen * slot->stripes;
442     splitkey = g_new0(uint8_t, splitkeylen);
443     possiblekey = g_new0(uint8_t, masterkeylen);
444 
445     /*
446      * The user password is used to generate a (possible)
447      * decryption key. This may or may not successfully
448      * decrypt the master key - we just blindly assume
449      * the key is correct and validate the results of
450      * decryption later.
451      */
452     if (qcrypto_pbkdf2(hash,
453                        (const uint8_t *)password, strlen(password),
454                        slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
455                        slot->iterations,
456                        possiblekey, masterkeylen,
457                        errp) < 0) {
458         return -1;
459     }
460 
461     /*
462      * We need to read the master key material from the
463      * LUKS key material header. What we're reading is
464      * not the raw master key, but rather the data after
465      * it has been passed through AFSplit and the result
466      * then encrypted.
467      */
468     rv = readfunc(block,
469                   slot->key_offset * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
470                   splitkey, splitkeylen,
471                   opaque,
472                   errp);
473     if (rv < 0) {
474         return -1;
475     }
476 
477 
478     /* Setup the cipher/ivgen that we'll use to try to decrypt
479      * the split master key material */
480     cipher = qcrypto_cipher_new(cipheralg, ciphermode,
481                                 possiblekey, masterkeylen,
482                                 errp);
483     if (!cipher) {
484         return -1;
485     }
486 
487     niv = qcrypto_cipher_get_iv_len(cipheralg,
488                                     ciphermode);
489     ivgen = qcrypto_ivgen_new(ivalg,
490                               ivcipheralg,
491                               ivhash,
492                               possiblekey, masterkeylen,
493                               errp);
494     if (!ivgen) {
495         return -1;
496     }
497 
498 
499     /*
500      * The master key needs to be decrypted in the same
501      * way that the block device payload will be decrypted
502      * later. In particular we'll be using the IV generator
503      * to reset the encryption cipher every time the master
504      * key crosses a sector boundary.
505      */
506     if (qcrypto_block_cipher_decrypt_helper(cipher,
507                                             niv,
508                                             ivgen,
509                                             QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
510                                             0,
511                                             splitkey,
512                                             splitkeylen,
513                                             errp) < 0) {
514         return -1;
515     }
516 
517     /*
518      * Now we've decrypted the split master key, join
519      * it back together to get the actual master key.
520      */
521     if (qcrypto_afsplit_decode(hash,
522                                masterkeylen,
523                                slot->stripes,
524                                splitkey,
525                                masterkey,
526                                errp) < 0) {
527         return -1;
528     }
529 
530 
531     /*
532      * We still don't know that the masterkey we got is valid,
533      * because we just blindly assumed the user's password
534      * was correct. This is where we now verify it. We are
535      * creating a hash of the master key using PBKDF and
536      * then comparing that to the hash stored in the key slot
537      * header
538      */
539     if (qcrypto_pbkdf2(hash,
540                        masterkey, masterkeylen,
541                        luks->header.master_key_salt,
542                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
543                        luks->header.master_key_iterations,
544                        keydigest, G_N_ELEMENTS(keydigest),
545                        errp) < 0) {
546         return -1;
547     }
548 
549     if (memcmp(keydigest, luks->header.master_key_digest,
550                QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
551         /* Success, we got the right master key */
552         return 1;
553     }
554 
555     /* Fail, user's password was not valid for this key slot,
556      * tell caller to try another slot */
557     return 0;
558 }
559 
560 
561 /*
562  * Given a user password, this will iterate over all key
563  * slots and try to unlock each active key slot using the
564  * password until it successfully obtains a master key.
565  *
566  * Returns 0 if a key was loaded, -1 if no keys could be loaded
567  */
568 static int
569 qcrypto_block_luks_find_key(QCryptoBlock *block,
570                             const char *password,
571                             QCryptoCipherAlgorithm cipheralg,
572                             QCryptoCipherMode ciphermode,
573                             QCryptoHashAlgorithm hash,
574                             QCryptoIVGenAlgorithm ivalg,
575                             QCryptoCipherAlgorithm ivcipheralg,
576                             QCryptoHashAlgorithm ivhash,
577                             uint8_t **masterkey,
578                             size_t *masterkeylen,
579                             QCryptoBlockReadFunc readfunc,
580                             void *opaque,
581                             Error **errp)
582 {
583     QCryptoBlockLUKS *luks = block->opaque;
584     size_t i;
585     int rv;
586 
587     *masterkey = g_new0(uint8_t, luks->header.key_bytes);
588     *masterkeylen = luks->header.key_bytes;
589 
590     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
591         rv = qcrypto_block_luks_load_key(block,
592                                          &luks->header.key_slots[i],
593                                          password,
594                                          cipheralg,
595                                          ciphermode,
596                                          hash,
597                                          ivalg,
598                                          ivcipheralg,
599                                          ivhash,
600                                          *masterkey,
601                                          *masterkeylen,
602                                          readfunc,
603                                          opaque,
604                                          errp);
605         if (rv < 0) {
606             goto error;
607         }
608         if (rv == 1) {
609             return 0;
610         }
611     }
612 
613     error_setg(errp, "Invalid password, cannot unlock any keyslot");
614 
615  error:
616     g_free(*masterkey);
617     *masterkey = NULL;
618     *masterkeylen = 0;
619     return -1;
620 }
621 
622 
623 static int
624 qcrypto_block_luks_open(QCryptoBlock *block,
625                         QCryptoBlockOpenOptions *options,
626                         const char *optprefix,
627                         QCryptoBlockReadFunc readfunc,
628                         void *opaque,
629                         unsigned int flags,
630                         size_t n_threads,
631                         Error **errp)
632 {
633     QCryptoBlockLUKS *luks;
634     Error *local_err = NULL;
635     int ret = 0;
636     size_t i;
637     ssize_t rv;
638     g_autofree uint8_t *masterkey = NULL;
639     size_t masterkeylen;
640     char *ivgen_name, *ivhash_name;
641     QCryptoCipherMode ciphermode;
642     QCryptoCipherAlgorithm cipheralg;
643     QCryptoIVGenAlgorithm ivalg;
644     QCryptoCipherAlgorithm ivcipheralg;
645     QCryptoHashAlgorithm hash;
646     QCryptoHashAlgorithm ivhash;
647     g_autofree char *password = NULL;
648 
649     if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
650         if (!options->u.luks.key_secret) {
651             error_setg(errp, "Parameter '%skey-secret' is required for cipher",
652                        optprefix ? optprefix : "");
653             return -1;
654         }
655         password = qcrypto_secret_lookup_as_utf8(
656             options->u.luks.key_secret, errp);
657         if (!password) {
658             return -1;
659         }
660     }
661 
662     luks = g_new0(QCryptoBlockLUKS, 1);
663     block->opaque = luks;
664 
665     /* Read the entire LUKS header, minus the key material from
666      * the underlying device */
667     rv = readfunc(block, 0,
668                   (uint8_t *)&luks->header,
669                   sizeof(luks->header),
670                   opaque,
671                   errp);
672     if (rv < 0) {
673         ret = rv;
674         goto fail;
675     }
676 
677     /* The header is always stored in big-endian format, so
678      * convert everything to native */
679     be16_to_cpus(&luks->header.version);
680     be32_to_cpus(&luks->header.payload_offset);
681     be32_to_cpus(&luks->header.key_bytes);
682     be32_to_cpus(&luks->header.master_key_iterations);
683 
684     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
685         be32_to_cpus(&luks->header.key_slots[i].active);
686         be32_to_cpus(&luks->header.key_slots[i].iterations);
687         be32_to_cpus(&luks->header.key_slots[i].key_offset);
688         be32_to_cpus(&luks->header.key_slots[i].stripes);
689     }
690 
691     if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
692                QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
693         error_setg(errp, "Volume is not in LUKS format");
694         ret = -EINVAL;
695         goto fail;
696     }
697     if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
698         error_setg(errp, "LUKS version %" PRIu32 " is not supported",
699                    luks->header.version);
700         ret = -ENOTSUP;
701         goto fail;
702     }
703 
704     /*
705      * The cipher_mode header contains a string that we have
706      * to further parse, of the format
707      *
708      *    <cipher-mode>-<iv-generator>[:<iv-hash>]
709      *
710      * eg  cbc-essiv:sha256, cbc-plain64
711      */
712     ivgen_name = strchr(luks->header.cipher_mode, '-');
713     if (!ivgen_name) {
714         ret = -EINVAL;
715         error_setg(errp, "Unexpected cipher mode string format %s",
716                    luks->header.cipher_mode);
717         goto fail;
718     }
719     *ivgen_name = '\0';
720     ivgen_name++;
721 
722     ivhash_name = strchr(ivgen_name, ':');
723     if (!ivhash_name) {
724         ivhash = 0;
725     } else {
726         *ivhash_name = '\0';
727         ivhash_name++;
728 
729         ivhash = qcrypto_block_luks_hash_name_lookup(ivhash_name,
730                                                      &local_err);
731         if (local_err) {
732             ret = -ENOTSUP;
733             error_propagate(errp, local_err);
734             goto fail;
735         }
736     }
737 
738     ciphermode = qcrypto_block_luks_cipher_mode_lookup(luks->header.cipher_mode,
739                                                        &local_err);
740     if (local_err) {
741         ret = -ENOTSUP;
742         error_propagate(errp, local_err);
743         goto fail;
744     }
745 
746     cipheralg = qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
747                                                       ciphermode,
748                                                       luks->header.key_bytes,
749                                                       &local_err);
750     if (local_err) {
751         ret = -ENOTSUP;
752         error_propagate(errp, local_err);
753         goto fail;
754     }
755 
756     hash = qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
757                                                &local_err);
758     if (local_err) {
759         ret = -ENOTSUP;
760         error_propagate(errp, local_err);
761         goto fail;
762     }
763 
764     ivalg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
765                                                  &local_err);
766     if (local_err) {
767         ret = -ENOTSUP;
768         error_propagate(errp, local_err);
769         goto fail;
770     }
771 
772     if (ivalg == QCRYPTO_IVGEN_ALG_ESSIV) {
773         if (!ivhash_name) {
774             ret = -EINVAL;
775             error_setg(errp, "Missing IV generator hash specification");
776             goto fail;
777         }
778         ivcipheralg = qcrypto_block_luks_essiv_cipher(cipheralg,
779                                                       ivhash,
780                                                       &local_err);
781         if (local_err) {
782             ret = -ENOTSUP;
783             error_propagate(errp, local_err);
784             goto fail;
785         }
786     } else {
787         /* Note we parsed the ivhash_name earlier in the cipher_mode
788          * spec string even with plain/plain64 ivgens, but we
789          * will ignore it, since it is irrelevant for these ivgens.
790          * This is for compat with dm-crypt which will silently
791          * ignore hash names with these ivgens rather than report
792          * an error about the invalid usage
793          */
794         ivcipheralg = cipheralg;
795     }
796 
797     if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
798         /* Try to find which key slot our password is valid for
799          * and unlock the master key from that slot.
800          */
801         if (qcrypto_block_luks_find_key(block,
802                                         password,
803                                         cipheralg, ciphermode,
804                                         hash,
805                                         ivalg,
806                                         ivcipheralg,
807                                         ivhash,
808                                         &masterkey, &masterkeylen,
809                                         readfunc, opaque,
810                                         errp) < 0) {
811             ret = -EACCES;
812             goto fail;
813         }
814 
815         /* We have a valid master key now, so can setup the
816          * block device payload decryption objects
817          */
818         block->kdfhash = hash;
819         block->niv = qcrypto_cipher_get_iv_len(cipheralg,
820                                                ciphermode);
821         block->ivgen = qcrypto_ivgen_new(ivalg,
822                                          ivcipheralg,
823                                          ivhash,
824                                          masterkey, masterkeylen,
825                                          errp);
826         if (!block->ivgen) {
827             ret = -ENOTSUP;
828             goto fail;
829         }
830 
831         ret = qcrypto_block_init_cipher(block, cipheralg, ciphermode,
832                                         masterkey, masterkeylen, n_threads,
833                                         errp);
834         if (ret < 0) {
835             ret = -ENOTSUP;
836             goto fail;
837         }
838     }
839 
840     block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
841     block->payload_offset = luks->header.payload_offset *
842         block->sector_size;
843 
844     luks->cipher_alg = cipheralg;
845     luks->cipher_mode = ciphermode;
846     luks->ivgen_alg = ivalg;
847     luks->ivgen_hash_alg = ivhash;
848     luks->hash_alg = hash;
849 
850     return 0;
851 
852  fail:
853     qcrypto_block_free_cipher(block);
854     qcrypto_ivgen_free(block->ivgen);
855     g_free(luks);
856     return ret;
857 }
858 
859 
860 static void
861 qcrypto_block_luks_uuid_gen(uint8_t *uuidstr)
862 {
863     QemuUUID uuid;
864     qemu_uuid_generate(&uuid);
865     qemu_uuid_unparse(&uuid, (char *)uuidstr);
866 }
867 
868 static int
869 qcrypto_block_luks_create(QCryptoBlock *block,
870                           QCryptoBlockCreateOptions *options,
871                           const char *optprefix,
872                           QCryptoBlockInitFunc initfunc,
873                           QCryptoBlockWriteFunc writefunc,
874                           void *opaque,
875                           Error **errp)
876 {
877     QCryptoBlockLUKS *luks;
878     QCryptoBlockCreateOptionsLUKS luks_opts;
879     Error *local_err = NULL;
880     g_autofree uint8_t *masterkey = NULL;
881     g_autofree uint8_t *slotkey = NULL;
882     g_autofree uint8_t *splitkey = NULL;
883     size_t splitkeylen = 0;
884     size_t i;
885     g_autoptr(QCryptoCipher) cipher = NULL;
886     g_autoptr(QCryptoIVGen) ivgen = NULL;
887     g_autofree char *password = NULL;
888     const char *cipher_alg;
889     const char *cipher_mode;
890     const char *ivgen_alg;
891     const char *ivgen_hash_alg = NULL;
892     const char *hash_alg;
893     g_autofree char *cipher_mode_spec = NULL;
894     QCryptoCipherAlgorithm ivcipheralg = 0;
895     uint64_t iters;
896 
897     memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
898     if (!luks_opts.has_iter_time) {
899         luks_opts.iter_time = 2000;
900     }
901     if (!luks_opts.has_cipher_alg) {
902         luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
903     }
904     if (!luks_opts.has_cipher_mode) {
905         luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
906     }
907     if (!luks_opts.has_ivgen_alg) {
908         luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
909     }
910     if (!luks_opts.has_hash_alg) {
911         luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
912     }
913     if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
914         if (!luks_opts.has_ivgen_hash_alg) {
915             luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
916             luks_opts.has_ivgen_hash_alg = true;
917         }
918     }
919     /* Note we're allowing ivgen_hash_alg to be set even for
920      * non-essiv iv generators that don't need a hash. It will
921      * be silently ignored, for compatibility with dm-crypt */
922 
923     if (!options->u.luks.key_secret) {
924         error_setg(errp, "Parameter '%skey-secret' is required for cipher",
925                    optprefix ? optprefix : "");
926         return -1;
927     }
928     password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
929     if (!password) {
930         return -1;
931     }
932 
933     luks = g_new0(QCryptoBlockLUKS, 1);
934     block->opaque = luks;
935 
936     memcpy(luks->header.magic, qcrypto_block_luks_magic,
937            QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
938 
939     /* We populate the header in native endianness initially and
940      * then convert everything to big endian just before writing
941      * it out to disk
942      */
943     luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
944     qcrypto_block_luks_uuid_gen(luks->header.uuid);
945 
946     cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
947                                                       errp);
948     if (!cipher_alg) {
949         goto error;
950     }
951 
952     cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
953     ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
954     if (luks_opts.has_ivgen_hash_alg) {
955         ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
956         cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
957                                            ivgen_hash_alg);
958     } else {
959         cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
960     }
961     hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
962 
963 
964     if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
965         error_setg(errp, "Cipher name '%s' is too long for LUKS header",
966                    cipher_alg);
967         goto error;
968     }
969     if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
970         error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
971                    cipher_mode_spec);
972         goto error;
973     }
974     if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
975         error_setg(errp, "Hash name '%s' is too long for LUKS header",
976                    hash_alg);
977         goto error;
978     }
979 
980     if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
981         ivcipheralg = qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
982                                                       luks_opts.ivgen_hash_alg,
983                                                       &local_err);
984         if (local_err) {
985             error_propagate(errp, local_err);
986             goto error;
987         }
988     } else {
989         ivcipheralg = luks_opts.cipher_alg;
990     }
991 
992     strcpy(luks->header.cipher_name, cipher_alg);
993     strcpy(luks->header.cipher_mode, cipher_mode_spec);
994     strcpy(luks->header.hash_spec, hash_alg);
995 
996     luks->header.key_bytes = qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
997     if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
998         luks->header.key_bytes *= 2;
999     }
1000 
1001     /* Generate the salt used for hashing the master key
1002      * with PBKDF later
1003      */
1004     if (qcrypto_random_bytes(luks->header.master_key_salt,
1005                              QCRYPTO_BLOCK_LUKS_SALT_LEN,
1006                              errp) < 0) {
1007         goto error;
1008     }
1009 
1010     /* Generate random master key */
1011     masterkey = g_new0(uint8_t, luks->header.key_bytes);
1012     if (qcrypto_random_bytes(masterkey,
1013                              luks->header.key_bytes, errp) < 0) {
1014         goto error;
1015     }
1016 
1017 
1018     /* Setup the block device payload encryption objects */
1019     if (qcrypto_block_init_cipher(block, luks_opts.cipher_alg,
1020                                   luks_opts.cipher_mode, masterkey,
1021                                   luks->header.key_bytes, 1, errp) < 0) {
1022         goto error;
1023     }
1024 
1025     block->kdfhash = luks_opts.hash_alg;
1026     block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1027                                            luks_opts.cipher_mode);
1028     block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1029                                      ivcipheralg,
1030                                      luks_opts.ivgen_hash_alg,
1031                                      masterkey, luks->header.key_bytes,
1032                                      errp);
1033 
1034     if (!block->ivgen) {
1035         goto error;
1036     }
1037 
1038 
1039     /* Determine how many iterations we need to hash the master
1040      * key, in order to have 1 second of compute time used
1041      */
1042     iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1043                                        masterkey, luks->header.key_bytes,
1044                                        luks->header.master_key_salt,
1045                                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1046                                        QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1047                                        &local_err);
1048     if (local_err) {
1049         error_propagate(errp, local_err);
1050         goto error;
1051     }
1052 
1053     if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1054         error_setg_errno(errp, ERANGE,
1055                          "PBKDF iterations %llu too large to scale",
1056                          (unsigned long long)iters);
1057         goto error;
1058     }
1059 
1060     /* iter_time was in millis, but count_iters reported for secs */
1061     iters = iters * luks_opts.iter_time / 1000;
1062 
1063     /* Why /= 8 ?  That matches cryptsetup, but there's no
1064      * explanation why they chose /= 8... Probably so that
1065      * if all 8 keyslots are active we only spend 1 second
1066      * in total time to check all keys */
1067     iters /= 8;
1068     if (iters > UINT32_MAX) {
1069         error_setg_errno(errp, ERANGE,
1070                          "PBKDF iterations %llu larger than %u",
1071                          (unsigned long long)iters, UINT32_MAX);
1072         goto error;
1073     }
1074     iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1075     luks->header.master_key_iterations = iters;
1076 
1077     /* Hash the master key, saving the result in the LUKS
1078      * header. This hash is used when opening the encrypted
1079      * device to verify that the user password unlocked a
1080      * valid master key
1081      */
1082     if (qcrypto_pbkdf2(luks_opts.hash_alg,
1083                        masterkey, luks->header.key_bytes,
1084                        luks->header.master_key_salt,
1085                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1086                        luks->header.master_key_iterations,
1087                        luks->header.master_key_digest,
1088                        QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1089                        errp) < 0) {
1090         goto error;
1091     }
1092 
1093 
1094     /* Although LUKS has multiple key slots, we're just going
1095      * to use the first key slot */
1096     splitkeylen = luks->header.key_bytes * QCRYPTO_BLOCK_LUKS_STRIPES;
1097     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1098         luks->header.key_slots[i].active = i == 0 ?
1099             QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED :
1100             QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1101         luks->header.key_slots[i].stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
1102 
1103         /* This calculation doesn't match that shown in the spec,
1104          * but instead follows the cryptsetup implementation.
1105          */
1106         luks->header.key_slots[i].key_offset =
1107             (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1108              QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
1109             (ROUND_UP(DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
1110                       (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1111                        QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) * i);
1112     }
1113 
1114     if (qcrypto_random_bytes(luks->header.key_slots[0].salt,
1115                              QCRYPTO_BLOCK_LUKS_SALT_LEN,
1116                              errp) < 0) {
1117         goto error;
1118     }
1119 
1120     /* Again we determine how many iterations are required to
1121      * hash the user password while consuming 1 second of compute
1122      * time */
1123     iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1124                                        (uint8_t *)password, strlen(password),
1125                                        luks->header.key_slots[0].salt,
1126                                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1127                                        luks->header.key_bytes,
1128                                        &local_err);
1129     if (local_err) {
1130         error_propagate(errp, local_err);
1131         goto error;
1132     }
1133 
1134     if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1135         error_setg_errno(errp, ERANGE,
1136                          "PBKDF iterations %llu too large to scale",
1137                          (unsigned long long)iters);
1138         goto error;
1139     }
1140 
1141     /* iter_time was in millis, but count_iters reported for secs */
1142     iters = iters * luks_opts.iter_time / 1000;
1143 
1144     if (iters > UINT32_MAX) {
1145         error_setg_errno(errp, ERANGE,
1146                          "PBKDF iterations %llu larger than %u",
1147                          (unsigned long long)iters, UINT32_MAX);
1148         goto error;
1149     }
1150 
1151     luks->header.key_slots[0].iterations =
1152         MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
1153 
1154 
1155     /* Generate a key that we'll use to encrypt the master
1156      * key, from the user's password
1157      */
1158     slotkey = g_new0(uint8_t, luks->header.key_bytes);
1159     if (qcrypto_pbkdf2(luks_opts.hash_alg,
1160                        (uint8_t *)password, strlen(password),
1161                        luks->header.key_slots[0].salt,
1162                        QCRYPTO_BLOCK_LUKS_SALT_LEN,
1163                        luks->header.key_slots[0].iterations,
1164                        slotkey, luks->header.key_bytes,
1165                        errp) < 0) {
1166         goto error;
1167     }
1168 
1169 
1170     /* Setup the encryption objects needed to encrypt the
1171      * master key material
1172      */
1173     cipher = qcrypto_cipher_new(luks_opts.cipher_alg,
1174                                 luks_opts.cipher_mode,
1175                                 slotkey, luks->header.key_bytes,
1176                                 errp);
1177     if (!cipher) {
1178         goto error;
1179     }
1180 
1181     ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1182                               ivcipheralg,
1183                               luks_opts.ivgen_hash_alg,
1184                               slotkey, luks->header.key_bytes,
1185                               errp);
1186     if (!ivgen) {
1187         goto error;
1188     }
1189 
1190     /* Before storing the master key, we need to vastly
1191      * increase its size, as protection against forensic
1192      * disk data recovery */
1193     splitkey = g_new0(uint8_t, splitkeylen);
1194 
1195     if (qcrypto_afsplit_encode(luks_opts.hash_alg,
1196                                luks->header.key_bytes,
1197                                luks->header.key_slots[0].stripes,
1198                                masterkey,
1199                                splitkey,
1200                                errp) < 0) {
1201         goto error;
1202     }
1203 
1204     /* Now we encrypt the split master key with the key generated
1205      * from the user's password, before storing it */
1206     if (qcrypto_block_cipher_encrypt_helper(cipher, block->niv, ivgen,
1207                                             QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1208                                             0,
1209                                             splitkey,
1210                                             splitkeylen,
1211                                             errp) < 0) {
1212         goto error;
1213     }
1214 
1215 
1216     /* The total size of the LUKS headers is the partition header + key
1217      * slot headers, rounded up to the nearest sector, combined with
1218      * the size of each master key material region, also rounded up
1219      * to the nearest sector */
1220     luks->header.payload_offset =
1221         (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1222          QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
1223         (ROUND_UP(DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
1224                   (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1225                    QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) *
1226          QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1227 
1228     block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1229     block->payload_offset = luks->header.payload_offset *
1230         block->sector_size;
1231 
1232     /* Reserve header space to match payload offset */
1233     initfunc(block, block->payload_offset, opaque, &local_err);
1234     if (local_err) {
1235         error_propagate(errp, local_err);
1236         goto error;
1237     }
1238 
1239     /* Everything on disk uses Big Endian, so flip header fields
1240      * before writing them */
1241     cpu_to_be16s(&luks->header.version);
1242     cpu_to_be32s(&luks->header.payload_offset);
1243     cpu_to_be32s(&luks->header.key_bytes);
1244     cpu_to_be32s(&luks->header.master_key_iterations);
1245 
1246     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1247         cpu_to_be32s(&luks->header.key_slots[i].active);
1248         cpu_to_be32s(&luks->header.key_slots[i].iterations);
1249         cpu_to_be32s(&luks->header.key_slots[i].key_offset);
1250         cpu_to_be32s(&luks->header.key_slots[i].stripes);
1251     }
1252 
1253 
1254     /* Write out the partition header and key slot headers */
1255     writefunc(block, 0,
1256               (const uint8_t *)&luks->header,
1257               sizeof(luks->header),
1258               opaque,
1259               &local_err);
1260 
1261     /* Delay checking local_err until we've byte-swapped */
1262 
1263     /* Byte swap the header back to native, in case we need
1264      * to read it again later */
1265     be16_to_cpus(&luks->header.version);
1266     be32_to_cpus(&luks->header.payload_offset);
1267     be32_to_cpus(&luks->header.key_bytes);
1268     be32_to_cpus(&luks->header.master_key_iterations);
1269 
1270     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1271         be32_to_cpus(&luks->header.key_slots[i].active);
1272         be32_to_cpus(&luks->header.key_slots[i].iterations);
1273         be32_to_cpus(&luks->header.key_slots[i].key_offset);
1274         be32_to_cpus(&luks->header.key_slots[i].stripes);
1275     }
1276 
1277     if (local_err) {
1278         error_propagate(errp, local_err);
1279         goto error;
1280     }
1281 
1282     /* Write out the master key material, starting at the
1283      * sector immediately following the partition header. */
1284     if (writefunc(block,
1285                   luks->header.key_slots[0].key_offset *
1286                   QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1287                   splitkey, splitkeylen,
1288                   opaque,
1289                   errp) != splitkeylen) {
1290         goto error;
1291     }
1292 
1293     luks->cipher_alg = luks_opts.cipher_alg;
1294     luks->cipher_mode = luks_opts.cipher_mode;
1295     luks->ivgen_alg = luks_opts.ivgen_alg;
1296     luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
1297     luks->hash_alg = luks_opts.hash_alg;
1298 
1299     memset(masterkey, 0, luks->header.key_bytes);
1300     memset(slotkey, 0, luks->header.key_bytes);
1301 
1302     return 0;
1303 
1304  error:
1305     if (masterkey) {
1306         memset(masterkey, 0, luks->header.key_bytes);
1307     }
1308     if (slotkey) {
1309         memset(slotkey, 0, luks->header.key_bytes);
1310     }
1311 
1312     qcrypto_block_free_cipher(block);
1313     qcrypto_ivgen_free(block->ivgen);
1314 
1315     g_free(luks);
1316     return -1;
1317 }
1318 
1319 
1320 static int qcrypto_block_luks_get_info(QCryptoBlock *block,
1321                                        QCryptoBlockInfo *info,
1322                                        Error **errp)
1323 {
1324     QCryptoBlockLUKS *luks = block->opaque;
1325     QCryptoBlockInfoLUKSSlot *slot;
1326     QCryptoBlockInfoLUKSSlotList *slots = NULL, **prev = &info->u.luks.slots;
1327     size_t i;
1328 
1329     info->u.luks.cipher_alg = luks->cipher_alg;
1330     info->u.luks.cipher_mode = luks->cipher_mode;
1331     info->u.luks.ivgen_alg = luks->ivgen_alg;
1332     if (info->u.luks.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1333         info->u.luks.has_ivgen_hash_alg = true;
1334         info->u.luks.ivgen_hash_alg = luks->ivgen_hash_alg;
1335     }
1336     info->u.luks.hash_alg = luks->hash_alg;
1337     info->u.luks.payload_offset = block->payload_offset;
1338     info->u.luks.master_key_iters = luks->header.master_key_iterations;
1339     info->u.luks.uuid = g_strndup((const char *)luks->header.uuid,
1340                                   sizeof(luks->header.uuid));
1341 
1342     for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1343         slots = g_new0(QCryptoBlockInfoLUKSSlotList, 1);
1344         *prev = slots;
1345 
1346         slots->value = slot = g_new0(QCryptoBlockInfoLUKSSlot, 1);
1347         slot->active = luks->header.key_slots[i].active ==
1348             QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
1349         slot->key_offset = luks->header.key_slots[i].key_offset
1350              * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1351         if (slot->active) {
1352             slot->has_iters = true;
1353             slot->iters = luks->header.key_slots[i].iterations;
1354             slot->has_stripes = true;
1355             slot->stripes = luks->header.key_slots[i].stripes;
1356         }
1357 
1358         prev = &slots->next;
1359     }
1360 
1361     return 0;
1362 }
1363 
1364 
1365 static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1366 {
1367     g_free(block->opaque);
1368 }
1369 
1370 
1371 static int
1372 qcrypto_block_luks_decrypt(QCryptoBlock *block,
1373                            uint64_t offset,
1374                            uint8_t *buf,
1375                            size_t len,
1376                            Error **errp)
1377 {
1378     assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1379     assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1380     return qcrypto_block_decrypt_helper(block,
1381                                         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1382                                         offset, buf, len, errp);
1383 }
1384 
1385 
1386 static int
1387 qcrypto_block_luks_encrypt(QCryptoBlock *block,
1388                            uint64_t offset,
1389                            uint8_t *buf,
1390                            size_t len,
1391                            Error **errp)
1392 {
1393     assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1394     assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1395     return qcrypto_block_encrypt_helper(block,
1396                                         QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1397                                         offset, buf, len, errp);
1398 }
1399 
1400 
1401 const QCryptoBlockDriver qcrypto_block_driver_luks = {
1402     .open = qcrypto_block_luks_open,
1403     .create = qcrypto_block_luks_create,
1404     .get_info = qcrypto_block_luks_get_info,
1405     .cleanup = qcrypto_block_luks_cleanup,
1406     .decrypt = qcrypto_block_luks_decrypt,
1407     .encrypt = qcrypto_block_luks_encrypt,
1408     .has_format = qcrypto_block_luks_has_format,
1409 };
1410