blob: 45347adeeb71027cf8977f83389fb860c7429b1a [file] [log] [blame]
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001/*
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
Thomas Huthb7cbb872019-02-13 16:54:59 +01009 * version 2.1 of the License, or (at your option) any later version.
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010010 *
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"
Markus Armbrusterda34e652016-03-14 09:01:28 +010022#include "qapi/error.h"
Paolo Bonzini58369e22016-03-15 17:22:36 +010023#include "qemu/bswap.h"
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010024
Michael S. Tsirkin986bc8d2018-05-03 22:50:23 +030025#include "block-luks.h"
Daniel P. Berrangé36445ac2022-05-10 15:19:58 +010026#include "block-luks-priv.h"
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010027
28#include "crypto/hash.h"
29#include "crypto/afsplit.h"
30#include "crypto/pbkdf.h"
31#include "crypto/secret.h"
32#include "crypto/random.h"
Fam Zheng2ef950f2016-09-21 12:27:19 +080033#include "qemu/uuid.h"
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010034
Maxim Levitsky557d2bd2020-06-25 14:55:37 +020035#include "qemu/bitmap.h"
Yao Xingtao7cd9b9d2024-07-22 00:07:40 -040036#include "qemu/range.h"
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010037
38/*
39 * Reference for the LUKS format implemented here is
40 *
41 * docs/on-disk-format.pdf
42 *
43 * in 'cryptsetup' package source code
44 *
45 * This file implements the 1.2.1 specification, dated
46 * Oct 16, 2011.
47 */
48
49typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +010050
51typedef struct QCryptoBlockLUKSNameMap QCryptoBlockLUKSNameMap;
52struct QCryptoBlockLUKSNameMap {
53 const char *name;
54 int id;
55};
56
57typedef struct QCryptoBlockLUKSCipherSizeMap QCryptoBlockLUKSCipherSizeMap;
58struct QCryptoBlockLUKSCipherSizeMap {
59 uint32_t key_bytes;
60 int id;
61};
62typedef struct QCryptoBlockLUKSCipherNameMap QCryptoBlockLUKSCipherNameMap;
63struct QCryptoBlockLUKSCipherNameMap {
64 const char *name;
65 const QCryptoBlockLUKSCipherSizeMap *sizes;
66};
67
68
69static const QCryptoBlockLUKSCipherSizeMap
70qcrypto_block_luks_cipher_size_map_aes[] = {
71 { 16, QCRYPTO_CIPHER_ALG_AES_128 },
72 { 24, QCRYPTO_CIPHER_ALG_AES_192 },
73 { 32, QCRYPTO_CIPHER_ALG_AES_256 },
74 { 0, 0 },
75};
76
77static const QCryptoBlockLUKSCipherSizeMap
78qcrypto_block_luks_cipher_size_map_cast5[] = {
79 { 16, QCRYPTO_CIPHER_ALG_CAST5_128 },
80 { 0, 0 },
81};
82
83static const QCryptoBlockLUKSCipherSizeMap
84qcrypto_block_luks_cipher_size_map_serpent[] = {
85 { 16, QCRYPTO_CIPHER_ALG_SERPENT_128 },
86 { 24, QCRYPTO_CIPHER_ALG_SERPENT_192 },
87 { 32, QCRYPTO_CIPHER_ALG_SERPENT_256 },
88 { 0, 0 },
89};
90
91static const QCryptoBlockLUKSCipherSizeMap
92qcrypto_block_luks_cipher_size_map_twofish[] = {
93 { 16, QCRYPTO_CIPHER_ALG_TWOFISH_128 },
94 { 24, QCRYPTO_CIPHER_ALG_TWOFISH_192 },
95 { 32, QCRYPTO_CIPHER_ALG_TWOFISH_256 },
96 { 0, 0 },
97};
98
Hyman Huang52ed9f42023-12-07 23:47:35 +080099#ifdef CONFIG_CRYPTO_SM4
100static const QCryptoBlockLUKSCipherSizeMap
101qcrypto_block_luks_cipher_size_map_sm4[] = {
102 { 16, QCRYPTO_CIPHER_ALG_SM4},
103 { 0, 0 },
104};
105#endif
106
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100107static const QCryptoBlockLUKSCipherNameMap
108qcrypto_block_luks_cipher_name_map[] = {
109 { "aes", qcrypto_block_luks_cipher_size_map_aes },
110 { "cast5", qcrypto_block_luks_cipher_size_map_cast5 },
111 { "serpent", qcrypto_block_luks_cipher_size_map_serpent },
112 { "twofish", qcrypto_block_luks_cipher_size_map_twofish },
Hyman Huang52ed9f42023-12-07 23:47:35 +0800113#ifdef CONFIG_CRYPTO_SM4
114 { "sm4", qcrypto_block_luks_cipher_size_map_sm4},
115#endif
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100116};
117
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100118QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSKeySlot) != 48);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100119QEMU_BUILD_BUG_ON(sizeof(struct QCryptoBlockLUKSHeader) != 592);
120
121
122struct QCryptoBlockLUKS {
123 QCryptoBlockLUKSHeader header;
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100124
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300125 /* Main encryption algorithm used for encryption*/
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100126 QCryptoCipherAlgorithm cipher_alg;
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300127
128 /* Mode of encryption for the selected encryption algorithm */
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100129 QCryptoCipherMode cipher_mode;
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300130
131 /* Initialization vector generation algorithm */
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100132 QCryptoIVGenAlgorithm ivgen_alg;
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300133
134 /* Hash algorithm used for IV generation*/
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100135 QCryptoHashAlgorithm ivgen_hash_alg;
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300136
137 /*
138 * Encryption algorithm used for IV generation.
139 * Usually the same as main encryption algorithm
140 */
141 QCryptoCipherAlgorithm ivgen_cipher_alg;
142
143 /* Hash algorithm used in pbkdf2 function */
Daniel P. Berrange40c85022016-07-22 13:53:34 +0100144 QCryptoHashAlgorithm hash_alg;
Maxim Levitsky557d2bd2020-06-25 14:55:37 +0200145
146 /* Name of the secret that was used to open the image */
147 char *secret;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100148};
149
150
151static int qcrypto_block_luks_cipher_name_lookup(const char *name,
152 QCryptoCipherMode mode,
153 uint32_t key_bytes,
154 Error **errp)
155{
156 const QCryptoBlockLUKSCipherNameMap *map =
157 qcrypto_block_luks_cipher_name_map;
158 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
159 size_t i, j;
160
161 if (mode == QCRYPTO_CIPHER_MODE_XTS) {
162 key_bytes /= 2;
163 }
164
165 for (i = 0; i < maplen; i++) {
166 if (!g_str_equal(map[i].name, name)) {
167 continue;
168 }
169 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
170 if (map[i].sizes[j].key_bytes == key_bytes) {
171 return map[i].sizes[j].id;
172 }
173 }
174 }
175
Daniel P. Berrangé6c198932022-09-05 12:08:21 +0100176 error_setg(errp, "Algorithm '%s' with key size %d bytes not supported",
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100177 name, key_bytes);
178 return 0;
179}
180
181static const char *
182qcrypto_block_luks_cipher_alg_lookup(QCryptoCipherAlgorithm alg,
183 Error **errp)
184{
185 const QCryptoBlockLUKSCipherNameMap *map =
186 qcrypto_block_luks_cipher_name_map;
187 size_t maplen = G_N_ELEMENTS(qcrypto_block_luks_cipher_name_map);
188 size_t i, j;
189 for (i = 0; i < maplen; i++) {
190 for (j = 0; j < map[i].sizes[j].key_bytes; j++) {
191 if (map[i].sizes[j].id == alg) {
192 return map[i].name;
193 }
194 }
195 }
196
197 error_setg(errp, "Algorithm '%s' not supported",
Markus Armbruster977c7362017-08-24 10:46:08 +0200198 QCryptoCipherAlgorithm_str(alg));
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100199 return NULL;
200}
201
202/* XXX replace with qapi_enum_parse() in future, when we can
203 * make that function emit a more friendly error message */
204static int qcrypto_block_luks_name_lookup(const char *name,
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +0200205 const QEnumLookup *map,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100206 const char *type,
207 Error **errp)
208{
Markus Armbruster9ae33072017-08-24 10:46:04 +0200209 int ret = qapi_enum_parse(map, name, -1, NULL);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100210
Markus Armbruster9ae33072017-08-24 10:46:04 +0200211 if (ret < 0) {
Daniel P. Berrangé6c198932022-09-05 12:08:21 +0100212 error_setg(errp, "%s '%s' not supported", type, name);
Markus Armbruster9ae33072017-08-24 10:46:04 +0200213 return 0;
214 }
215 return ret;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100216}
217
218#define qcrypto_block_luks_cipher_mode_lookup(name, errp) \
219 qcrypto_block_luks_name_lookup(name, \
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +0200220 &QCryptoCipherMode_lookup, \
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100221 "Cipher mode", \
222 errp)
223
224#define qcrypto_block_luks_hash_name_lookup(name, errp) \
225 qcrypto_block_luks_name_lookup(name, \
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +0200226 &QCryptoHashAlgorithm_lookup, \
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100227 "Hash algorithm", \
228 errp)
229
230#define qcrypto_block_luks_ivgen_name_lookup(name, errp) \
231 qcrypto_block_luks_name_lookup(name, \
Marc-André Lureauf7abe0e2017-08-24 10:46:10 +0200232 &QCryptoIVGenAlgorithm_lookup, \
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100233 "IV generator", \
234 errp)
235
236
237static bool
238qcrypto_block_luks_has_format(const uint8_t *buf,
239 size_t buf_size)
240{
241 const QCryptoBlockLUKSHeader *luks_header = (const void *)buf;
242
243 if (buf_size >= offsetof(QCryptoBlockLUKSHeader, cipher_name) &&
244 memcmp(luks_header->magic, qcrypto_block_luks_magic,
245 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) == 0 &&
246 be16_to_cpu(luks_header->version) == QCRYPTO_BLOCK_LUKS_VERSION) {
247 return true;
248 } else {
249 return false;
250 }
251}
252
253
254/**
255 * Deal with a quirk of dm-crypt usage of ESSIV.
256 *
257 * When calculating ESSIV IVs, the cipher length used by ESSIV
258 * may be different from the cipher length used for the block
Michael Tokarev0a19d872023-07-14 14:33:49 +0300259 * encryption, because dm-crypt uses the hash digest length
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100260 * as the key size. ie, if you have AES 128 as the block cipher
261 * and SHA 256 as ESSIV hash, then ESSIV will use AES 256 as
262 * the cipher since that gets a key length matching the digest
263 * size, not AES 128 with truncated digest as might be imagined
264 */
265static QCryptoCipherAlgorithm
266qcrypto_block_luks_essiv_cipher(QCryptoCipherAlgorithm cipher,
267 QCryptoHashAlgorithm hash,
268 Error **errp)
269{
270 size_t digestlen = qcrypto_hash_digest_len(hash);
271 size_t keylen = qcrypto_cipher_get_key_len(cipher);
272 if (digestlen == keylen) {
273 return cipher;
274 }
275
276 switch (cipher) {
277 case QCRYPTO_CIPHER_ALG_AES_128:
278 case QCRYPTO_CIPHER_ALG_AES_192:
279 case QCRYPTO_CIPHER_ALG_AES_256:
280 if (digestlen == qcrypto_cipher_get_key_len(
281 QCRYPTO_CIPHER_ALG_AES_128)) {
282 return QCRYPTO_CIPHER_ALG_AES_128;
283 } else if (digestlen == qcrypto_cipher_get_key_len(
284 QCRYPTO_CIPHER_ALG_AES_192)) {
285 return QCRYPTO_CIPHER_ALG_AES_192;
286 } else if (digestlen == qcrypto_cipher_get_key_len(
287 QCRYPTO_CIPHER_ALG_AES_256)) {
288 return QCRYPTO_CIPHER_ALG_AES_256;
289 } else {
290 error_setg(errp, "No AES cipher with key size %zu available",
291 digestlen);
292 return 0;
293 }
294 break;
295 case QCRYPTO_CIPHER_ALG_SERPENT_128:
296 case QCRYPTO_CIPHER_ALG_SERPENT_192:
297 case QCRYPTO_CIPHER_ALG_SERPENT_256:
298 if (digestlen == qcrypto_cipher_get_key_len(
299 QCRYPTO_CIPHER_ALG_SERPENT_128)) {
300 return QCRYPTO_CIPHER_ALG_SERPENT_128;
301 } else if (digestlen == qcrypto_cipher_get_key_len(
302 QCRYPTO_CIPHER_ALG_SERPENT_192)) {
303 return QCRYPTO_CIPHER_ALG_SERPENT_192;
304 } else if (digestlen == qcrypto_cipher_get_key_len(
305 QCRYPTO_CIPHER_ALG_SERPENT_256)) {
306 return QCRYPTO_CIPHER_ALG_SERPENT_256;
307 } else {
308 error_setg(errp, "No Serpent cipher with key size %zu available",
309 digestlen);
310 return 0;
311 }
312 break;
313 case QCRYPTO_CIPHER_ALG_TWOFISH_128:
314 case QCRYPTO_CIPHER_ALG_TWOFISH_192:
315 case QCRYPTO_CIPHER_ALG_TWOFISH_256:
316 if (digestlen == qcrypto_cipher_get_key_len(
317 QCRYPTO_CIPHER_ALG_TWOFISH_128)) {
318 return QCRYPTO_CIPHER_ALG_TWOFISH_128;
319 } else if (digestlen == qcrypto_cipher_get_key_len(
320 QCRYPTO_CIPHER_ALG_TWOFISH_192)) {
321 return QCRYPTO_CIPHER_ALG_TWOFISH_192;
322 } else if (digestlen == qcrypto_cipher_get_key_len(
323 QCRYPTO_CIPHER_ALG_TWOFISH_256)) {
324 return QCRYPTO_CIPHER_ALG_TWOFISH_256;
325 } else {
326 error_setg(errp, "No Twofish cipher with key size %zu available",
327 digestlen);
328 return 0;
329 }
330 break;
331 default:
332 error_setg(errp, "Cipher %s not supported with essiv",
Markus Armbruster977c7362017-08-24 10:46:08 +0200333 QCryptoCipherAlgorithm_str(cipher));
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100334 return 0;
335 }
336}
337
338/*
Maxim Levitskybd56a552019-09-26 00:35:25 +0300339 * Returns number of sectors needed to store the key material
340 * given number of anti forensic stripes
341 */
342static int
343qcrypto_block_luks_splitkeylen_sectors(const QCryptoBlockLUKS *luks,
344 unsigned int header_sectors,
345 unsigned int stripes)
346{
347 /*
348 * This calculation doesn't match that shown in the spec,
349 * but instead follows the cryptsetup implementation.
350 */
351
352 size_t splitkeylen = luks->header.master_key_len * stripes;
353
354 /* First align the key material size to block size*/
355 size_t splitkeylen_sectors =
356 DIV_ROUND_UP(splitkeylen, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE);
357
358 /* Then also align the key material size to the size of the header */
359 return ROUND_UP(splitkeylen_sectors, header_sectors);
360}
361
Daniel P. Berrangé98c72df2022-05-10 15:40:55 +0100362
363void
364qcrypto_block_luks_to_disk_endian(QCryptoBlockLUKSHeader *hdr)
365{
366 size_t i;
367
368 /*
369 * Everything on disk uses Big Endian (tm), so flip header fields
370 * before writing them
371 */
372 cpu_to_be16s(&hdr->version);
373 cpu_to_be32s(&hdr->payload_offset_sector);
374 cpu_to_be32s(&hdr->master_key_len);
375 cpu_to_be32s(&hdr->master_key_iterations);
376
377 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
378 cpu_to_be32s(&hdr->key_slots[i].active);
379 cpu_to_be32s(&hdr->key_slots[i].iterations);
380 cpu_to_be32s(&hdr->key_slots[i].key_offset_sector);
381 cpu_to_be32s(&hdr->key_slots[i].stripes);
382 }
383}
384
385void
386qcrypto_block_luks_from_disk_endian(QCryptoBlockLUKSHeader *hdr)
387{
388 size_t i;
389
390 /*
391 * The header is always stored in big-endian format, so
392 * convert everything to native
393 */
394 be16_to_cpus(&hdr->version);
395 be32_to_cpus(&hdr->payload_offset_sector);
396 be32_to_cpus(&hdr->master_key_len);
397 be32_to_cpus(&hdr->master_key_iterations);
398
399 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
400 be32_to_cpus(&hdr->key_slots[i].active);
401 be32_to_cpus(&hdr->key_slots[i].iterations);
402 be32_to_cpus(&hdr->key_slots[i].key_offset_sector);
403 be32_to_cpus(&hdr->key_slots[i].stripes);
404 }
405}
406
Maxim Levitskybd56a552019-09-26 00:35:25 +0300407/*
Michael Tokarev0a19d872023-07-14 14:33:49 +0300408 * Stores the main LUKS header, taking care of endianness
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300409 */
410static int
411qcrypto_block_luks_store_header(QCryptoBlock *block,
412 QCryptoBlockWriteFunc writefunc,
413 void *opaque,
414 Error **errp)
415{
416 const QCryptoBlockLUKS *luks = block->opaque;
417 Error *local_err = NULL;
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300418 g_autofree QCryptoBlockLUKSHeader *hdr_copy = NULL;
419
420 /* Create a copy of the header */
421 hdr_copy = g_new0(QCryptoBlockLUKSHeader, 1);
422 memcpy(hdr_copy, &luks->header, sizeof(QCryptoBlockLUKSHeader));
423
Daniel P. Berrangé98c72df2022-05-10 15:40:55 +0100424 qcrypto_block_luks_to_disk_endian(hdr_copy);
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300425
426 /* Write out the partition header and key slot headers */
427 writefunc(block, 0, (const uint8_t *)hdr_copy, sizeof(*hdr_copy),
428 opaque, &local_err);
429
430 if (local_err) {
431 error_propagate(errp, local_err);
432 return -1;
433 }
434 return 0;
435}
436
437/*
Michael Tokarev0a19d872023-07-14 14:33:49 +0300438 * Loads the main LUKS header, and byteswaps it to native endianness
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300439 * And run basic sanity checks on it
440 */
441static int
442qcrypto_block_luks_load_header(QCryptoBlock *block,
443 QCryptoBlockReadFunc readfunc,
444 void *opaque,
445 Error **errp)
446{
Alberto Faria757dda52022-06-09 16:27:38 +0100447 int rv;
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300448 QCryptoBlockLUKS *luks = block->opaque;
449
450 /*
451 * Read the entire LUKS header, minus the key material from
452 * the underlying device
453 */
454 rv = readfunc(block, 0,
455 (uint8_t *)&luks->header,
456 sizeof(luks->header),
457 opaque,
458 errp);
459 if (rv < 0) {
460 return rv;
461 }
462
Daniel P. Berrangé98c72df2022-05-10 15:40:55 +0100463 qcrypto_block_luks_from_disk_endian(&luks->header);
Maxim Levitskydde2c5a2019-09-26 00:35:22 +0300464
465 return 0;
466}
467
468/*
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +0300469 * Does basic sanity checks on the LUKS header
470 */
471static int
Hyman Huang9ad5c4e2024-01-30 13:37:19 +0800472qcrypto_block_luks_check_header(const QCryptoBlockLUKS *luks,
473 unsigned int flags,
474 Error **errp)
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +0300475{
Maxim Levitskybefdba92019-09-26 00:35:26 +0300476 size_t i, j;
477
478 unsigned int header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
479 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
Hyman Huang9ad5c4e2024-01-30 13:37:19 +0800480 bool detached = flags & QCRYPTO_BLOCK_OPEN_DETACHED;
Maxim Levitskybefdba92019-09-26 00:35:26 +0300481
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +0300482 if (memcmp(luks->header.magic, qcrypto_block_luks_magic,
483 QCRYPTO_BLOCK_LUKS_MAGIC_LEN) != 0) {
484 error_setg(errp, "Volume is not in LUKS format");
485 return -1;
486 }
487
488 if (luks->header.version != QCRYPTO_BLOCK_LUKS_VERSION) {
489 error_setg(errp, "LUKS version %" PRIu32 " is not supported",
490 luks->header.version);
491 return -1;
492 }
Maxim Levitskybefdba92019-09-26 00:35:26 +0300493
Daniel P. Berrangéc1d86342022-05-10 14:17:43 +0100494 if (!memchr(luks->header.cipher_name, '\0',
495 sizeof(luks->header.cipher_name))) {
496 error_setg(errp, "LUKS header cipher name is not NUL terminated");
497 return -1;
498 }
499
500 if (!memchr(luks->header.cipher_mode, '\0',
501 sizeof(luks->header.cipher_mode))) {
502 error_setg(errp, "LUKS header cipher mode is not NUL terminated");
503 return -1;
504 }
505
506 if (!memchr(luks->header.hash_spec, '\0',
507 sizeof(luks->header.hash_spec))) {
508 error_setg(errp, "LUKS header hash spec is not NUL terminated");
509 return -1;
510 }
511
Hyman Huang9ad5c4e2024-01-30 13:37:19 +0800512 if (!detached && luks->header.payload_offset_sector <
Daniel P. Berrangéd233fbc2022-09-05 13:50:03 +0100513 DIV_ROUND_UP(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET,
514 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) {
515 error_setg(errp, "LUKS payload is overlapping with the header");
516 return -1;
517 }
518
Daniel P. Berrangéb57151a2022-09-05 13:52:29 +0100519 if (luks->header.master_key_iterations == 0) {
520 error_setg(errp, "LUKS key iteration count is zero");
521 return -1;
522 }
523
Maxim Levitskybefdba92019-09-26 00:35:26 +0300524 /* Check all keyslots for corruption */
525 for (i = 0 ; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; i++) {
526
527 const QCryptoBlockLUKSKeySlot *slot1 = &luks->header.key_slots[i];
528 unsigned int start1 = slot1->key_offset_sector;
529 unsigned int len1 =
530 qcrypto_block_luks_splitkeylen_sectors(luks,
531 header_sectors,
532 slot1->stripes);
533
Daniel P. Berrangéf1195962022-05-10 14:27:33 +0100534 if (slot1->stripes != QCRYPTO_BLOCK_LUKS_STRIPES) {
535 error_setg(errp, "Keyslot %zu is corrupted (stripes %d != %d)",
536 i, slot1->stripes, QCRYPTO_BLOCK_LUKS_STRIPES);
Maxim Levitskybefdba92019-09-26 00:35:26 +0300537 return -1;
538 }
539
540 if (slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED &&
541 slot1->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
542 error_setg(errp,
543 "Keyslot %zu state (active/disable) is corrupted", i);
544 return -1;
545 }
546
Daniel P. Berrangéb57151a2022-09-05 13:52:29 +0100547 if (slot1->active == QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED &&
548 slot1->iterations == 0) {
549 error_setg(errp, "Keyslot %zu iteration count is zero", i);
550 return -1;
551 }
552
Daniel P. Berrangéc5f69622022-09-05 13:57:01 +0100553 if (start1 < DIV_ROUND_UP(QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET,
Daniel P. Berrangé93569c32022-05-10 14:35:57 +0100554 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE)) {
555 error_setg(errp,
556 "Keyslot %zu is overlapping with the LUKS header",
557 i);
558 return -1;
559 }
560
Hyman Huang9ad5c4e2024-01-30 13:37:19 +0800561 if (!detached && start1 + len1 > luks->header.payload_offset_sector) {
Maxim Levitskybefdba92019-09-26 00:35:26 +0300562 error_setg(errp,
563 "Keyslot %zu is overlapping with the encrypted payload",
564 i);
565 return -1;
566 }
567
568 for (j = i + 1 ; j < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS ; j++) {
569 const QCryptoBlockLUKSKeySlot *slot2 = &luks->header.key_slots[j];
570 unsigned int start2 = slot2->key_offset_sector;
571 unsigned int len2 =
572 qcrypto_block_luks_splitkeylen_sectors(luks,
573 header_sectors,
574 slot2->stripes);
575
Yao Xingtao7cd9b9d2024-07-22 00:07:40 -0400576 if (ranges_overlap(start1, len1, start2, len2)) {
Maxim Levitskybefdba92019-09-26 00:35:26 +0300577 error_setg(errp,
578 "Keyslots %zu and %zu are overlapping in the header",
579 i, j);
580 return -1;
581 }
582 }
583
584 }
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +0300585 return 0;
586}
587
588/*
589 * Parses the crypto parameters that are stored in the LUKS header
590 */
591
592static int
593qcrypto_block_luks_parse_header(QCryptoBlockLUKS *luks, Error **errp)
594{
595 g_autofree char *cipher_mode = g_strdup(luks->header.cipher_mode);
596 char *ivgen_name, *ivhash_name;
597 Error *local_err = NULL;
598
599 /*
600 * The cipher_mode header contains a string that we have
601 * to further parse, of the format
602 *
603 * <cipher-mode>-<iv-generator>[:<iv-hash>]
604 *
605 * eg cbc-essiv:sha256, cbc-plain64
606 */
607 ivgen_name = strchr(cipher_mode, '-');
608 if (!ivgen_name) {
Daniel P. Berrangé6c198932022-09-05 12:08:21 +0100609 error_setg(errp, "Unexpected cipher mode string format '%s'",
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +0300610 luks->header.cipher_mode);
611 return -1;
612 }
613 *ivgen_name = '\0';
614 ivgen_name++;
615
616 ivhash_name = strchr(ivgen_name, ':');
617 if (!ivhash_name) {
618 luks->ivgen_hash_alg = 0;
619 } else {
620 *ivhash_name = '\0';
621 ivhash_name++;
622
623 luks->ivgen_hash_alg = qcrypto_block_luks_hash_name_lookup(ivhash_name,
624 &local_err);
625 if (local_err) {
626 error_propagate(errp, local_err);
627 return -1;
628 }
629 }
630
631 luks->cipher_mode = qcrypto_block_luks_cipher_mode_lookup(cipher_mode,
632 &local_err);
633 if (local_err) {
634 error_propagate(errp, local_err);
635 return -1;
636 }
637
638 luks->cipher_alg =
639 qcrypto_block_luks_cipher_name_lookup(luks->header.cipher_name,
640 luks->cipher_mode,
641 luks->header.master_key_len,
642 &local_err);
643 if (local_err) {
644 error_propagate(errp, local_err);
645 return -1;
646 }
647
648 luks->hash_alg =
649 qcrypto_block_luks_hash_name_lookup(luks->header.hash_spec,
650 &local_err);
651 if (local_err) {
652 error_propagate(errp, local_err);
653 return -1;
654 }
655
656 luks->ivgen_alg = qcrypto_block_luks_ivgen_name_lookup(ivgen_name,
657 &local_err);
658 if (local_err) {
659 error_propagate(errp, local_err);
660 return -1;
661 }
662
663 if (luks->ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
664 if (!ivhash_name) {
665 error_setg(errp, "Missing IV generator hash specification");
666 return -1;
667 }
668 luks->ivgen_cipher_alg =
669 qcrypto_block_luks_essiv_cipher(luks->cipher_alg,
670 luks->ivgen_hash_alg,
671 &local_err);
672 if (local_err) {
673 error_propagate(errp, local_err);
674 return -1;
675 }
676 } else {
677
678 /*
679 * Note we parsed the ivhash_name earlier in the cipher_mode
680 * spec string even with plain/plain64 ivgens, but we
681 * will ignore it, since it is irrelevant for these ivgens.
682 * This is for compat with dm-crypt which will silently
683 * ignore hash names with these ivgens rather than report
684 * an error about the invalid usage
685 */
686 luks->ivgen_cipher_alg = luks->cipher_alg;
687 }
688 return 0;
689}
690
691/*
Maxim Levitsky3994a7c2019-09-26 00:35:24 +0300692 * Given a key slot, user password, and the master key,
693 * will store the encrypted master key there, and update the
694 * in-memory header. User must then write the in-memory header
695 *
696 * Returns:
697 * 0 if the keyslot was written successfully
698 * with the provided password
699 * -1 if a fatal error occurred while storing the key
700 */
701static int
702qcrypto_block_luks_store_key(QCryptoBlock *block,
703 unsigned int slot_idx,
704 const char *password,
705 uint8_t *masterkey,
706 uint64_t iter_time,
707 QCryptoBlockWriteFunc writefunc,
708 void *opaque,
709 Error **errp)
710{
711 QCryptoBlockLUKS *luks = block->opaque;
Maxim Levitsky557d2bd2020-06-25 14:55:37 +0200712 QCryptoBlockLUKSKeySlot *slot;
Maxim Levitsky3994a7c2019-09-26 00:35:24 +0300713 g_autofree uint8_t *splitkey = NULL;
714 size_t splitkeylen;
715 g_autofree uint8_t *slotkey = NULL;
716 g_autoptr(QCryptoCipher) cipher = NULL;
717 g_autoptr(QCryptoIVGen) ivgen = NULL;
718 Error *local_err = NULL;
719 uint64_t iters;
720 int ret = -1;
721
Maxim Levitsky557d2bd2020-06-25 14:55:37 +0200722 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
723 slot = &luks->header.key_slots[slot_idx];
Akihiko Odaki55a01ca2023-05-22 20:47:37 +0900724 splitkeylen = luks->header.master_key_len * slot->stripes;
725
Maxim Levitsky3994a7c2019-09-26 00:35:24 +0300726 if (qcrypto_random_bytes(slot->salt,
727 QCRYPTO_BLOCK_LUKS_SALT_LEN,
728 errp) < 0) {
729 goto cleanup;
730 }
731
Maxim Levitsky3994a7c2019-09-26 00:35:24 +0300732 /*
733 * Determine how many iterations are required to
734 * hash the user password while consuming 1 second of compute
735 * time
736 */
737 iters = qcrypto_pbkdf2_count_iters(luks->hash_alg,
738 (uint8_t *)password, strlen(password),
739 slot->salt,
740 QCRYPTO_BLOCK_LUKS_SALT_LEN,
741 luks->header.master_key_len,
742 &local_err);
743 if (local_err) {
744 error_propagate(errp, local_err);
745 goto cleanup;
746 }
747
748 if (iters > (ULLONG_MAX / iter_time)) {
749 error_setg_errno(errp, ERANGE,
750 "PBKDF iterations %llu too large to scale",
751 (unsigned long long)iters);
752 goto cleanup;
753 }
754
755 /* iter_time was in millis, but count_iters reported for secs */
756 iters = iters * iter_time / 1000;
757
758 if (iters > UINT32_MAX) {
759 error_setg_errno(errp, ERANGE,
760 "PBKDF iterations %llu larger than %u",
761 (unsigned long long)iters, UINT32_MAX);
762 goto cleanup;
763 }
764
765 slot->iterations =
766 MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
767
768
769 /*
770 * Generate a key that we'll use to encrypt the master
771 * key, from the user's password
772 */
773 slotkey = g_new0(uint8_t, luks->header.master_key_len);
774 if (qcrypto_pbkdf2(luks->hash_alg,
775 (uint8_t *)password, strlen(password),
776 slot->salt,
777 QCRYPTO_BLOCK_LUKS_SALT_LEN,
778 slot->iterations,
779 slotkey, luks->header.master_key_len,
780 errp) < 0) {
781 goto cleanup;
782 }
783
784
785 /*
786 * Setup the encryption objects needed to encrypt the
787 * master key material
788 */
789 cipher = qcrypto_cipher_new(luks->cipher_alg,
790 luks->cipher_mode,
791 slotkey, luks->header.master_key_len,
792 errp);
793 if (!cipher) {
794 goto cleanup;
795 }
796
797 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
798 luks->ivgen_cipher_alg,
799 luks->ivgen_hash_alg,
800 slotkey, luks->header.master_key_len,
801 errp);
802 if (!ivgen) {
803 goto cleanup;
804 }
805
806 /*
807 * Before storing the master key, we need to vastly
808 * increase its size, as protection against forensic
809 * disk data recovery
810 */
811 splitkey = g_new0(uint8_t, splitkeylen);
812
813 if (qcrypto_afsplit_encode(luks->hash_alg,
814 luks->header.master_key_len,
815 slot->stripes,
816 masterkey,
817 splitkey,
818 errp) < 0) {
819 goto cleanup;
820 }
821
822 /*
823 * Now we encrypt the split master key with the key generated
824 * from the user's password, before storing it
825 */
826 if (qcrypto_block_cipher_encrypt_helper(cipher, block->niv, ivgen,
827 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
828 0,
829 splitkey,
830 splitkeylen,
831 errp) < 0) {
832 goto cleanup;
833 }
834
835 /* Write out the slot's master key material. */
836 if (writefunc(block,
837 slot->key_offset_sector *
838 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
839 splitkey, splitkeylen,
840 opaque,
Alberto Faria757dda52022-06-09 16:27:38 +0100841 errp) < 0) {
Maxim Levitsky3994a7c2019-09-26 00:35:24 +0300842 goto cleanup;
843 }
844
845 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
846
847 if (qcrypto_block_luks_store_header(block, writefunc, opaque, errp) < 0) {
848 goto cleanup;
849 }
850
851 ret = 0;
852
853cleanup:
854 if (slotkey) {
855 memset(slotkey, 0, luks->header.master_key_len);
856 }
857 if (splitkey) {
858 memset(splitkey, 0, splitkeylen);
859 }
860 return ret;
861}
862
863/*
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100864 * Given a key slot, and user password, this will attempt to unlock
865 * the master encryption key from the key slot.
866 *
867 * Returns:
868 * 0 if the key slot is disabled, or key could not be decrypted
869 * with the provided password
870 * 1 if the key slot is enabled, and key decrypted successfully
871 * with the provided password
872 * -1 if a fatal error occurred loading the key
873 */
874static int
875qcrypto_block_luks_load_key(QCryptoBlock *block,
Maxim Levitsky7e60a6f2019-09-26 00:35:19 +0300876 size_t slot_idx,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100877 const char *password,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100878 uint8_t *masterkey,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100879 QCryptoBlockReadFunc readfunc,
880 void *opaque,
881 Error **errp)
882{
883 QCryptoBlockLUKS *luks = block->opaque;
Maxim Levitsky557d2bd2020-06-25 14:55:37 +0200884 const QCryptoBlockLUKSKeySlot *slot;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100885 g_autofree uint8_t *splitkey = NULL;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100886 size_t splitkeylen;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100887 g_autofree uint8_t *possiblekey = NULL;
Alberto Faria757dda52022-06-09 16:27:38 +0100888 int rv;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100889 g_autoptr(QCryptoCipher) cipher = NULL;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100890 uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100891 g_autoptr(QCryptoIVGen) ivgen = NULL;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100892 size_t niv;
893
Maxim Levitsky557d2bd2020-06-25 14:55:37 +0200894 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
895 slot = &luks->header.key_slots[slot_idx];
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100896 if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
897 return 0;
898 }
899
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +0300900 splitkeylen = luks->header.master_key_len * slot->stripes;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100901 splitkey = g_new0(uint8_t, splitkeylen);
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +0300902 possiblekey = g_new0(uint8_t, luks->header.master_key_len);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100903
904 /*
905 * The user password is used to generate a (possible)
906 * decryption key. This may or may not successfully
907 * decrypt the master key - we just blindly assume
908 * the key is correct and validate the results of
909 * decryption later.
910 */
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300911 if (qcrypto_pbkdf2(luks->hash_alg,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100912 (const uint8_t *)password, strlen(password),
913 slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
914 slot->iterations,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +0300915 possiblekey, luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100916 errp) < 0) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100917 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100918 }
919
920 /*
921 * We need to read the master key material from the
922 * LUKS key material header. What we're reading is
923 * not the raw master key, but rather the data after
924 * it has been passed through AFSplit and the result
925 * then encrypted.
926 */
927 rv = readfunc(block,
Maxim Levitskyf0d3c362019-09-26 00:35:16 +0300928 slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100929 splitkey, splitkeylen,
Daniel P. Berrangee4a35072017-04-24 16:33:15 +0100930 opaque,
Fam Zheng37509232017-04-21 20:27:02 +0800931 errp);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100932 if (rv < 0) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100933 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100934 }
935
936
937 /* Setup the cipher/ivgen that we'll use to try to decrypt
938 * the split master key material */
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300939 cipher = qcrypto_cipher_new(luks->cipher_alg,
940 luks->cipher_mode,
941 possiblekey,
942 luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100943 errp);
944 if (!cipher) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100945 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100946 }
947
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300948 niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
949 luks->cipher_mode);
950
951 ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
952 luks->ivgen_cipher_alg,
953 luks->ivgen_hash_alg,
954 possiblekey,
955 luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100956 errp);
957 if (!ivgen) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100958 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100959 }
960
961
962 /*
963 * The master key needs to be decrypted in the same
964 * way that the block device payload will be decrypted
965 * later. In particular we'll be using the IV generator
966 * to reset the encryption cipher every time the master
967 * key crosses a sector boundary.
968 */
Vladimir Sementsov-Ogievskiy02704172018-12-07 19:13:49 +0300969 if (qcrypto_block_cipher_decrypt_helper(cipher,
970 niv,
971 ivgen,
972 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
973 0,
974 splitkey,
975 splitkeylen,
976 errp) < 0) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100977 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100978 }
979
980 /*
981 * Now we've decrypted the split master key, join
982 * it back together to get the actual master key.
983 */
Maxim Levitsky9d80e592019-09-26 00:35:20 +0300984 if (qcrypto_afsplit_decode(luks->hash_alg,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +0300985 luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100986 slot->stripes,
987 splitkey,
988 masterkey,
989 errp) < 0) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +0100990 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +0100991 }
992
993
994 /*
995 * We still don't know that the masterkey we got is valid,
996 * because we just blindly assumed the user's password
997 * was correct. This is where we now verify it. We are
998 * creating a hash of the master key using PBKDF and
999 * then comparing that to the hash stored in the key slot
1000 * header
1001 */
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001002 if (qcrypto_pbkdf2(luks->hash_alg,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001003 masterkey,
1004 luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001005 luks->header.master_key_salt,
1006 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1007 luks->header.master_key_iterations,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001008 keydigest,
1009 G_N_ELEMENTS(keydigest),
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001010 errp) < 0) {
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001011 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001012 }
1013
1014 if (memcmp(keydigest, luks->header.master_key_digest,
1015 QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
1016 /* Success, we got the right master key */
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001017 return 1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001018 }
1019
1020 /* Fail, user's password was not valid for this key slot,
1021 * tell caller to try another slot */
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001022 return 0;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001023}
1024
1025
1026/*
1027 * Given a user password, this will iterate over all key
1028 * slots and try to unlock each active key slot using the
1029 * password until it successfully obtains a master key.
1030 *
1031 * Returns 0 if a key was loaded, -1 if no keys could be loaded
1032 */
1033static int
1034qcrypto_block_luks_find_key(QCryptoBlock *block,
1035 const char *password,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001036 uint8_t *masterkey,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001037 QCryptoBlockReadFunc readfunc,
1038 void *opaque,
1039 Error **errp)
1040{
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001041 size_t i;
1042 int rv;
1043
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001044 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1045 rv = qcrypto_block_luks_load_key(block,
Maxim Levitsky7e60a6f2019-09-26 00:35:19 +03001046 i,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001047 password,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001048 masterkey,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001049 readfunc,
1050 opaque,
1051 errp);
1052 if (rv < 0) {
1053 goto error;
1054 }
1055 if (rv == 1) {
1056 return 0;
1057 }
1058 }
1059
1060 error_setg(errp, "Invalid password, cannot unlock any keyslot");
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001061 error:
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001062 return -1;
1063}
1064
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001065/*
1066 * Returns true if a slot i is marked as active
1067 * (contains encrypted copy of the master key)
1068 */
1069static bool
1070qcrypto_block_luks_slot_active(const QCryptoBlockLUKS *luks,
1071 unsigned int slot_idx)
1072{
1073 uint32_t val;
1074
1075 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1076 val = luks->header.key_slots[slot_idx].active;
1077 return val == QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
1078}
1079
1080/*
1081 * Returns the number of slots that are marked as active
1082 * (slots that contain encrypted copy of the master key)
1083 */
1084static unsigned int
1085qcrypto_block_luks_count_active_slots(const QCryptoBlockLUKS *luks)
1086{
1087 size_t i = 0;
1088 unsigned int ret = 0;
1089
1090 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1091 if (qcrypto_block_luks_slot_active(luks, i)) {
1092 ret++;
1093 }
1094 }
1095 return ret;
1096}
1097
1098/*
1099 * Finds first key slot which is not active
1100 * Returns the key slot index, or -1 if it doesn't exist
1101 */
1102static int
1103qcrypto_block_luks_find_free_keyslot(const QCryptoBlockLUKS *luks)
1104{
1105 size_t i;
1106
1107 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1108 if (!qcrypto_block_luks_slot_active(luks, i)) {
1109 return i;
1110 }
1111 }
1112 return -1;
1113}
1114
1115/*
1116 * Erases an keyslot given its index
1117 * Returns:
1118 * 0 if the keyslot was erased successfully
1119 * -1 if a error occurred while erasing the keyslot
1120 *
1121 */
1122static int
1123qcrypto_block_luks_erase_key(QCryptoBlock *block,
1124 unsigned int slot_idx,
1125 QCryptoBlockWriteFunc writefunc,
1126 void *opaque,
1127 Error **errp)
1128{
1129 QCryptoBlockLUKS *luks = block->opaque;
1130 QCryptoBlockLUKSKeySlot *slot;
1131 g_autofree uint8_t *garbagesplitkey = NULL;
1132 size_t splitkeylen;
1133 size_t i;
1134 Error *local_err = NULL;
1135 int ret;
1136
1137 assert(slot_idx < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1138 slot = &luks->header.key_slots[slot_idx];
1139
1140 splitkeylen = luks->header.master_key_len * slot->stripes;
1141 assert(splitkeylen > 0);
1142
1143 garbagesplitkey = g_new0(uint8_t, splitkeylen);
1144
1145 /* Reset the key slot header */
1146 memset(slot->salt, 0, QCRYPTO_BLOCK_LUKS_SALT_LEN);
1147 slot->iterations = 0;
1148 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
1149
1150 ret = qcrypto_block_luks_store_header(block, writefunc,
1151 opaque, &local_err);
1152
1153 if (ret < 0) {
1154 error_propagate(errp, local_err);
1155 }
1156 /*
1157 * Now try to erase the key material, even if the header
1158 * update failed
1159 */
1160 for (i = 0; i < QCRYPTO_BLOCK_LUKS_ERASE_ITERATIONS; i++) {
1161 if (qcrypto_random_bytes(garbagesplitkey,
1162 splitkeylen, &local_err) < 0) {
1163 /*
1164 * If we failed to get the random data, still write
1165 * at least zeros to the key slot at least once
1166 */
1167 error_propagate(errp, local_err);
1168
1169 if (i > 0) {
1170 return -1;
1171 }
1172 }
1173 if (writefunc(block,
1174 slot->key_offset_sector * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1175 garbagesplitkey,
1176 splitkeylen,
1177 opaque,
Alberto Faria757dda52022-06-09 16:27:38 +01001178 &local_err) < 0) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001179 error_propagate(errp, local_err);
1180 return -1;
1181 }
1182 }
1183 return ret;
1184}
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001185
1186static int
1187qcrypto_block_luks_open(QCryptoBlock *block,
1188 QCryptoBlockOpenOptions *options,
Daniel P. Berrange1cd9a782017-06-23 17:24:17 +01001189 const char *optprefix,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001190 QCryptoBlockReadFunc readfunc,
1191 void *opaque,
1192 unsigned int flags,
1193 Error **errp)
1194{
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001195 QCryptoBlockLUKS *luks = NULL;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001196 g_autofree uint8_t *masterkey = NULL;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001197 g_autofree char *password = NULL;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001198
1199 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1200 if (!options->u.luks.key_secret) {
Daniel P. Berrange1cd9a782017-06-23 17:24:17 +01001201 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1202 optprefix ? optprefix : "");
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001203 return -1;
1204 }
1205 password = qcrypto_secret_lookup_as_utf8(
1206 options->u.luks.key_secret, errp);
1207 if (!password) {
1208 return -1;
1209 }
1210 }
1211
1212 luks = g_new0(QCryptoBlockLUKS, 1);
1213 block->opaque = luks;
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001214 luks->secret = g_strdup(options->u.luks.key_secret);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001215
Maxim Levitskydde2c5a2019-09-26 00:35:22 +03001216 if (qcrypto_block_luks_load_header(block, readfunc, opaque, errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001217 goto fail;
1218 }
1219
Hyman Huang9ad5c4e2024-01-30 13:37:19 +08001220 if (qcrypto_block_luks_check_header(luks, flags, errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001221 goto fail;
1222 }
1223
Maxim Levitsky9fa9c1c2019-09-26 00:35:23 +03001224 if (qcrypto_block_luks_parse_header(luks, errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001225 goto fail;
1226 }
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001227
1228 if (!(flags & QCRYPTO_BLOCK_OPEN_NO_IO)) {
1229 /* Try to find which key slot our password is valid for
1230 * and unlock the master key from that slot.
1231 */
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001232
1233 masterkey = g_new0(uint8_t, luks->header.master_key_len);
1234
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001235 if (qcrypto_block_luks_find_key(block,
1236 password,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001237 masterkey,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001238 readfunc, opaque,
1239 errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001240 goto fail;
1241 }
1242
1243 /* We have a valid master key now, so can setup the
1244 * block device payload decryption objects
1245 */
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001246 block->kdfhash = luks->hash_alg;
1247 block->niv = qcrypto_cipher_get_iv_len(luks->cipher_alg,
1248 luks->cipher_mode);
1249
1250 block->ivgen = qcrypto_ivgen_new(luks->ivgen_alg,
1251 luks->ivgen_cipher_alg,
1252 luks->ivgen_hash_alg,
Maxim Levitsky1ddd52e2019-09-26 00:35:18 +03001253 masterkey,
1254 luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001255 errp);
1256 if (!block->ivgen) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001257 goto fail;
1258 }
1259
Maxim Levitsky61dd8a92019-09-26 00:35:21 +03001260 if (qcrypto_block_init_cipher(block,
1261 luks->cipher_alg,
1262 luks->cipher_mode,
1263 masterkey,
1264 luks->header.master_key_len,
Maxim Levitsky61dd8a92019-09-26 00:35:21 +03001265 errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001266 goto fail;
1267 }
1268 }
1269
Daniel P. Berrange850f49d2017-09-27 13:53:36 +01001270 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001271 block->payload_offset = luks->header.payload_offset_sector *
Daniel P. Berrange850f49d2017-09-27 13:53:36 +01001272 block->sector_size;
Hyman Huang0bd779e2024-01-30 13:37:24 +08001273 block->detached_header = (block->payload_offset == 0) ? true : false;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001274
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001275 return 0;
1276
1277 fail:
Vladimir Sementsov-Ogievskiyc972fa12018-12-07 19:13:51 +03001278 qcrypto_block_free_cipher(block);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001279 qcrypto_ivgen_free(block->ivgen);
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001280 g_free(luks->secret);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001281 g_free(luks);
Maxim Levitsky61dd8a92019-09-26 00:35:21 +03001282 return -1;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001283}
1284
1285
Fam Zheng2ef950f2016-09-21 12:27:19 +08001286static void
1287qcrypto_block_luks_uuid_gen(uint8_t *uuidstr)
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001288{
Fam Zheng2ef950f2016-09-21 12:27:19 +08001289 QemuUUID uuid;
1290 qemu_uuid_generate(&uuid);
1291 qemu_uuid_unparse(&uuid, (char *)uuidstr);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001292}
1293
1294static int
1295qcrypto_block_luks_create(QCryptoBlock *block,
1296 QCryptoBlockCreateOptions *options,
Daniel P. Berrange1cd9a782017-06-23 17:24:17 +01001297 const char *optprefix,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001298 QCryptoBlockInitFunc initfunc,
1299 QCryptoBlockWriteFunc writefunc,
1300 void *opaque,
1301 Error **errp)
1302{
1303 QCryptoBlockLUKS *luks;
1304 QCryptoBlockCreateOptionsLUKS luks_opts;
1305 Error *local_err = NULL;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001306 g_autofree uint8_t *masterkey = NULL;
Maxim Levitskybd56a552019-09-26 00:35:25 +03001307 size_t header_sectors;
1308 size_t split_key_sectors;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001309 size_t i;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001310 g_autofree char *password = NULL;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001311 const char *cipher_alg;
1312 const char *cipher_mode;
1313 const char *ivgen_alg;
1314 const char *ivgen_hash_alg = NULL;
1315 const char *hash_alg;
Daniel P. Berrangé57b9f112019-07-23 16:22:36 +01001316 g_autofree char *cipher_mode_spec = NULL;
Daniel P. Berrange59b060b2016-09-12 12:50:12 +01001317 uint64_t iters;
Hyman Huangd74523a2024-01-30 13:37:21 +08001318 uint64_t detached_header_size;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001319
1320 memcpy(&luks_opts, &options->u.luks, sizeof(luks_opts));
Daniel P. Berrange3bd18892016-09-06 18:43:00 +01001321 if (!luks_opts.has_iter_time) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001322 luks_opts.iter_time = QCRYPTO_BLOCK_LUKS_DEFAULT_ITER_TIME_MS;
Daniel P. Berrange3bd18892016-09-06 18:43:00 +01001323 }
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001324 if (!luks_opts.has_cipher_alg) {
1325 luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
1326 }
1327 if (!luks_opts.has_cipher_mode) {
1328 luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_XTS;
1329 }
1330 if (!luks_opts.has_ivgen_alg) {
1331 luks_opts.ivgen_alg = QCRYPTO_IVGEN_ALG_PLAIN64;
1332 }
1333 if (!luks_opts.has_hash_alg) {
1334 luks_opts.hash_alg = QCRYPTO_HASH_ALG_SHA256;
1335 }
Daniel P. Berrange8b7cdba2016-05-20 17:43:44 +01001336 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1337 if (!luks_opts.has_ivgen_hash_alg) {
1338 luks_opts.ivgen_hash_alg = QCRYPTO_HASH_ALG_SHA256;
1339 luks_opts.has_ivgen_hash_alg = true;
1340 }
1341 }
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001342
1343 luks = g_new0(QCryptoBlockLUKS, 1);
1344 block->opaque = luks;
1345
1346 luks->cipher_alg = luks_opts.cipher_alg;
1347 luks->cipher_mode = luks_opts.cipher_mode;
1348 luks->ivgen_alg = luks_opts.ivgen_alg;
1349 luks->ivgen_hash_alg = luks_opts.ivgen_hash_alg;
1350 luks->hash_alg = luks_opts.hash_alg;
1351
1352
Daniel P. Berrange8b7cdba2016-05-20 17:43:44 +01001353 /* Note we're allowing ivgen_hash_alg to be set even for
1354 * non-essiv iv generators that don't need a hash. It will
1355 * be silently ignored, for compatibility with dm-crypt */
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001356
1357 if (!options->u.luks.key_secret) {
Daniel P. Berrange1cd9a782017-06-23 17:24:17 +01001358 error_setg(errp, "Parameter '%skey-secret' is required for cipher",
1359 optprefix ? optprefix : "");
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001360 goto error;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001361 }
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001362 luks->secret = g_strdup(options->u.luks.key_secret);
1363
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001364 password = qcrypto_secret_lookup_as_utf8(luks_opts.key_secret, errp);
1365 if (!password) {
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001366 goto error;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001367 }
1368
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001369
1370 memcpy(luks->header.magic, qcrypto_block_luks_magic,
1371 QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
1372
1373 /* We populate the header in native endianness initially and
1374 * then convert everything to big endian just before writing
1375 * it out to disk
1376 */
1377 luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;
Fam Zheng2ef950f2016-09-21 12:27:19 +08001378 qcrypto_block_luks_uuid_gen(luks->header.uuid);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001379
1380 cipher_alg = qcrypto_block_luks_cipher_alg_lookup(luks_opts.cipher_alg,
1381 errp);
1382 if (!cipher_alg) {
1383 goto error;
1384 }
1385
Markus Armbruster977c7362017-08-24 10:46:08 +02001386 cipher_mode = QCryptoCipherMode_str(luks_opts.cipher_mode);
1387 ivgen_alg = QCryptoIVGenAlgorithm_str(luks_opts.ivgen_alg);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001388 if (luks_opts.has_ivgen_hash_alg) {
Markus Armbruster977c7362017-08-24 10:46:08 +02001389 ivgen_hash_alg = QCryptoHashAlgorithm_str(luks_opts.ivgen_hash_alg);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001390 cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
1391 ivgen_hash_alg);
1392 } else {
1393 cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
1394 }
Markus Armbruster977c7362017-08-24 10:46:08 +02001395 hash_alg = QCryptoHashAlgorithm_str(luks_opts.hash_alg);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001396
1397
1398 if (strlen(cipher_alg) >= QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN) {
1399 error_setg(errp, "Cipher name '%s' is too long for LUKS header",
1400 cipher_alg);
1401 goto error;
1402 }
1403 if (strlen(cipher_mode_spec) >= QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN) {
1404 error_setg(errp, "Cipher mode '%s' is too long for LUKS header",
1405 cipher_mode_spec);
1406 goto error;
1407 }
1408 if (strlen(hash_alg) >= QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN) {
1409 error_setg(errp, "Hash name '%s' is too long for LUKS header",
1410 hash_alg);
1411 goto error;
1412 }
1413
1414 if (luks_opts.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001415 luks->ivgen_cipher_alg =
1416 qcrypto_block_luks_essiv_cipher(luks_opts.cipher_alg,
1417 luks_opts.ivgen_hash_alg,
1418 &local_err);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001419 if (local_err) {
1420 error_propagate(errp, local_err);
1421 goto error;
1422 }
1423 } else {
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001424 luks->ivgen_cipher_alg = luks_opts.cipher_alg;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001425 }
1426
1427 strcpy(luks->header.cipher_name, cipher_alg);
1428 strcpy(luks->header.cipher_mode, cipher_mode_spec);
1429 strcpy(luks->header.hash_spec, hash_alg);
1430
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001431 luks->header.master_key_len =
1432 qcrypto_cipher_get_key_len(luks_opts.cipher_alg);
1433
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001434 if (luks_opts.cipher_mode == QCRYPTO_CIPHER_MODE_XTS) {
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001435 luks->header.master_key_len *= 2;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001436 }
1437
1438 /* Generate the salt used for hashing the master key
1439 * with PBKDF later
1440 */
1441 if (qcrypto_random_bytes(luks->header.master_key_salt,
1442 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1443 errp) < 0) {
1444 goto error;
1445 }
1446
1447 /* Generate random master key */
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001448 masterkey = g_new0(uint8_t, luks->header.master_key_len);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001449 if (qcrypto_random_bytes(masterkey,
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001450 luks->header.master_key_len, errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001451 goto error;
1452 }
1453
1454
1455 /* Setup the block device payload encryption objects */
Vladimir Sementsov-Ogievskiyc972fa12018-12-07 19:13:51 +03001456 if (qcrypto_block_init_cipher(block, luks_opts.cipher_alg,
1457 luks_opts.cipher_mode, masterkey,
Stefan Hajnocziaf206c22024-05-27 11:58:50 -04001458 luks->header.master_key_len, errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001459 goto error;
1460 }
1461
1462 block->kdfhash = luks_opts.hash_alg;
1463 block->niv = qcrypto_cipher_get_iv_len(luks_opts.cipher_alg,
1464 luks_opts.cipher_mode);
1465 block->ivgen = qcrypto_ivgen_new(luks_opts.ivgen_alg,
Maxim Levitsky9d80e592019-09-26 00:35:20 +03001466 luks->ivgen_cipher_alg,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001467 luks_opts.ivgen_hash_alg,
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001468 masterkey, luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001469 errp);
1470
1471 if (!block->ivgen) {
1472 goto error;
1473 }
1474
1475
1476 /* Determine how many iterations we need to hash the master
1477 * key, in order to have 1 second of compute time used
1478 */
Daniel P. Berrange59b060b2016-09-12 12:50:12 +01001479 iters = qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001480 masterkey, luks->header.master_key_len,
Daniel P. Berrange59b060b2016-09-12 12:50:12 +01001481 luks->header.master_key_salt,
1482 QCRYPTO_BLOCK_LUKS_SALT_LEN,
Daniel P. Berrangee74aabc2016-09-07 12:43:29 +01001483 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
Daniel P. Berrange59b060b2016-09-12 12:50:12 +01001484 &local_err);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001485 if (local_err) {
1486 error_propagate(errp, local_err);
1487 goto error;
1488 }
1489
Daniel P. Berrange3bd18892016-09-06 18:43:00 +01001490 if (iters > (ULLONG_MAX / luks_opts.iter_time)) {
1491 error_setg_errno(errp, ERANGE,
1492 "PBKDF iterations %llu too large to scale",
1493 (unsigned long long)iters);
1494 goto error;
1495 }
1496
1497 /* iter_time was in millis, but count_iters reported for secs */
1498 iters = iters * luks_opts.iter_time / 1000;
1499
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001500 /* Why /= 8 ? That matches cryptsetup, but there's no
1501 * explanation why they chose /= 8... Probably so that
1502 * if all 8 keyslots are active we only spend 1 second
1503 * in total time to check all keys */
Daniel P. Berrange59b060b2016-09-12 12:50:12 +01001504 iters /= 8;
1505 if (iters > UINT32_MAX) {
1506 error_setg_errno(errp, ERANGE,
1507 "PBKDF iterations %llu larger than %u",
1508 (unsigned long long)iters, UINT32_MAX);
1509 goto error;
1510 }
1511 iters = MAX(iters, QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
1512 luks->header.master_key_iterations = iters;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001513
1514 /* Hash the master key, saving the result in the LUKS
1515 * header. This hash is used when opening the encrypted
1516 * device to verify that the user password unlocked a
1517 * valid master key
1518 */
1519 if (qcrypto_pbkdf2(luks_opts.hash_alg,
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001520 masterkey, luks->header.master_key_len,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001521 luks->header.master_key_salt,
1522 QCRYPTO_BLOCK_LUKS_SALT_LEN,
1523 luks->header.master_key_iterations,
1524 luks->header.master_key_digest,
1525 QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
1526 errp) < 0) {
1527 goto error;
1528 }
1529
Maxim Levitskybd56a552019-09-26 00:35:25 +03001530 /* start with the sector that follows the header*/
1531 header_sectors = QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET /
1532 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001533
Maxim Levitskybd56a552019-09-26 00:35:25 +03001534 split_key_sectors =
1535 qcrypto_block_luks_splitkeylen_sectors(luks,
1536 header_sectors,
1537 QCRYPTO_BLOCK_LUKS_STRIPES);
1538
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001539 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
Maxim Levitskybd56a552019-09-26 00:35:25 +03001540 QCryptoBlockLUKSKeySlot *slot = &luks->header.key_slots[i];
1541 slot->active = QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001542
Maxim Levitskybd56a552019-09-26 00:35:25 +03001543 slot->key_offset_sector = header_sectors + i * split_key_sectors;
1544 slot->stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001545 }
1546
Hyman Huangd74523a2024-01-30 13:37:21 +08001547 if (block->detached_header) {
1548 /*
1549 * For a detached LUKS header image, set the payload_offset_sector
1550 * to 0 to specify the starting point for read/write
1551 */
1552 luks->header.payload_offset_sector = 0;
1553 } else {
1554 /*
1555 * The total size of the LUKS headers is the partition header + key
1556 * slot headers, rounded up to the nearest sector, combined with
1557 * the size of each master key material region, also rounded up
1558 * to the nearest sector
1559 */
1560 luks->header.payload_offset_sector = header_sectors +
1561 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS * split_key_sectors;
1562 }
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001563
Daniel P. Berrange850f49d2017-09-27 13:53:36 +01001564 block->sector_size = QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001565 block->payload_offset = luks->header.payload_offset_sector *
Daniel P. Berrange850f49d2017-09-27 13:53:36 +01001566 block->sector_size;
Hyman Huangd74523a2024-01-30 13:37:21 +08001567 detached_header_size =
1568 (header_sectors + QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS *
1569 split_key_sectors) * block->sector_size;
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001570
1571 /* Reserve header space to match payload offset */
Hyman Huangd74523a2024-01-30 13:37:21 +08001572 initfunc(block, detached_header_size, opaque, &local_err);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001573 if (local_err) {
1574 error_propagate(errp, local_err);
1575 goto error;
1576 }
1577
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001578
Maxim Levitsky3994a7c2019-09-26 00:35:24 +03001579 /* populate the slot 0 with the password encrypted master key*/
1580 /* This will also store the header */
1581 if (qcrypto_block_luks_store_key(block,
1582 0,
1583 password,
1584 masterkey,
1585 luks_opts.iter_time,
1586 writefunc,
1587 opaque,
1588 errp) < 0) {
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001589 goto error;
1590 }
1591
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001592 memset(masterkey, 0, luks->header.master_key_len);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001593
1594 return 0;
1595
1596 error:
1597 if (masterkey) {
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001598 memset(masterkey, 0, luks->header.master_key_len);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001599 }
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001600
Vladimir Sementsov-Ogievskiyc972fa12018-12-07 19:13:51 +03001601 qcrypto_block_free_cipher(block);
Vladimir Sementsov-Ogievskiyb640adc2018-12-07 19:13:47 +03001602 qcrypto_ivgen_free(block->ivgen);
1603
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001604 g_free(luks->secret);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001605 g_free(luks);
1606 return -1;
1607}
1608
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001609static int
1610qcrypto_block_luks_amend_add_keyslot(QCryptoBlock *block,
1611 QCryptoBlockReadFunc readfunc,
1612 QCryptoBlockWriteFunc writefunc,
1613 void *opaque,
1614 QCryptoBlockAmendOptionsLUKS *opts_luks,
1615 bool force,
1616 Error **errp)
1617{
1618 QCryptoBlockLUKS *luks = block->opaque;
1619 uint64_t iter_time = opts_luks->has_iter_time ?
1620 opts_luks->iter_time :
1621 QCRYPTO_BLOCK_LUKS_DEFAULT_ITER_TIME_MS;
1622 int keyslot;
1623 g_autofree char *old_password = NULL;
1624 g_autofree char *new_password = NULL;
1625 g_autofree uint8_t *master_key = NULL;
1626
Markus Armbruster16110c82022-11-04 17:06:54 +01001627 char *secret = opts_luks->secret ?: luks->secret;
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001628
Markus Armbruster16110c82022-11-04 17:06:54 +01001629 if (!opts_luks->new_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001630 error_setg(errp, "'new-secret' is required to activate a keyslot");
1631 return -1;
1632 }
Markus Armbruster16110c82022-11-04 17:06:54 +01001633 if (opts_luks->old_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001634 error_setg(errp,
1635 "'old-secret' must not be given when activating keyslots");
1636 return -1;
1637 }
1638
1639 if (opts_luks->has_keyslot) {
1640 keyslot = opts_luks->keyslot;
1641 if (keyslot < 0 || keyslot >= QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS) {
1642 error_setg(errp,
1643 "Invalid keyslot %u specified, must be between 0 and %u",
1644 keyslot, QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS - 1);
1645 return -1;
1646 }
1647 } else {
1648 keyslot = qcrypto_block_luks_find_free_keyslot(luks);
1649 if (keyslot == -1) {
1650 error_setg(errp,
1651 "Can't add a keyslot - all keyslots are in use");
1652 return -1;
1653 }
1654 }
1655
1656 if (!force && qcrypto_block_luks_slot_active(luks, keyslot)) {
1657 error_setg(errp,
1658 "Refusing to overwrite active keyslot %i - "
1659 "please erase it first",
1660 keyslot);
1661 return -1;
1662 }
1663
1664 /* Locate the password that will be used to retrieve the master key */
1665 old_password = qcrypto_secret_lookup_as_utf8(secret, errp);
1666 if (!old_password) {
1667 return -1;
1668 }
1669
1670 /* Retrieve the master key */
1671 master_key = g_new0(uint8_t, luks->header.master_key_len);
1672
1673 if (qcrypto_block_luks_find_key(block, old_password, master_key,
1674 readfunc, opaque, errp) < 0) {
1675 error_append_hint(errp, "Failed to retrieve the master key");
1676 return -1;
1677 }
1678
1679 /* Locate the new password*/
1680 new_password = qcrypto_secret_lookup_as_utf8(opts_luks->new_secret, errp);
1681 if (!new_password) {
1682 return -1;
1683 }
1684
1685 /* Now set the new keyslots */
1686 if (qcrypto_block_luks_store_key(block, keyslot, new_password, master_key,
1687 iter_time, writefunc, opaque, errp)) {
1688 error_append_hint(errp, "Failed to write to keyslot %i", keyslot);
1689 return -1;
1690 }
1691 return 0;
1692}
1693
1694static int
1695qcrypto_block_luks_amend_erase_keyslots(QCryptoBlock *block,
1696 QCryptoBlockReadFunc readfunc,
1697 QCryptoBlockWriteFunc writefunc,
1698 void *opaque,
1699 QCryptoBlockAmendOptionsLUKS *opts_luks,
1700 bool force,
1701 Error **errp)
1702{
1703 QCryptoBlockLUKS *luks = block->opaque;
1704 g_autofree uint8_t *tmpkey = NULL;
1705 g_autofree char *old_password = NULL;
1706
Markus Armbruster16110c82022-11-04 17:06:54 +01001707 if (opts_luks->new_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001708 error_setg(errp,
1709 "'new-secret' must not be given when erasing keyslots");
1710 return -1;
1711 }
1712 if (opts_luks->has_iter_time) {
1713 error_setg(errp,
1714 "'iter-time' must not be given when erasing keyslots");
1715 return -1;
1716 }
Markus Armbruster16110c82022-11-04 17:06:54 +01001717 if (opts_luks->secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001718 error_setg(errp,
1719 "'secret' must not be given when erasing keyslots");
1720 return -1;
1721 }
1722
1723 /* Load the old password if given */
Markus Armbruster16110c82022-11-04 17:06:54 +01001724 if (opts_luks->old_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001725 old_password = qcrypto_secret_lookup_as_utf8(opts_luks->old_secret,
1726 errp);
1727 if (!old_password) {
1728 return -1;
1729 }
1730
1731 /*
1732 * Allocate a temporary key buffer that we will need when
1733 * checking if slot matches the given old password
1734 */
1735 tmpkey = g_new0(uint8_t, luks->header.master_key_len);
1736 }
1737
1738 /* Erase an explicitly given keyslot */
1739 if (opts_luks->has_keyslot) {
1740 int keyslot = opts_luks->keyslot;
1741
1742 if (keyslot < 0 || keyslot >= QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS) {
1743 error_setg(errp,
1744 "Invalid keyslot %i specified, must be between 0 and %i",
1745 keyslot, QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS - 1);
1746 return -1;
1747 }
1748
Markus Armbruster16110c82022-11-04 17:06:54 +01001749 if (opts_luks->old_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001750 int rv = qcrypto_block_luks_load_key(block,
1751 keyslot,
1752 old_password,
1753 tmpkey,
1754 readfunc,
1755 opaque,
1756 errp);
1757 if (rv == -1) {
1758 return -1;
1759 } else if (rv == 0) {
1760 error_setg(errp,
1761 "Given keyslot %i doesn't contain the given "
1762 "old password for erase operation",
1763 keyslot);
1764 return -1;
1765 }
1766 }
1767
1768 if (!force && !qcrypto_block_luks_slot_active(luks, keyslot)) {
1769 error_setg(errp,
1770 "Given keyslot %i is already erased (inactive) ",
1771 keyslot);
1772 return -1;
1773 }
1774
1775 if (!force && qcrypto_block_luks_count_active_slots(luks) == 1) {
1776 error_setg(errp,
1777 "Attempt to erase the only active keyslot %i "
1778 "which will erase all the data in the image "
1779 "irreversibly - refusing operation",
1780 keyslot);
1781 return -1;
1782 }
1783
1784 if (qcrypto_block_luks_erase_key(block, keyslot,
1785 writefunc, opaque, errp)) {
1786 error_append_hint(errp, "Failed to erase keyslot %i", keyslot);
1787 return -1;
1788 }
1789
1790 /* Erase all keyslots that match the given old password */
Markus Armbruster16110c82022-11-04 17:06:54 +01001791 } else if (opts_luks->old_secret) {
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001792
1793 unsigned long slots_to_erase_bitmap = 0;
1794 size_t i;
1795 int slot_count;
1796
1797 assert(QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS <=
1798 sizeof(slots_to_erase_bitmap) * 8);
1799
1800 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1801 int rv = qcrypto_block_luks_load_key(block,
1802 i,
1803 old_password,
1804 tmpkey,
1805 readfunc,
1806 opaque,
1807 errp);
1808 if (rv == -1) {
1809 return -1;
1810 } else if (rv == 1) {
1811 bitmap_set(&slots_to_erase_bitmap, i, 1);
1812 }
1813 }
1814
1815 slot_count = bitmap_count_one(&slots_to_erase_bitmap,
1816 QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
1817 if (slot_count == 0) {
1818 error_setg(errp,
1819 "No keyslots match given (old) password for erase operation");
1820 return -1;
1821 }
1822
1823 if (!force &&
1824 slot_count == qcrypto_block_luks_count_active_slots(luks)) {
1825 error_setg(errp,
1826 "All the active keyslots match the (old) password that "
1827 "was given and erasing them will erase all the data in "
1828 "the image irreversibly - refusing operation");
1829 return -1;
1830 }
1831
1832 /* Now apply the update */
1833 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
1834 if (!test_bit(i, &slots_to_erase_bitmap)) {
1835 continue;
1836 }
1837 if (qcrypto_block_luks_erase_key(block, i, writefunc,
1838 opaque, errp)) {
1839 error_append_hint(errp, "Failed to erase keyslot %zu", i);
1840 return -1;
1841 }
1842 }
1843 } else {
1844 error_setg(errp,
1845 "To erase keyslot(s), either explicit keyslot index "
1846 "or the password currently contained in them must be given");
1847 return -1;
1848 }
1849 return 0;
1850}
1851
1852static int
1853qcrypto_block_luks_amend_options(QCryptoBlock *block,
1854 QCryptoBlockReadFunc readfunc,
1855 QCryptoBlockWriteFunc writefunc,
1856 void *opaque,
1857 QCryptoBlockAmendOptions *options,
1858 bool force,
1859 Error **errp)
1860{
1861 QCryptoBlockAmendOptionsLUKS *opts_luks = &options->u.luks;
1862
1863 switch (opts_luks->state) {
1864 case Q_CRYPTO_BLOCKLUKS_KEYSLOT_STATE_ACTIVE:
1865 return qcrypto_block_luks_amend_add_keyslot(block, readfunc,
1866 writefunc, opaque,
1867 opts_luks, force, errp);
1868 case Q_CRYPTO_BLOCKLUKS_KEYSLOT_STATE_INACTIVE:
1869 return qcrypto_block_luks_amend_erase_keyslots(block, readfunc,
1870 writefunc, opaque,
1871 opts_luks, force, errp);
1872 default:
1873 g_assert_not_reached();
1874 }
1875}
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001876
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001877static int qcrypto_block_luks_get_info(QCryptoBlock *block,
1878 QCryptoBlockInfo *info,
1879 Error **errp)
1880{
1881 QCryptoBlockLUKS *luks = block->opaque;
1882 QCryptoBlockInfoLUKSSlot *slot;
Eric Blakec3033fd2021-01-13 16:10:12 -06001883 QCryptoBlockInfoLUKSSlotList **tail = &info->u.luks.slots;
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001884 size_t i;
1885
1886 info->u.luks.cipher_alg = luks->cipher_alg;
1887 info->u.luks.cipher_mode = luks->cipher_mode;
1888 info->u.luks.ivgen_alg = luks->ivgen_alg;
1889 if (info->u.luks.ivgen_alg == QCRYPTO_IVGEN_ALG_ESSIV) {
1890 info->u.luks.has_ivgen_hash_alg = true;
1891 info->u.luks.ivgen_hash_alg = luks->ivgen_hash_alg;
1892 }
1893 info->u.luks.hash_alg = luks->hash_alg;
1894 info->u.luks.payload_offset = block->payload_offset;
1895 info->u.luks.master_key_iters = luks->header.master_key_iterations;
1896 info->u.luks.uuid = g_strndup((const char *)luks->header.uuid,
1897 sizeof(luks->header.uuid));
Hyman Huang0bd779e2024-01-30 13:37:24 +08001898 info->u.luks.detached_header = block->detached_header;
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001899
1900 for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
Eric Blakec3033fd2021-01-13 16:10:12 -06001901 slot = g_new0(QCryptoBlockInfoLUKSSlot, 1);
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001902 slot->active = luks->header.key_slots[i].active ==
1903 QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED;
Maxim Levitskyf0d3c362019-09-26 00:35:16 +03001904 slot->key_offset = luks->header.key_slots[i].key_offset_sector
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001905 * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE;
1906 if (slot->active) {
1907 slot->has_iters = true;
1908 slot->iters = luks->header.key_slots[i].iterations;
1909 slot->has_stripes = true;
1910 slot->stripes = luks->header.key_slots[i].stripes;
1911 }
1912
Eric Blakec3033fd2021-01-13 16:10:12 -06001913 QAPI_LIST_APPEND(tail, slot);
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001914 }
1915
1916 return 0;
1917}
1918
1919
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001920static void qcrypto_block_luks_cleanup(QCryptoBlock *block)
1921{
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001922 QCryptoBlockLUKS *luks = block->opaque;
1923 if (luks) {
1924 g_free(luks->secret);
1925 g_free(luks);
1926 }
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001927}
1928
1929
1930static int
1931qcrypto_block_luks_decrypt(QCryptoBlock *block,
Daniel P. Berrange46097422017-09-27 13:53:39 +01001932 uint64_t offset,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001933 uint8_t *buf,
1934 size_t len,
1935 Error **errp)
1936{
Daniel P. Berrange46097422017-09-27 13:53:39 +01001937 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1938 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
Vladimir Sementsov-Ogievskiy0f0d5962018-12-07 19:13:50 +03001939 return qcrypto_block_decrypt_helper(block,
1940 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1941 offset, buf, len, errp);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001942}
1943
1944
1945static int
1946qcrypto_block_luks_encrypt(QCryptoBlock *block,
Daniel P. Berrange46097422017-09-27 13:53:39 +01001947 uint64_t offset,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001948 uint8_t *buf,
1949 size_t len,
1950 Error **errp)
1951{
Daniel P. Berrange46097422017-09-27 13:53:39 +01001952 assert(QEMU_IS_ALIGNED(offset, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
1953 assert(QEMU_IS_ALIGNED(len, QCRYPTO_BLOCK_LUKS_SECTOR_SIZE));
Vladimir Sementsov-Ogievskiy0f0d5962018-12-07 19:13:50 +03001954 return qcrypto_block_encrypt_helper(block,
1955 QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,
1956 offset, buf, len, errp);
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001957}
1958
1959
1960const QCryptoBlockDriver qcrypto_block_driver_luks = {
1961 .open = qcrypto_block_luks_open,
1962 .create = qcrypto_block_luks_create,
Maxim Levitsky557d2bd2020-06-25 14:55:37 +02001963 .amend = qcrypto_block_luks_amend_options,
Daniel P. Berrange40c85022016-07-22 13:53:34 +01001964 .get_info = qcrypto_block_luks_get_info,
Daniel P. Berrange3e308f22015-10-24 11:55:48 +01001965 .cleanup = qcrypto_block_luks_cleanup,
1966 .decrypt = qcrypto_block_luks_decrypt,
1967 .encrypt = qcrypto_block_luks_encrypt,
1968 .has_format = qcrypto_block_luks_has_format,
1969};