block: move restarting of throttled reqs to block/throttle-groups.c
[qemu/ar7.git] / crypto / block-luks.c
blob439f89230c9f5a86a6d7217e3b8951a3b994e339
1 /*
2 * QEMU Crypto block device encryption LUKS format
4 * Copyright (c) 2015-2016 Red Hat, Inc.
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.
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.
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/>.
21 #include "qemu/osdep.h"
22 #include "qapi/error.h"
24 #include "crypto/block-luks.h"
26 #include "crypto/hash.h"
27 #include "crypto/afsplit.h"
28 #include "crypto/pbkdf.h"
29 #include "crypto/secret.h"
30 #include "crypto/random.h"
32 #ifdef CONFIG_UUID
33 #include <uuid/uuid.h>
34 #endif
36 #include "qemu/coroutine.h"
39 * Reference for the LUKS format implemented here is
41 * docs/on-disk-format.pdf
43 * in 'cryptsetup' package source code
45 * This file implements the 1.2.1 specification, dated
46 * Oct 16, 2011.
49 typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
50 typedef struct QCryptoBlockLUKSHeader QCryptoBlockLUKSHeader;
51 typedef struct QCryptoBlockLUKSKeySlot QCryptoBlockLUKSKeySlot;
54 /* The following constants are all defined by the LUKS spec */
55 #define QCRYPTO_BLOCK_LUKS_VERSION 1
57 #define QCRYPTO_BLOCK_LUKS_MAGIC_LEN 6
58 #define QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN 32
59 #define QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN 32
60 #define QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN 32
61 #define QCRYPTO_BLOCK_LUKS_DIGEST_LEN 20
62 #define QCRYPTO_BLOCK_LUKS_SALT_LEN 32
63 #define QCRYPTO_BLOCK_LUKS_UUID_LEN 40
64 #define QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS 8
65 #define QCRYPTO_BLOCK_LUKS_STRIPES 4000
66 #define QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS 1000
67 #define QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS 1000
68 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET 4096
70 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED 0x0000DEAD
71 #define QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED 0x00AC71F3
73 #define QCRYPTO_BLOCK_LUKS_SECTOR_SIZE 512LL
75 static const char qcrypto_block_luks_magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN] = {
76 'L', 'U', 'K', 'S', 0xBA, 0xBE
79 typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
80 struct QCryptoBlockLUKSNameMap {
81 const char *name;
82 int id;
85 typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
86 struct QCryptoBlockLUKSCipherSizeMap {
87 uint32_t key_bytes;
88 int id;
90 typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
91 struct QCryptoBlockLUKSCipherNameMap {
92 const char *name;
93 const QCryptoBlockLUKSCipherSizeMap *sizes;
97 static const QCryptoBlockLUKSCipherSizeMap
98 qcrypto_block_luks_cipher_size_map_aes[] = {
99 { 16, QCRYPTO_CIPHER_ALG_AES_128 },
100 { 24, QCRYPTO_CIPHER_ALG_AES_192 },
101 { 32, QCRYPTO_CIPHER_ALG_AES_256 },
102 { 0, 0 },
105 static const QCryptoBlockLUKSCipherSizeMap
106 qcrypto_block_luks_cipher_size_map_cast5[] = {
107 { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
108 { 0, 0 },
111 static const QCryptoBlockLUKSCipherSizeMap
112 qcrypto_block_luks_cipher_size_map_serpent[] = {
113 { 16, QCRYPTO_CIPHER_ALG_SERPENT_128 },
114 { 24, QCRYPTO_CIPHER_ALG_SERPENT_192 },
115 { 32, QCRYPTO_CIPHER_ALG_SERPENT_256 },
116 { 0, 0 },
119 static const QCryptoBlockLUKSCipherSizeMap
120 qcrypto_block_luks_cipher_size_map_twofish[] = {
121 { 16, QCRYPTO_CIPHER_ALG_TWOFISH_128 },
122 { 24, QCRYPTO_CIPHER_ALG_TWOFISH_192 },
123 { 32, QCRYPTO_CIPHER_ALG_TWOFISH_256 },
124 { 0, 0 },
127 static const QCryptoBlockLUKSCipherNameMap
128 qcrypto_block_luks_cipher_name_map[] = {
129 { "aes", qcrypto_block_luks_cipher_size_map_aes },
130 { "cast5", qcrypto_block_luks_cipher_size_map_cast5 },
131 { "serpent", qcrypto_block_luks_cipher_size_map_serpent },
132 { "twofish", qcrypto_block_luks_cipher_size_map_twofish },
137 * This struct is written to disk in big-endian format,
138 * but operated upon in native-endian format.
140 struct QCryptoBlockLUKSKeySlot {
141 /* state of keyslot, enabled/disable */
142 uint32_t active;
143 /* iterations for PBKDF2 */
144 uint32_t iterations;
145 /* salt for PBKDF2 */
146 uint8_t salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
147 /* start sector of key material */
148 uint32_t key_offset;
149 /* number of anti-forensic stripes */
150 uint32_t stripes;
151 } QEMU_PACKED;
153 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSKeySlot) != 48);
157 * This struct is written to disk in big-endian format,
158 * but operated upon in native-endian format.
160 struct QCryptoBlockLUKSHeader {
161 /* 'L', 'U', 'K', 'S', '0xBA', '0xBE' */
162 char magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN];
164 /* LUKS version, currently 1 */
165 uint16_t version;
167 /* cipher name specification (aes, etc) */
168 char cipher_name[QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN];
170 /* cipher mode specification (cbc-plain, xts-essiv:sha256, etc) */
171 char cipher_mode[QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN];
173 /* hash specification (sha256, etc) */
174 char hash_spec[QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN];
176 /* start offset of the volume data (in 512 byte sectors) */
177 uint32_t payload_offset;
179 /* Number of key bytes */
180 uint32_t key_bytes;
182 /* master key checksum after PBKDF2 */
183 uint8_t master_key_digest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
185 /* salt for master key PBKDF2 */
186 uint8_t master_key_salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
188 /* iterations for master key PBKDF2 */
189 uint32_t master_key_iterations;
191 /* UUID of the partition in standard ASCII representation */
192 uint8_t uuid[QCRYPTO_BLOCK_LUKS_UUID_LEN];
194 /* key slots */
195 QCryptoBlockLUKSKeySlot key_slots[QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS];
196 } QEMU_PACKED;
198 QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSHeader) != 592);
201 struct QCryptoBlockLUKS {
202 QCryptoBlockLUKSHeader header;
206 static int qcrypto_block_luks_cipher_name_lookup(const char *name,
207 QCryptoCipherMode mode,
208 uint32_t key_bytes,
209 Error **errp)
211 const QCryptoBlockLUKSCipherNameMap *map =
212 qcrypto_block_luks_cipher_name_map;
213 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
214 size_t i, j;
216 if (mode == QCRYPTO_CIPHER_MODE_XTS) {
217 key_bytes /= 2;
220 for (i = 0; i < maplen; i++) {
221 if (!g_str_equal(map[i].name, name)) {
222 continue;
224 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
225 if (map[i].sizes[j].key_bytes == key_bytes) {
226 return map[i].sizes[j].id;
231 error_setg(errp, "Algorithm %s with key size %d bytes not supported",
232 name, key_bytes);
233 return 0;
236 static const char *
237 qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
238 Error **errp)
240 const QCryptoBlockLUKSCipherNameMap *map =
241 qcrypto_block_luks_cipher_name_map;
242 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
243 size_t i, j;
244 for (i = 0; i < maplen; i++) {
245 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
246 if (map[i].sizes[j].id == alg) {
247 return map[i].name;
252 error_setg(errp, "Algorithm '%s' not supported",
253 QCryptoCipherAlgorithm_lookup[alg]);
254 return NULL;
257 /* XXX replace with qapi_enum_parse() in future, when we can
258 * make that function emit a more friendly error message */
259 static int qcrypto_block_luks_name_lookup(const char *name,
260 const char *const *map,
261 size_t maplen,
262 const char *type,
263 Error **errp)
265 size_t i;
266 for (i = 0; i < maplen; i++) {
267 if (g_str_equal(map[i], name)) {
268 return i;
272 error_setg(errp, "%s %s not supported", type, name);
273 return 0;
276 #define qcrypto_block_luks_cipher_mode_lookup(name, errp) \
277 qcrypto_block_luks_name_lookup(name, \
278 QCryptoCipherMode_lookup, \
279 QCRYPTO_CIPHER_MODE__MAX, \
280 "Cipher mode", \
281 errp)
283 #define qcrypto_block_luks_hash_name_lookup(name, errp) \
284 qcrypto_block_luks_name_lookup(name, \
285 QCryptoHashAlgorithm_lookup, \
286 QCRYPTO_HASH_ALG__MAX, \
287 "Hash algorithm", \
288 errp)
290 #define qcrypto_block_luks_ivgen_name_lookup(name, errp) \
291 qcrypto_block_luks_name_lookup(name, \
292 QCryptoIVGenAlgorithm_lookup, \
293 QCRYPTO_IVGEN_ALG__MAX, \
294 "IV generator", \
295 errp)
298 static bool
299 qcrypto_block_luks_has_format(const uint8_t *buf,
300 size_t buf_size)
302 const QCryptoBlockLUKSHeader *luks_header = (const void *)buf;
304 if (buf_size >= offsetof(QCryptoBlockLUKSHeader, cipher_name) &&
305 memcmp(luks_header->magic, qcrypto_block_luks_magic,
306 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) == 0 &&
307 be16_to_cpu(luks_header->version) == QCRYPTO_BLOCK_LUKS_VERSION) {
308 return true;
309 } else {
310 return false;
316 * Deal with a quirk of dm-crypt usage of ESSIV.
318 * When calculating ESSIV IVs, the cipher length used by ESSIV
319 * may be different from the cipher length used for the block
320 * encryption, becauses dm-crypt uses the hash digest length
321 * as the key size. ie, if you have AES 128 as the block cipher
322 * and SHA 256 as ESSIV hash, then ESSIV will use AES 256 as
323 * the cipher since that gets a key length matching the digest
324 * size, not AES 128 with truncated digest as might be imagined
326 static QCryptoCipherAlgorithm
327 qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
328 QCryptoHashAlgorithm hash,
329 Error **errp)
331 size_t digestlen = qcrypto_hash_digest_len(hash);
332 size_t keylen = qcrypto_cipher_get_key_len(cipher);
333 if (digestlen == keylen) {
334 return cipher;
337 switch (cipher) {
338 case QCRYPTO_CIPHER_ALG_AES_128:
339 case QCRYPTO_CIPHER_ALG_AES_192:
340 case QCRYPTO_CIPHER_ALG_AES_256:
341 if (digestlen == qcrypto_cipher_get_key_len(
342 QCRYPTO_CIPHER_ALG_AES_128)) {
343 return QCRYPTO_CIPHER_ALG_AES_128;
344 } else if (digestlen == qcrypto_cipher_get_key_len(
345 QCRYPTO_CIPHER_ALG_AES_192)) {
346 return QCRYPTO_CIPHER_ALG_AES_192;
347 } else if (digestlen == qcrypto_cipher_get_key_len(
348 QCRYPTO_CIPHER_ALG_AES_256)) {
349 return QCRYPTO_CIPHER_ALG_AES_256;
350 } else {
351 error_setg(errp, "No AES cipher with key size %zu available",
352 digestlen);
353 return 0;
355 break;
356 case QCRYPTO_CIPHER_ALG_SERPENT_128:
357 case QCRYPTO_CIPHER_ALG_SERPENT_192:
358 case QCRYPTO_CIPHER_ALG_SERPENT_256:
359 if (digestlen == qcrypto_cipher_get_key_len(
360 QCRYPTO_CIPHER_ALG_SERPENT_128)) {
361 return QCRYPTO_CIPHER_ALG_SERPENT_128;
362 } else if (digestlen == qcrypto_cipher_get_key_len(
363 QCRYPTO_CIPHER_ALG_SERPENT_192)) {
364 return QCRYPTO_CIPHER_ALG_SERPENT_192;
365 } else if (digestlen == qcrypto_cipher_get_key_len(
366 QCRYPTO_CIPHER_ALG_SERPENT_256)) {
367 return QCRYPTO_CIPHER_ALG_SERPENT_256;
368 } else {
369 error_setg(errp, "No Serpent cipher with key size %zu available",
370 digestlen);
371 return 0;
373 break;
374 case QCRYPTO_CIPHER_ALG_TWOFISH_128:
375 case QCRYPTO_CIPHER_ALG_TWOFISH_192:
376 case QCRYPTO_CIPHER_ALG_TWOFISH_256:
377 if (digestlen == qcrypto_cipher_get_key_len(
378 QCRYPTO_CIPHER_ALG_TWOFISH_128)) {
379 return QCRYPTO_CIPHER_ALG_TWOFISH_128;
380 } else if (digestlen == qcrypto_cipher_get_key_len(
381 QCRYPTO_CIPHER_ALG_TWOFISH_192)) {
382 return QCRYPTO_CIPHER_ALG_TWOFISH_192;
383 } else if (digestlen == qcrypto_cipher_get_key_len(
384 QCRYPTO_CIPHER_ALG_TWOFISH_256)) {
385 return QCRYPTO_CIPHER_ALG_TWOFISH_256;
386 } else {
387 error_setg(errp, "No Twofish cipher with key size %zu available",
388 digestlen);
389 return 0;
391 break;
392 default:
393 error_setg(errp, "Cipher %s not supported with essiv",
394 QCryptoCipherAlgorithm_lookup[cipher]);
395 return 0;
400 * Given a key slot, and user password, this will attempt to unlock
401 * the master encryption key from the key slot.
403 * Returns:
404 * 0 if the key slot is disabled, or key could not be decrypted
405 * with the provided password
406 * 1 if the key slot is enabled, and key decrypted successfully
407 * with the provided password
408 * -1 if a fatal error occurred loading the key
410 static int
411 qcrypto_block_luks_load_key(QCryptoBlock *block,
412 QCryptoBlockLUKSKeySlot *slot,
413 const char *password,
414 QCryptoCipherAlgorithm cipheralg,
415 QCryptoCipherMode ciphermode,
416 QCryptoHashAlgorithm hash,
417 QCryptoIVGenAlgorithm ivalg,
418 QCryptoCipherAlgorithm ivcipheralg,
419 QCryptoHashAlgorithm ivhash,
420 uint8_t *masterkey,
421 size_t masterkeylen,
422 QCryptoBlockReadFunc readfunc,
423 void *opaque,
424 Error **errp)
426 QCryptoBlockLUKS *luks = block->opaque;
427 uint8_t *splitkey;
428 size_t splitkeylen;
429 uint8_t *possiblekey;
430 int ret = -1;
431 ssize_t rv;
432 QCryptoCipher *cipher = NULL;
433 uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
434 QCryptoIVGen *ivgen = NULL;
435 size_t niv;
437 if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
438 return 0;
441 splitkeylen = masterkeylen * slot->stripes;
442 splitkey = g_new0(uint8_t, splitkeylen);
443 possiblekey = g_new0(uint8_t, masterkeylen);
446 * The user password is used to generate a (possible)
447 * decryption key. This may or may not successfully
448 * decrypt the master key - we just blindly assume
449 * the key is correct and validate the results of
450 * decryption later.
452 if (qcrypto_pbkdf2(hash,
453 (const uint8_t *)password, strlen(password),
454 slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
455 slot->iterations,
456 possiblekey, masterkeylen,
457 errp) < 0) {
458 goto cleanup;
462 * We need to read the master key material from the
463 * LUKS key material header. What we're reading is
464 * not the raw master key, but rather the data after
465 * it has been passed through AFSplit and the result
466 * then encrypted.
468 rv = readfunc(block,
469 slot->key_offset * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
470 splitkey, splitkeylen,
471 errp,
472 opaque);
473 if (rv < 0) {
474 goto cleanup;
478 /* Setup the cipher/ivgen that we'll use to try to decrypt
479 * the split master key material */
480 cipher = qcrypto_cipher_new(cipheralg, ciphermode,
481 possiblekey, masterkeylen,
482 errp);
483 if (!cipher) {
484 goto cleanup;
487 niv = qcrypto_cipher_get_iv_len(cipheralg,
488 ciphermode);
489 ivgen = qcrypto_ivgen_new(ivalg,
490 ivcipheralg,
491 ivhash,
492 possiblekey, masterkeylen,
493 errp);
494 if (!ivgen) {
495 goto cleanup;
500 * The master key needs to be decrypted in the same
501 * way that the block device payload will be decrypted
502 * later. In particular we'll be using the IV generator
503 * to reset the encryption cipher every time the master
504 * key crosses a sector boundary.
506 if (qcrypto_block_decrypt_helper(cipher,
507 niv,
508 ivgen,
509 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
511 splitkey,
512 splitkeylen,
513 errp) < 0) {
514 goto cleanup;
518 * Now we've decrypted the split master key, join
519 * it back together to get the actual master key.
521 if (qcrypto_afsplit_decode(hash,
522 masterkeylen,
523 slot->stripes,
524 splitkey,
525 masterkey,
526 errp) < 0) {
527 goto cleanup;
532 * We still don't know that the masterkey we got is valid,
533 * because we just blindly assumed the user's password
534 * was correct. This is where we now verify it. We are
535 * creating a hash of the master key using PBKDF and
536 * then comparing that to the hash stored in the key slot
537 * header
539 if (qcrypto_pbkdf2(hash,
540 masterkey, masterkeylen,
541 luks->header.master_key_salt,
542 QCRYPTO_BLOCK_LUKS_SALT_LEN,
543 luks->header.master_key_iterations,
544 keydigest, G_N_ELEMENTS(keydigest),
545 errp) < 0) {
546 goto cleanup;
549 if (memcmp(keydigest, luks->header.master_key_digest,
550 QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
551 /* Success, we got the right master key */
552 ret = 1;
553 goto cleanup;
556 /* Fail, user's password was not valid for this key slot,
557 * tell caller to try another slot */
558 ret = 0;
560 cleanup:
561 qcrypto_ivgen_free(ivgen);
562 qcrypto_cipher_free(cipher);
563 g_free(splitkey);
564 g_free(possiblekey);
565 return ret;
570 * Given a user password, this will iterate over all key
571 * slots and try to unlock each active key slot using the
572 * password until it successfully obtains a master key.
574 * Returns 0 if a key was loaded, -1 if no keys could be loaded
576 static int
577 qcrypto_block_luks_find_key(QCryptoBlock *block,
578 const char *password,
579 QCryptoCipherAlgorithm cipheralg,
580 QCryptoCipherMode ciphermode,
581 QCryptoHashAlgorithm hash,
582 QCryptoIVGenAlgorithm ivalg,
583 QCryptoCipherAlgorithm ivcipheralg,
584 QCryptoHashAlgorithm ivhash,
585 uint8_t **masterkey,
586 size_t *masterkeylen,
587 QCryptoBlockReadFunc readfunc,
588 void *opaque,
589 Error **errp)
591 QCryptoBlockLUKS *luks = block->opaque;
592 size_t i;
593 int rv;
595 *masterkey = g_new0(uint8_t, luks->header.key_bytes);
596 *masterkeylen = luks->header.key_bytes;
598 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
599 rv = qcrypto_block_luks_load_key(block,
600 &luks->header.key_slots[i],
601 password,
602 cipheralg,
603 ciphermode,
604 hash,
605 ivalg,
606 ivcipheralg,
607 ivhash,
608 *masterkey,
609 *masterkeylen,
610 readfunc,
611 opaque,
612 errp);
613 if (rv < 0) {
614 goto error;
616 if (rv == 1) {
617 return 0;
621 error_setg(errp, "Invalid password, cannot unlock any keyslot");
623 error:
624 g_free(*masterkey);
625 *masterkey = NULL;
626 *masterkeylen = 0;
627 return -1;
631 static int
632 qcrypto_block_luks_open(QCryptoBlock *block,
633 QCryptoBlockOpenOptions *options,
634 QCryptoBlockReadFunc readfunc,
635 void *opaque,
636 unsigned int flags,
637 Error **errp)
639 QCryptoBlockLUKS *luks;
640 Error *local_err = NULL;
641 int ret = 0;
642 size_t i;
643 ssize_t rv;
644 uint8_t *masterkey = NULL;
645 size_t masterkeylen;
646 char *ivgen_name, *ivhash_name;
647 QCryptoCipherMode ciphermode;
648 QCryptoCipherAlgorithm cipheralg;
649 QCryptoIVGenAlgorithm ivalg;
650 QCryptoCipherAlgorithm ivcipheralg;
651 QCryptoHashAlgorithm hash;
652 QCryptoHashAlgorithm ivhash;
653 char *password = NULL;
655 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
656 if (!options->u.luks.key_secret) {
657 error_setg(errp, "Parameter 'key-secret' is required for cipher");
658 return -1;
660 password = qcrypto_secret_lookup_as_utf8(
661 options->u.luks.key_secret, errp);
662 if (!password) {
663 return -1;
667 luks = g_new0(QCryptoBlockLUKS, 1);
668 block->opaque = luks;
670 /* Read the entire LUKS header, minus the key material from
671 * the underlying device */
672 rv = readfunc(block, 0,
673 (uint8_t *)&luks->header,
674 sizeof(luks->header),
675 errp,
676 opaque);
677 if (rv < 0) {
678 ret = rv;
679 goto fail;
682 /* The header is always stored in big-endian format, so
683 * convert everything to native */
684 be16_to_cpus(&luks->header.version);
685 be32_to_cpus(&luks->header.payload_offset);
686 be32_to_cpus(&luks->header.key_bytes);
687 be32_to_cpus(&luks->header.master_key_iterations);
689 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
690 be32_to_cpus(&luks->header.key_slots[i].active);
691 be32_to_cpus(&luks->header.key_slots[i].iterations);
692 be32_to_cpus(&luks->header.key_slots[i].key_offset);
693 be32_to_cpus(&luks->header.key_slots[i].stripes);
696 if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
697 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
698 error_setg(errp, "Volume is not in LUKS format");
699 ret = -EINVAL;
700 goto fail;
702 if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
703 error_setg(errp, "LUKS version %" PRIu32 " is not supported",
704 luks->header.version);
705 ret = -ENOTSUP;
706 goto fail;
710 * The cipher_mode header contains a string that we have
711 * to further parse, of the format
713 * <cipher-mode>-<iv-generator>[:<iv-hash>]
715 * eg cbc-essiv:sha256, cbc-plain64
717 ivgen_name = strchr(luks->header.cipher_mode, '-');
718 if (!ivgen_name) {
719 ret = -EINVAL;
720 error_setg(errp, "Unexpected cipher mode string format %s",
721 luks->header.cipher_mode);
722 goto fail;
724 *ivgen_name = '\0';
725 ivgen_name++;
727 ivhash_name = strchr(ivgen_name, ':');
728 if (!ivhash_name) {
729 ivhash = 0;
730 } else {
731 *ivhash_name = '\0';
732 ivhash_name++;
734 ivhash = qcrypto_block_luks_hash_name_lookup(ivhash_name,
735 &local_err);
736 if (local_err) {
737 ret = -ENOTSUP;
738 error_propagate(errp, local_err);
739 goto fail;
743 ciphermode = qcrypto_block_luks_cipher_mode_lookup(luks->header.cipher_mode,
744 &local_err);
745 if (local_err) {
746 ret = -ENOTSUP;
747 error_propagate(errp, local_err);
748 goto fail;
751 cipheralg = qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
752 ciphermode,
753 luks->header.key_bytes,
754 &local_err);
755 if (local_err) {
756 ret = -ENOTSUP;
757 error_propagate(errp, local_err);
758 goto fail;
761 hash = qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
762 &local_err);
763 if (local_err) {
764 ret = -ENOTSUP;
765 error_propagate(errp, local_err);
766 goto fail;
769 ivalg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
770 &local_err);
771 if (local_err) {
772 ret = -ENOTSUP;
773 error_propagate(errp, local_err);
774 goto fail;
777 if (ivalg == QCRYPTO_IVGEN_ALG_ESSIV) {
778 ivcipheralg = qcrypto_block_luks_essiv_cipher(cipheralg,
779 ivhash,
780 &local_err);
781 if (local_err) {
782 ret = -ENOTSUP;
783 error_propagate(errp, local_err);
784 goto fail;
786 } else {
787 ivcipheralg = cipheralg;
790 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
791 /* Try to find which key slot our password is valid for
792 * and unlock the master key from that slot.
794 if (qcrypto_block_luks_find_key(block,
795 password,
796 cipheralg, ciphermode,
797 hash,
798 ivalg,
799 ivcipheralg,
800 ivhash,
801 &masterkey, &masterkeylen,
802 readfunc, opaque,
803 errp) < 0) {
804 ret = -EACCES;
805 goto fail;
808 /* We have a valid master key now, so can setup the
809 * block device payload decryption objects
811 block->kdfhash = hash;
812 block->niv = qcrypto_cipher_get_iv_len(cipheralg,
813 ciphermode);
814 block->ivgen = qcrypto_ivgen_new(ivalg,
815 ivcipheralg,
816 ivhash,
817 masterkey, masterkeylen,
818 errp);
819 if (!block->ivgen) {
820 ret = -ENOTSUP;
821 goto fail;
824 block->cipher = qcrypto_cipher_new(cipheralg,
825 ciphermode,
826 masterkey, masterkeylen,
827 errp);
828 if (!block->cipher) {
829 ret = -ENOTSUP;
830 goto fail;
834 block->payload_offset = luks->header.payload_offset *
835 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
837 g_free(masterkey);
838 g_free(password);
840 return 0;
842 fail:
843 g_free(masterkey);
844 qcrypto_cipher_free(block->cipher);
845 qcrypto_ivgen_free(block->ivgen);
846 g_free(luks);
847 g_free(password);
848 return ret;
852 static int
853 qcrypto_block_luks_uuid_gen(uint8_t *uuidstr, Error **errp)
855 #ifdef CONFIG_UUID
856 uuid_t uuid;
857 uuid_generate(uuid);
858 uuid_unparse(uuid, (char *)uuidstr);
859 return 0;
860 #else
861 error_setg(errp, "Unable to generate uuids on this platform");
862 return -1;
863 #endif
866 static int
867 qcrypto_block_luks_create(QCryptoBlock *block,
868 QCryptoBlockCreateOptions *options,
869 QCryptoBlockInitFunc initfunc,
870 QCryptoBlockWriteFunc writefunc,
871 void *opaque,
872 Error **errp)
874 QCryptoBlockLUKS *luks;
875 QCryptoBlockCreateOptionsLUKS luks_opts;
876 Error *local_err = NULL;
877 uint8_t *masterkey = NULL;
878 uint8_t *slotkey = NULL;
879 uint8_t *splitkey = NULL;
880 size_t splitkeylen = 0;
881 size_t i;
882 QCryptoCipher *cipher = NULL;
883 QCryptoIVGen *ivgen = NULL;
884 char *password;
885 const char *cipher_alg;
886 const char *cipher_mode;
887 const char *ivgen_alg;
888 const char *ivgen_hash_alg = NULL;
889 const char *hash_alg;
890 char *cipher_mode_spec = NULL;
891 QCryptoCipherAlgorithm ivcipheralg = 0;
893 memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
894 if (!luks_opts.has_cipher_alg) {
895 luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
897 if (!luks_opts.has_cipher_mode) {
898 luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
900 if (!luks_opts.has_ivgen_alg) {
901 luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
903 if (!luks_opts.has_hash_alg) {
904 luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
907 if (!options->u.luks.key_secret) {
908 error_setg(errp, "Parameter 'key-secret' is required for cipher");
909 return -1;
911 password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
912 if (!password) {
913 return -1;
916 luks = g_new0(QCryptoBlockLUKS, 1);
917 block->opaque = luks;
919 memcpy(luks->header.magic, qcrypto_block_luks_magic,
920 QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
922 /* We populate the header in native endianness initially and
923 * then convert everything to big endian just before writing
924 * it out to disk
926 luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
927 if (qcrypto_block_luks_uuid_gen(luks->header.uuid,
928 errp) < 0) {
929 goto error;
932 cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
933 errp);
934 if (!cipher_alg) {
935 goto error;
938 cipher_mode = QCryptoCipherMode_lookup[luks_opts.cipher_mode];
939 ivgen_alg = QCryptoIVGenAlgorithm_lookup[luks_opts.ivgen_alg];
940 if (luks_opts.has_ivgen_hash_alg) {
941 ivgen_hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.ivgen_hash_alg];
942 cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
943 ivgen_hash_alg);
944 } else {
945 cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
947 hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.hash_alg];
950 if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
951 error_setg(errp, "Cipher name '%s' is too long for LUKS header",
952 cipher_alg);
953 goto error;
955 if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
956 error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
957 cipher_mode_spec);
958 goto error;
960 if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
961 error_setg(errp, "Hash name '%s' is too long for LUKS header",
962 hash_alg);
963 goto error;
966 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
967 ivcipheralg = qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
968 luks_opts.ivgen_hash_alg,
969 &local_err);
970 if (local_err) {
971 error_propagate(errp, local_err);
972 goto error;
974 } else {
975 ivcipheralg = luks_opts.cipher_alg;
978 strcpy(luks->header.cipher_name, cipher_alg);
979 strcpy(luks->header.cipher_mode, cipher_mode_spec);
980 strcpy(luks->header.hash_spec, hash_alg);
982 luks->header.key_bytes = qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
983 if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
984 luks->header.key_bytes *= 2;
987 /* Generate the salt used for hashing the master key
988 * with PBKDF later
990 if (qcrypto_random_bytes(luks->header.master_key_salt,
991 QCRYPTO_BLOCK_LUKS_SALT_LEN,
992 errp) < 0) {
993 goto error;
996 /* Generate random master key */
997 masterkey = g_new0(uint8_t, luks->header.key_bytes);
998 if (qcrypto_random_bytes(masterkey,
999 luks->header.key_bytes, errp) < 0) {
1000 goto error;
1004 /* Setup the block device payload encryption objects */
1005 block->cipher = qcrypto_cipher_new(luks_opts.cipher_alg,
1006 luks_opts.cipher_mode,
1007 masterkey, luks->header.key_bytes,
1008 errp);
1009 if (!block->cipher) {
1010 goto error;
1013 block->kdfhash = luks_opts.hash_alg;
1014 block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1015 luks_opts.cipher_mode);
1016 block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1017 ivcipheralg,
1018 luks_opts.ivgen_hash_alg,
1019 masterkey, luks->header.key_bytes,
1020 errp);
1022 if (!block->ivgen) {
1023 goto error;
1027 /* Determine how many iterations we need to hash the master
1028 * key, in order to have 1 second of compute time used
1030 luks->header.master_key_iterations =
1031 qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1032 masterkey, luks->header.key_bytes,
1033 luks->header.master_key_salt,
1034 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1035 &local_err);
1036 if (local_err) {
1037 error_propagate(errp, local_err);
1038 goto error;
1041 /* Why /= 8 ? That matches cryptsetup, but there's no
1042 * explanation why they chose /= 8... Probably so that
1043 * if all 8 keyslots are active we only spend 1 second
1044 * in total time to check all keys */
1045 luks->header.master_key_iterations /= 8;
1046 luks->header.master_key_iterations = MAX(
1047 luks->header.master_key_iterations,
1048 QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1051 /* Hash the master key, saving the result in the LUKS
1052 * header. This hash is used when opening the encrypted
1053 * device to verify that the user password unlocked a
1054 * valid master key
1056 if (qcrypto_pbkdf2(luks_opts.hash_alg,
1057 masterkey, luks->header.key_bytes,
1058 luks->header.master_key_salt,
1059 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1060 luks->header.master_key_iterations,
1061 luks->header.master_key_digest,
1062 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1063 errp) < 0) {
1064 goto error;
1068 /* Although LUKS has multiple key slots, we're just going
1069 * to use the first key slot */
1070 splitkeylen = luks->header.key_bytes * QCRYPTO_BLOCK_LUKS_STRIPES;
1071 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1072 luks->header.key_slots[i].active = i == 0 ?
1073 QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED :
1074 QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1075 luks->header.key_slots[i].stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
1077 /* This calculation doesn't match that shown in the spec,
1078 * but instead follows the cryptsetup implementation.
1080 luks->header.key_slots[i].key_offset =
1081 (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1082 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
1083 (ROUND_UP(((splitkeylen + (QCRYPTO_BLOCK_LUKS_SECTOR_SIZE - 1)) /
1084 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
1085 (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1086 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) * i);
1089 if (qcrypto_random_bytes(luks->header.key_slots[0].salt,
1090 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1091 errp) < 0) {
1092 goto error;
1095 /* Again we determine how many iterations are required to
1096 * hash the user password while consuming 1 second of compute
1097 * time */
1098 luks->header.key_slots[0].iterations =
1099 qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
1100 (uint8_t *)password, strlen(password),
1101 luks->header.key_slots[0].salt,
1102 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1103 &local_err);
1104 if (local_err) {
1105 error_propagate(errp, local_err);
1106 goto error;
1108 /* Why /= 2 ? That matches cryptsetup, but there's no
1109 * explanation why they chose /= 2... */
1110 luks->header.key_slots[0].iterations /= 2;
1111 luks->header.key_slots[0].iterations = MAX(
1112 luks->header.key_slots[0].iterations,
1113 QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
1116 /* Generate a key that we'll use to encrypt the master
1117 * key, from the user's password
1119 slotkey = g_new0(uint8_t, luks->header.key_bytes);
1120 if (qcrypto_pbkdf2(luks_opts.hash_alg,
1121 (uint8_t *)password, strlen(password),
1122 luks->header.key_slots[0].salt,
1123 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1124 luks->header.key_slots[0].iterations,
1125 slotkey, luks->header.key_bytes,
1126 errp) < 0) {
1127 goto error;
1131 /* Setup the encryption objects needed to encrypt the
1132 * master key material
1134 cipher = qcrypto_cipher_new(luks_opts.cipher_alg,
1135 luks_opts.cipher_mode,
1136 slotkey, luks->header.key_bytes,
1137 errp);
1138 if (!cipher) {
1139 goto error;
1142 ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
1143 ivcipheralg,
1144 luks_opts.ivgen_hash_alg,
1145 slotkey, luks->header.key_bytes,
1146 errp);
1147 if (!ivgen) {
1148 goto error;
1151 /* Before storing the master key, we need to vastly
1152 * increase its size, as protection against forensic
1153 * disk data recovery */
1154 splitkey = g_new0(uint8_t, splitkeylen);
1156 if (qcrypto_afsplit_encode(luks_opts.hash_alg,
1157 luks->header.key_bytes,
1158 luks->header.key_slots[0].stripes,
1159 masterkey,
1160 splitkey,
1161 errp) < 0) {
1162 goto error;
1165 /* Now we encrypt the split master key with the key generated
1166 * from the user's password, before storing it */
1167 if (qcrypto_block_encrypt_helper(cipher, block->niv, ivgen,
1168 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1170 splitkey,
1171 splitkeylen,
1172 errp) < 0) {
1173 goto error;
1177 /* The total size of the LUKS headers is the partition header + key
1178 * slot headers, rounded up to the nearest sector, combined with
1179 * the size of each master key material region, also rounded up
1180 * to the nearest sector */
1181 luks->header.payload_offset =
1182 (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1183 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE) +
1184 (ROUND_UP(((splitkeylen + (QCRYPTO_BLOCK_LUKS_SECTOR_SIZE - 1)) /
1185 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE),
1186 (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1187 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) *
1188 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1190 block->payload_offset = luks->header.payload_offset *
1191 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1193 /* Reserve header space to match payload offset */
1194 initfunc(block, block->payload_offset, &local_err, opaque);
1195 if (local_err) {
1196 error_propagate(errp, local_err);
1197 goto error;
1200 /* Everything on disk uses Big Endian, so flip header fields
1201 * before writing them */
1202 cpu_to_be16s(&luks->header.version);
1203 cpu_to_be32s(&luks->header.payload_offset);
1204 cpu_to_be32s(&luks->header.key_bytes);
1205 cpu_to_be32s(&luks->header.master_key_iterations);
1207 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1208 cpu_to_be32s(&luks->header.key_slots[i].active);
1209 cpu_to_be32s(&luks->header.key_slots[i].iterations);
1210 cpu_to_be32s(&luks->header.key_slots[i].key_offset);
1211 cpu_to_be32s(&luks->header.key_slots[i].stripes);
1215 /* Write out the partition header and key slot headers */
1216 writefunc(block, 0,
1217 (const uint8_t *)&luks->header,
1218 sizeof(luks->header),
1219 &local_err,
1220 opaque);
1222 /* Delay checking local_err until we've byte-swapped */
1224 /* Byte swap the header back to native, in case we need
1225 * to read it again later */
1226 be16_to_cpus(&luks->header.version);
1227 be32_to_cpus(&luks->header.payload_offset);
1228 be32_to_cpus(&luks->header.key_bytes);
1229 be32_to_cpus(&luks->header.master_key_iterations);
1231 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1232 be32_to_cpus(&luks->header.key_slots[i].active);
1233 be32_to_cpus(&luks->header.key_slots[i].iterations);
1234 be32_to_cpus(&luks->header.key_slots[i].key_offset);
1235 be32_to_cpus(&luks->header.key_slots[i].stripes);
1238 if (local_err) {
1239 error_propagate(errp, local_err);
1240 goto error;
1243 /* Write out the master key material, starting at the
1244 * sector immediately following the partition header. */
1245 if (writefunc(block,
1246 luks->header.key_slots[0].key_offset *
1247 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1248 splitkey, splitkeylen,
1249 errp,
1250 opaque) != splitkeylen) {
1251 goto error;
1254 memset(masterkey, 0, luks->header.key_bytes);
1255 g_free(masterkey);
1256 memset(slotkey, 0, luks->header.key_bytes);
1257 g_free(slotkey);
1258 g_free(splitkey);
1259 g_free(password);
1260 g_free(cipher_mode_spec);
1262 qcrypto_ivgen_free(ivgen);
1263 qcrypto_cipher_free(cipher);
1265 return 0;
1267 error:
1268 if (masterkey) {
1269 memset(masterkey, 0, luks->header.key_bytes);
1271 g_free(masterkey);
1272 if (slotkey) {
1273 memset(slotkey, 0, luks->header.key_bytes);
1275 g_free(slotkey);
1276 g_free(splitkey);
1277 g_free(password);
1278 g_free(cipher_mode_spec);
1280 qcrypto_ivgen_free(ivgen);
1281 qcrypto_cipher_free(cipher);
1283 g_free(luks);
1284 return -1;
1288 static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1290 g_free(block->opaque);
1294 static int
1295 qcrypto_block_luks_decrypt(QCryptoBlock *block,
1296 uint64_t startsector,
1297 uint8_t *buf,
1298 size_t len,
1299 Error **errp)
1301 return qcrypto_block_decrypt_helper(block->cipher,
1302 block->niv, block->ivgen,
1303 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1304 startsector, buf, len, errp);
1308 static int
1309 qcrypto_block_luks_encrypt(QCryptoBlock *block,
1310 uint64_t startsector,
1311 uint8_t *buf,
1312 size_t len,
1313 Error **errp)
1315 return qcrypto_block_encrypt_helper(block->cipher,
1316 block->niv, block->ivgen,
1317 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1318 startsector, buf, len, errp);
1322 const QCryptoBlockDriver qcrypto_block_driver_luks = {
1323 .open = qcrypto_block_luks_open,
1324 .create = qcrypto_block_luks_create,
1325 .cleanup = qcrypto_block_luks_cleanup,
1326 .decrypt = qcrypto_block_luks_decrypt,
1327 .encrypt = qcrypto_block_luks_encrypt,
1328 .has_format = qcrypto_block_luks_has_format,