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