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