Coverage Report

Created: 2026-11-20 08:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qemu/block/crypto.c
Line
Count
Source
1
/*
2
 * QEMU block full disk encryption
3
 *
4
 * Copyright (c) 2015-2016 Red Hat, Inc.
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 *
19
 */
20
21
#include "qemu/osdep.h"
22
23
#include "block/block_int.h"
24
#include "block/qdict.h"
25
#include "system/block-backend.h"
26
#include "crypto/block.h"
27
#include "qapi/opts-visitor.h"
28
#include "qapi/qapi-visit-crypto.h"
29
#include "qapi/qobject-input-visitor.h"
30
#include "qapi/error.h"
31
#include "qemu/module.h"
32
#include "qemu/option.h"
33
#include "qemu/cutils.h"
34
#include "qemu/memalign.h"
35
#include "crypto.h"
36
37
typedef struct BlockCrypto BlockCrypto;
38
39
struct BlockCrypto {
40
    QCryptoBlock *block;
41
    bool updating_keys;
42
    BdrvChild *header;  /* Reference to the detached LUKS header */
43
};
44
45
46
static int block_crypto_probe_generic(QCryptoBlockFormat format,
47
                                      const uint8_t *buf,
48
                                      int buf_size,
49
                                      const char *filename)
50
0
{
51
0
    if (qcrypto_block_has_format(format, buf, buf_size)) {
52
0
        return 100;
53
0
    } else {
54
0
        return 0;
55
0
    }
56
0
}
57
58
59
static int coroutine_mixed_fn
60
block_crypto_read_func(QCryptoBlock *block,
61
                       size_t offset,
62
                       uint8_t *buf,
63
                       size_t buflen,
64
                       void *opaque,
65
                       Error **errp)
66
0
{
67
0
    BlockDriverState *bs = opaque;
68
0
    BlockCrypto *crypto = bs->opaque;
69
0
    ssize_t ret;
70
71
0
    if (qemu_in_coroutine()) {
72
0
        GRAPH_RDLOCK_GUARD();
73
74
0
        ret = bdrv_co_pread(crypto->header ? crypto->header : bs->file,
75
0
                            offset, buflen, buf, 0);
76
0
    } else {
77
0
        GLOBAL_STATE_CODE();
78
0
        GRAPH_RDLOCK_GUARD_MAINLOOP();
79
80
0
        ret = bdrv_pread(crypto->header ? crypto->header : bs->file,
81
0
                         offset, buflen, buf, 0);
82
0
    }
83
0
    if (ret < 0) {
84
0
        error_setg_errno(errp, -ret, "Could not read encryption header");
85
0
        return ret;
86
0
    }
87
0
    return 0;
88
0
}
89
90
static int block_crypto_write_func(QCryptoBlock *block,
91
                                   size_t offset,
92
                                   const uint8_t *buf,
93
                                   size_t buflen,
94
                                   void *opaque,
95
                                   Error **errp)
96
0
{
97
0
    BlockDriverState *bs = opaque;
98
0
    BlockCrypto *crypto = bs->opaque;
99
0
    ssize_t ret;
100
101
0
    if (qemu_in_coroutine()) {
102
0
        GRAPH_RDLOCK_GUARD();
103
104
0
        ret = bdrv_co_pwrite(crypto->header ? crypto->header : bs->file,
105
0
                             offset, buflen, buf, 0);
106
0
    } else {
107
0
        GLOBAL_STATE_CODE();
108
0
        GRAPH_RDLOCK_GUARD_MAINLOOP();
109
110
0
        ret = bdrv_pwrite(crypto->header ? crypto->header : bs->file,
111
0
                          offset, buflen, buf, 0);
112
0
    }
113
0
    if (ret < 0) {
114
0
        error_setg_errno(errp, -ret, "Could not write encryption header");
115
0
        return ret;
116
0
    }
117
0
    return 0;
118
0
}
119
120
121
struct BlockCryptoCreateData {
122
    BlockBackend *blk;
123
    uint64_t size;
124
    PreallocMode prealloc;
125
};
126
127
128
static int coroutine_fn GRAPH_UNLOCKED
129
block_crypto_create_write_func(QCryptoBlock *block, size_t offset,
130
                               const uint8_t *buf, size_t buflen, void *opaque,
131
                               Error **errp)
132
0
{
133
0
    struct BlockCryptoCreateData *data = opaque;
134
0
    ssize_t ret;
135
136
0
    ret = blk_pwrite(data->blk, offset, buflen, buf, 0);
137
0
    if (ret < 0) {
138
0
        error_setg_errno(errp, -ret, "Could not write encryption header");
139
0
        return ret;
140
0
    }
141
0
    return 0;
142
0
}
143
144
static int coroutine_fn GRAPH_UNLOCKED
145
block_crypto_create_init_func(QCryptoBlock *block, size_t headerlen,
146
                              void *opaque, Error **errp)
147
0
{
148
0
    struct BlockCryptoCreateData *data = opaque;
149
0
    Error *local_error = NULL;
150
0
    int ret;
151
152
0
    if (data->size > INT64_MAX || headerlen > INT64_MAX - data->size) {
153
0
        ret = -EFBIG;
154
0
        goto error;
155
0
    }
156
157
    /* User provided size should reflect amount of space made
158
     * available to the guest, so we must take account of that
159
     * which will be used by the crypto header
160
     */
161
0
    ret = blk_truncate(data->blk, data->size + headerlen, false,
162
0
                       data->prealloc, 0, &local_error);
163
164
0
    if (ret >= 0) {
165
0
        return 0;
166
0
    }
167
168
0
error:
169
0
    if (ret == -EFBIG) {
170
        /* Replace the error message with a better one */
171
0
        error_free(local_error);
172
0
        error_setg(errp, "The requested file size is too large");
173
0
    } else {
174
0
        error_propagate(errp, local_error);
175
0
    }
176
177
0
    return ret;
178
0
}
179
180
static int coroutine_fn GRAPH_UNLOCKED
181
block_crypto_co_format_luks_payload(BlockdevCreateOptionsLUKS *luks_opts,
182
                                    Error **errp)
183
0
{
184
0
    BlockDriverState *bs = NULL;
185
0
    BlockBackend *blk = NULL;
186
0
    Error *local_error = NULL;
187
0
    int ret;
188
189
0
    if (luks_opts->size > INT64_MAX) {
190
0
        return -EFBIG;
191
0
    }
192
193
0
    bs = bdrv_co_open_blockdev_ref(luks_opts->file, errp);
194
0
    if (bs == NULL) {
195
0
        return -EIO;
196
0
    }
197
198
0
    blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE,
199
0
                             BLK_PERM_ALL, errp);
200
0
    if (!blk) {
201
0
        ret = -EPERM;
202
0
        goto fail;
203
0
    }
204
205
0
    ret = blk_truncate(blk, luks_opts->size, true,
206
0
                       luks_opts->preallocation, 0, &local_error);
207
0
    if (ret < 0) {
208
0
        if (ret == -EFBIG) {
209
            /* Replace the error message with a better one */
210
0
            error_free(local_error);
211
0
            error_setg(errp, "The requested file size is too large");
212
0
        }
213
0
        goto fail;
214
0
    }
215
216
0
    ret = 0;
217
218
0
fail:
219
0
    bdrv_co_unref(bs);
220
0
    return ret;
221
0
}
222
223
static QemuOptsList block_crypto_runtime_opts_luks = {
224
    .name = "crypto",
225
    .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head),
226
    .desc = {
227
        BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""),
228
        { /* end of list */ }
229
    },
230
};
231
232
233
static QemuOptsList block_crypto_create_opts_luks = {
234
    .name = "crypto",
235
    .head = QTAILQ_HEAD_INITIALIZER(block_crypto_create_opts_luks.head),
236
    .desc = {
237
        {
238
            .name = BLOCK_OPT_SIZE,
239
            .type = QEMU_OPT_SIZE,
240
            .help = "Virtual disk size"
241
        },
242
        BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""),
243
        BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG(""),
244
        BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE(""),
245
        BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG(""),
246
        BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG(""),
247
        BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG(""),
248
        BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME(""),
249
        BLOCK_CRYPTO_OPT_DEF_LUKS_DETACHED_HEADER(""),
250
        { /* end of list */ }
251
    },
252
};
253
254
255
static QemuOptsList block_crypto_amend_opts_luks = {
256
    .name = "crypto",
257
    .head = QTAILQ_HEAD_INITIALIZER(block_crypto_create_opts_luks.head),
258
    .desc = {
259
        BLOCK_CRYPTO_OPT_DEF_LUKS_STATE(""),
260
        BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT(""),
261
        BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET(""),
262
        BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET(""),
263
        BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME(""),
264
        { /* end of list */ }
265
    },
266
};
267
268
QCryptoBlockOpenOptions *
269
block_crypto_open_opts_init(QDict *opts, Error **errp)
270
0
{
271
0
    Visitor *v;
272
0
    QCryptoBlockOpenOptions *ret;
273
274
0
    v = qobject_input_visitor_new_flat_confused(opts, errp);
275
0
    if (!v) {
276
0
        return NULL;
277
0
    }
278
279
0
    visit_type_QCryptoBlockOpenOptions(v, NULL, &ret, errp);
280
281
0
    visit_free(v);
282
0
    return ret;
283
0
}
284
285
286
QCryptoBlockCreateOptions *
287
block_crypto_create_opts_init(QDict *opts, Error **errp)
288
0
{
289
0
    Visitor *v;
290
0
    QCryptoBlockCreateOptions *ret;
291
292
0
    v = qobject_input_visitor_new_flat_confused(opts, errp);
293
0
    if (!v) {
294
0
        return NULL;
295
0
    }
296
297
0
    visit_type_QCryptoBlockCreateOptions(v, NULL, &ret, errp);
298
299
0
    visit_free(v);
300
0
    return ret;
301
0
}
302
303
QCryptoBlockAmendOptions *
304
block_crypto_amend_opts_init(QDict *opts, Error **errp)
305
0
{
306
0
    Visitor *v;
307
0
    QCryptoBlockAmendOptions *ret;
308
309
0
    v = qobject_input_visitor_new_flat_confused(opts, errp);
310
0
    if (!v) {
311
0
        return NULL;
312
0
    }
313
314
0
    visit_type_QCryptoBlockAmendOptions(v, NULL, &ret, errp);
315
316
0
    visit_free(v);
317
0
    return ret;
318
0
}
319
320
321
static int block_crypto_open_generic(QCryptoBlockFormat format,
322
                                     QemuOptsList *opts_spec,
323
                                     BlockDriverState *bs,
324
                                     QDict *options,
325
                                     int flags,
326
                                     Error **errp)
327
0
{
328
0
    ERRP_GUARD();
329
330
0
    BlockCrypto *crypto = bs->opaque;
331
0
    QemuOpts *opts = NULL;
332
0
    int ret;
333
0
    QCryptoBlockOpenOptions *open_opts = NULL;
334
0
    unsigned int cflags = 0;
335
0
    QDict *cryptoopts = NULL;
336
337
0
    GLOBAL_STATE_CODE();
338
339
0
    ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
340
0
    if (ret < 0) {
341
0
        return ret;
342
0
    }
343
344
0
    crypto->header = bdrv_open_child(NULL, options, "header", bs,
345
0
                                     &child_of_bds, BDRV_CHILD_METADATA,
346
0
                                     true, errp);
347
0
    if (*errp != NULL) {
348
0
        return -EINVAL;
349
0
    }
350
351
0
    GRAPH_RDLOCK_GUARD_MAINLOOP();
352
353
0
    bs->supported_write_flags = BDRV_REQ_FUA &
354
0
        bs->file->bs->supported_write_flags;
355
356
0
    opts = qemu_opts_create(opts_spec, NULL, 0, &error_abort);
357
0
    if (!qemu_opts_absorb_qdict(opts, options, errp)) {
358
0
        ret = -EINVAL;
359
0
        goto cleanup;
360
0
    }
361
362
0
    cryptoopts = qemu_opts_to_qdict(opts, NULL);
363
0
    qdict_put_str(cryptoopts, "format", QCryptoBlockFormat_str(format));
364
365
0
    open_opts = block_crypto_open_opts_init(cryptoopts, errp);
366
0
    if (!open_opts) {
367
0
        ret = -EINVAL;
368
0
        goto cleanup;
369
0
    }
370
371
0
    if (flags & BDRV_O_NO_IO) {
372
0
        cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
373
0
    }
374
0
    if (crypto->header != NULL) {
375
0
        cflags |= QCRYPTO_BLOCK_OPEN_DETACHED;
376
0
    }
377
0
    crypto->block = qcrypto_block_open(open_opts, NULL,
378
0
                                       block_crypto_read_func,
379
0
                                       bs,
380
0
                                       cflags,
381
0
                                       errp);
382
383
0
    if (!crypto->block) {
384
0
        ret = -EIO;
385
0
        goto cleanup;
386
0
    }
387
388
0
    bs->encrypted = true;
389
390
0
    ret = 0;
391
0
 cleanup:
392
0
    qobject_unref(cryptoopts);
393
0
    qapi_free_QCryptoBlockOpenOptions(open_opts);
394
0
    return ret;
395
0
}
396
397
398
static int coroutine_fn GRAPH_UNLOCKED
399
block_crypto_co_create_generic(BlockDriverState *bs, int64_t size,
400
                               QCryptoBlockCreateOptions *opts,
401
                               PreallocMode prealloc,
402
                               unsigned int flags,
403
                               Error **errp)
404
0
{
405
0
    int ret;
406
0
    BlockBackend *blk;
407
0
    QCryptoBlock *crypto = NULL;
408
0
    struct BlockCryptoCreateData data;
409
410
0
    blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
411
0
                             errp);
412
0
    if (!blk) {
413
0
        ret = -EPERM;
414
0
        goto cleanup;
415
0
    }
416
417
0
    if (prealloc == PREALLOC_MODE_METADATA) {
418
0
        prealloc = PREALLOC_MODE_OFF;
419
0
    }
420
421
0
    data = (struct BlockCryptoCreateData) {
422
0
        .blk = blk,
423
0
        .size = flags & QCRYPTO_BLOCK_CREATE_DETACHED ? 0 : size,
424
0
        .prealloc = prealloc,
425
0
    };
426
427
0
    crypto = qcrypto_block_create(opts, NULL,
428
0
                                  block_crypto_create_init_func,
429
0
                                  block_crypto_create_write_func,
430
0
                                  &data,
431
0
                                  flags,
432
0
                                  errp);
433
434
0
    if (!crypto) {
435
0
        ret = -EIO;
436
0
        goto cleanup;
437
0
    }
438
439
0
    ret = 0;
440
0
 cleanup:
441
0
    qcrypto_block_free(crypto);
442
0
    blk_co_unref(blk);
443
0
    return ret;
444
0
}
445
446
static int coroutine_fn GRAPH_RDLOCK
447
block_crypto_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,
448
                         PreallocMode prealloc, BdrvRequestFlags flags,
449
                         Error **errp)
450
0
{
451
0
    BlockCrypto *crypto = bs->opaque;
452
0
    uint64_t payload_offset =
453
0
        qcrypto_block_get_payload_offset(crypto->block);
454
455
0
    if (payload_offset > INT64_MAX - offset) {
456
0
        error_setg(errp, "The requested file size is too large");
457
0
        return -EFBIG;
458
0
    }
459
460
0
    offset += payload_offset;
461
462
0
    return bdrv_co_truncate(bs->file, offset, exact, prealloc, 0, errp);
463
0
}
464
465
static void block_crypto_close(BlockDriverState *bs)
466
0
{
467
0
    BlockCrypto *crypto = bs->opaque;
468
0
    qcrypto_block_free(crypto->block);
469
0
}
470
471
static int block_crypto_reopen_prepare(BDRVReopenState *state,
472
                                       BlockReopenQueue *queue, Error **errp)
473
0
{
474
    /* nothing needs checking */
475
0
    return 0;
476
0
}
477
478
/*
479
 * 1 MB bounce buffer gives good performance / memory tradeoff
480
 * when using cache=none|directsync.
481
 */
482
#define BLOCK_CRYPTO_MAX_IO_SIZE (1024 * 1024)
483
484
static int coroutine_fn GRAPH_RDLOCK
485
block_crypto_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
486
                       QEMUIOVector *qiov, BdrvRequestFlags flags)
487
0
{
488
0
    BlockCrypto *crypto = bs->opaque;
489
0
    uint64_t cur_bytes; /* number of bytes in current iteration */
490
0
    uint64_t bytes_done = 0;
491
0
    uint8_t *cipher_data = NULL;
492
0
    QEMUIOVector hd_qiov;
493
0
    int ret = 0;
494
0
    uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
495
0
    uint64_t payload_offset = qcrypto_block_get_payload_offset(crypto->block);
496
497
0
    assert(payload_offset < INT64_MAX);
498
0
    assert(QEMU_IS_ALIGNED(offset, sector_size));
499
0
    assert(QEMU_IS_ALIGNED(bytes, sector_size));
500
501
0
    qemu_iovec_init(&hd_qiov, qiov->niov);
502
503
    /* Bounce buffer because we don't wish to expose cipher text
504
     * in qiov which points to guest memory.
505
     */
506
0
    cipher_data =
507
0
        qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_IO_SIZE,
508
0
                                              qiov->size));
509
0
    if (cipher_data == NULL) {
510
0
        ret = -ENOMEM;
511
0
        goto cleanup;
512
0
    }
513
514
0
    while (bytes) {
515
0
        cur_bytes = MIN(bytes, BLOCK_CRYPTO_MAX_IO_SIZE);
516
517
0
        qemu_iovec_reset(&hd_qiov);
518
0
        qemu_iovec_add(&hd_qiov, cipher_data, cur_bytes);
519
520
0
        ret = bdrv_co_preadv(bs->file, payload_offset + offset + bytes_done,
521
0
                             cur_bytes, &hd_qiov, 0);
522
0
        if (ret < 0) {
523
0
            goto cleanup;
524
0
        }
525
526
0
        if (qcrypto_block_decrypt(crypto->block, offset + bytes_done,
527
0
                                  cipher_data, cur_bytes, NULL) < 0) {
528
0
            ret = -EIO;
529
0
            goto cleanup;
530
0
        }
531
532
0
        qemu_iovec_from_buf(qiov, bytes_done, cipher_data, cur_bytes);
533
534
0
        bytes -= cur_bytes;
535
0
        bytes_done += cur_bytes;
536
0
    }
537
538
0
 cleanup:
539
0
    qemu_iovec_destroy(&hd_qiov);
540
0
    qemu_vfree(cipher_data);
541
542
0
    return ret;
543
0
}
544
545
546
static int coroutine_fn GRAPH_RDLOCK
547
block_crypto_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
548
                        QEMUIOVector *qiov, BdrvRequestFlags flags)
549
0
{
550
0
    BlockCrypto *crypto = bs->opaque;
551
0
    uint64_t cur_bytes; /* number of bytes in current iteration */
552
0
    uint64_t bytes_done = 0;
553
0
    uint8_t *cipher_data = NULL;
554
0
    QEMUIOVector hd_qiov;
555
0
    int ret = 0;
556
0
    uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
557
0
    uint64_t payload_offset = qcrypto_block_get_payload_offset(crypto->block);
558
559
0
    flags &= ~BDRV_REQ_REGISTERED_BUF;
560
561
0
    assert(payload_offset < INT64_MAX);
562
0
    assert(QEMU_IS_ALIGNED(offset, sector_size));
563
0
    assert(QEMU_IS_ALIGNED(bytes, sector_size));
564
565
0
    qemu_iovec_init(&hd_qiov, qiov->niov);
566
567
    /* Bounce buffer because we're not permitted to touch
568
     * contents of qiov - it points to guest memory.
569
     */
570
0
    cipher_data =
571
0
        qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_IO_SIZE,
572
0
                                              qiov->size));
573
0
    if (cipher_data == NULL) {
574
0
        ret = -ENOMEM;
575
0
        goto cleanup;
576
0
    }
577
578
0
    while (bytes) {
579
0
        cur_bytes = MIN(bytes, BLOCK_CRYPTO_MAX_IO_SIZE);
580
581
0
        qemu_iovec_to_buf(qiov, bytes_done, cipher_data, cur_bytes);
582
583
0
        if (qcrypto_block_encrypt(crypto->block, offset + bytes_done,
584
0
                                  cipher_data, cur_bytes, NULL) < 0) {
585
0
            ret = -EIO;
586
0
            goto cleanup;
587
0
        }
588
589
0
        qemu_iovec_reset(&hd_qiov);
590
0
        qemu_iovec_add(&hd_qiov, cipher_data, cur_bytes);
591
592
0
        ret = bdrv_co_pwritev(bs->file, payload_offset + offset + bytes_done,
593
0
                              cur_bytes, &hd_qiov, flags);
594
0
        if (ret < 0) {
595
0
            goto cleanup;
596
0
        }
597
598
0
        bytes -= cur_bytes;
599
0
        bytes_done += cur_bytes;
600
0
    }
601
602
0
 cleanup:
603
0
    qemu_iovec_destroy(&hd_qiov);
604
0
    qemu_vfree(cipher_data);
605
606
0
    return ret;
607
0
}
608
609
static void block_crypto_refresh_limits(BlockDriverState *bs, Error **errp)
610
0
{
611
0
    BlockCrypto *crypto = bs->opaque;
612
0
    uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
613
0
    bs->bl.request_alignment = sector_size; /* No sub-sector I/O */
614
0
}
615
616
617
static int64_t coroutine_fn GRAPH_RDLOCK
618
block_crypto_co_getlength(BlockDriverState *bs)
619
0
{
620
0
    BlockCrypto *crypto = bs->opaque;
621
0
    int64_t len = bdrv_co_getlength(bs->file->bs);
622
623
0
    uint64_t offset = qcrypto_block_get_payload_offset(crypto->block);
624
0
    assert(offset < INT64_MAX);
625
626
0
    if (offset > len) {
627
0
        return -EIO;
628
0
    }
629
630
0
    len -= offset;
631
632
0
    return len;
633
0
}
634
635
636
static BlockMeasureInfo *block_crypto_measure(QemuOpts *opts,
637
                                              BlockDriverState *in_bs,
638
                                              Error **errp)
639
0
{
640
0
    g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
641
0
    Error *local_err = NULL;
642
0
    BlockMeasureInfo *info;
643
0
    uint64_t size;
644
0
    size_t luks_payload_size;
645
0
    QDict *cryptoopts;
646
647
    /*
648
     * Preallocation mode doesn't affect size requirements but we must consume
649
     * the option.
650
     */
651
0
    g_free(qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC));
652
653
0
    size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
654
655
0
    if (in_bs) {
656
0
        int64_t ssize = bdrv_getlength(in_bs);
657
658
0
        if (ssize < 0) {
659
0
            error_setg_errno(&local_err, -ssize,
660
0
                             "Unable to get image virtual_size");
661
0
            goto err;
662
0
        }
663
664
0
        size = ssize;
665
0
    }
666
667
0
    cryptoopts = qemu_opts_to_qdict_filtered(opts, NULL,
668
0
            &block_crypto_create_opts_luks, true);
669
0
    qdict_put_str(cryptoopts, "format", "luks");
670
0
    create_opts = block_crypto_create_opts_init(cryptoopts, &local_err);
671
0
    qobject_unref(cryptoopts);
672
0
    if (!create_opts) {
673
0
        goto err;
674
0
    }
675
676
0
    if (!qcrypto_block_calculate_payload_offset(create_opts, NULL,
677
0
                                                &luks_payload_size,
678
0
                                                &local_err)) {
679
0
        goto err;
680
0
    }
681
682
    /*
683
     * Unallocated blocks are still encrypted so allocation status makes no
684
     * difference to the file size.
685
     */
686
0
    info = g_new0(BlockMeasureInfo, 1);
687
0
    info->fully_allocated = luks_payload_size + size;
688
0
    info->required = luks_payload_size + size;
689
0
    return info;
690
691
0
err:
692
0
    error_propagate(errp, local_err);
693
0
    return NULL;
694
0
}
695
696
697
static int block_crypto_probe_luks(const uint8_t *buf,
698
                                   int buf_size,
699
0
                                   const char *filename) {
700
0
    return block_crypto_probe_generic(QCRYPTO_BLOCK_FORMAT_LUKS,
701
0
                                      buf, buf_size, filename);
702
0
}
703
704
static int block_crypto_open_luks(BlockDriverState *bs,
705
                                  QDict *options,
706
                                  int flags,
707
                                  Error **errp)
708
0
{
709
0
    return block_crypto_open_generic(QCRYPTO_BLOCK_FORMAT_LUKS,
710
0
                                     &block_crypto_runtime_opts_luks,
711
0
                                     bs, options, flags, errp);
712
0
}
713
714
static int coroutine_fn GRAPH_UNLOCKED
715
block_crypto_co_create_luks(BlockdevCreateOptions *create_options, Error **errp)
716
0
{
717
0
    BlockdevCreateOptionsLUKS *luks_opts;
718
0
    BlockDriverState *hdr_bs = NULL;
719
0
    BlockDriverState *bs = NULL;
720
0
    QCryptoBlockCreateOptions create_opts;
721
0
    PreallocMode preallocation = PREALLOC_MODE_OFF;
722
0
    unsigned int cflags = 0;
723
0
    int ret;
724
725
0
    assert(create_options->driver == BLOCKDEV_DRIVER_LUKS);
726
0
    luks_opts = &create_options->u.luks;
727
728
0
    if (luks_opts->header == NULL && luks_opts->file == NULL) {
729
0
        error_setg(errp, "Either the parameter 'header' or 'file' must "
730
0
                   "be specified");
731
0
        return -EINVAL;
732
0
    }
733
734
0
    if ((luks_opts->preallocation != PREALLOC_MODE_OFF) &&
735
0
        (luks_opts->file == NULL)) {
736
0
        error_setg(errp, "Parameter 'preallocation' requires 'file' to be "
737
0
                   "specified for formatting LUKS disk");
738
0
        return -EINVAL;
739
0
    }
740
741
0
    create_opts = (QCryptoBlockCreateOptions) {
742
0
        .format = QCRYPTO_BLOCK_FORMAT_LUKS,
743
0
        .u.luks = *qapi_BlockdevCreateOptionsLUKS_base(luks_opts),
744
0
    };
745
746
0
    if (luks_opts->has_preallocation) {
747
0
        preallocation = luks_opts->preallocation;
748
0
    }
749
750
0
    if (luks_opts->header) {
751
        /* LUKS volume with detached header */
752
0
        hdr_bs = bdrv_co_open_blockdev_ref(luks_opts->header, errp);
753
0
        if (hdr_bs == NULL) {
754
0
            return -EIO;
755
0
        }
756
757
0
        cflags |= QCRYPTO_BLOCK_CREATE_DETACHED;
758
759
        /* Format the LUKS header node */
760
0
        ret = block_crypto_co_create_generic(hdr_bs, 0, &create_opts,
761
0
                                             PREALLOC_MODE_OFF, cflags, errp);
762
0
        if (ret < 0) {
763
0
            goto fail;
764
0
        }
765
766
        /* Format the LUKS payload node */
767
0
        if (luks_opts->file) {
768
0
            ret = block_crypto_co_format_luks_payload(luks_opts, errp);
769
0
            if (ret < 0) {
770
0
                goto fail;
771
0
            }
772
0
        }
773
0
    } else if (luks_opts->file) {
774
        /* LUKS volume with none-detached header */
775
0
        bs = bdrv_co_open_blockdev_ref(luks_opts->file, errp);
776
0
        if (bs == NULL) {
777
0
            return -EIO;
778
0
        }
779
780
0
        ret = block_crypto_co_create_generic(bs, luks_opts->size, &create_opts,
781
0
                                             preallocation, cflags, errp);
782
0
        if (ret < 0) {
783
0
            goto fail;
784
0
        }
785
0
    }
786
787
0
    ret = 0;
788
0
fail:
789
0
    if (hdr_bs != NULL) {
790
0
        bdrv_co_unref(hdr_bs);
791
0
    }
792
793
0
    if (bs != NULL) {
794
0
        bdrv_co_unref(bs);
795
0
    }
796
0
    return ret;
797
0
}
798
799
static int coroutine_fn GRAPH_UNLOCKED
800
block_crypto_co_create_opts_luks(BlockDriver *drv, const char *filename,
801
                                 QemuOpts *opts, Error **errp)
802
0
{
803
0
    QCryptoBlockCreateOptions *create_opts = NULL;
804
0
    BlockDriverState *bs = NULL;
805
0
    QDict *cryptoopts;
806
0
    PreallocMode prealloc;
807
0
    char *buf = NULL;
808
0
    int64_t size;
809
0
    bool detached_hdr =
810
0
        qemu_opt_get_bool_del(opts, "detached-header", false);
811
0
    unsigned int cflags = 0;
812
0
    int ret;
813
0
    Error *local_err = NULL;
814
815
    /* Parse options */
816
0
    size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
817
818
0
    buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
819
0
    prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
820
0
                               PREALLOC_MODE_OFF, &local_err);
821
0
    g_free(buf);
822
0
    if (local_err) {
823
0
        error_propagate(errp, local_err);
824
0
        return -EINVAL;
825
0
    }
826
827
0
    cryptoopts = qemu_opts_to_qdict_filtered(opts, NULL,
828
0
                                             &block_crypto_create_opts_luks,
829
0
                                             true);
830
831
0
    qdict_put_str(cryptoopts, "format", "luks");
832
0
    create_opts = block_crypto_create_opts_init(cryptoopts, errp);
833
0
    if (!create_opts) {
834
0
        ret = -EINVAL;
835
0
        goto fail;
836
0
    }
837
838
    /* Create protocol layer */
839
0
    ret = bdrv_co_create_file(filename, opts, true, errp);
840
0
    if (ret < 0) {
841
0
        goto fail;
842
0
    }
843
844
0
    bs = bdrv_co_open(filename, NULL, NULL,
845
0
                      BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
846
0
    if (!bs) {
847
0
        ret = -EINVAL;
848
0
        goto fail;
849
0
    }
850
851
0
    if (detached_hdr) {
852
0
        cflags |= QCRYPTO_BLOCK_CREATE_DETACHED;
853
0
    }
854
855
    /* Create format layer */
856
0
    ret = block_crypto_co_create_generic(bs, size, create_opts,
857
0
                                         prealloc, cflags, errp);
858
0
    if (ret < 0) {
859
0
        goto fail;
860
0
    }
861
862
0
    ret = 0;
863
0
fail:
864
    /*
865
     * If an error occurred, delete 'filename'. Even if the file existed
866
     * beforehand, it has been truncated and corrupted in the process.
867
     */
868
0
    if (ret) {
869
0
        bdrv_graph_co_rdlock();
870
0
        bdrv_co_delete_file_noerr(bs);
871
0
        bdrv_graph_co_rdunlock();
872
0
    }
873
874
0
    bdrv_co_unref(bs);
875
0
    qapi_free_QCryptoBlockCreateOptions(create_opts);
876
0
    qobject_unref(cryptoopts);
877
0
    return ret;
878
0
}
879
880
static int coroutine_fn GRAPH_RDLOCK
881
block_crypto_co_get_info_luks(BlockDriverState *bs, BlockDriverInfo *bdi)
882
0
{
883
0
    BlockDriverInfo subbdi;
884
0
    int ret;
885
886
0
    ret = bdrv_co_get_info(bs->file->bs, &subbdi);
887
0
    if (ret != 0) {
888
0
        return ret;
889
0
    }
890
891
0
    bdi->cluster_size = subbdi.cluster_size;
892
893
0
    return 0;
894
0
}
895
896
static ImageInfoSpecific *
897
block_crypto_get_specific_info_luks(BlockDriverState *bs, Error **errp)
898
0
{
899
0
    BlockCrypto *crypto = bs->opaque;
900
0
    ImageInfoSpecific *spec_info;
901
0
    QCryptoBlockInfo *info;
902
903
0
    info = qcrypto_block_get_info(crypto->block, errp);
904
0
    if (!info) {
905
0
        return NULL;
906
0
    }
907
0
    assert(info->format == QCRYPTO_BLOCK_FORMAT_LUKS);
908
909
0
    spec_info = g_new(ImageInfoSpecific, 1);
910
0
    spec_info->type = IMAGE_INFO_SPECIFIC_KIND_LUKS;
911
0
    spec_info->u.luks.data = g_new(QCryptoBlockInfoLUKS, 1);
912
0
    *spec_info->u.luks.data = info->u.luks;
913
914
    /* Blank out pointers we've just stolen to avoid double free */
915
0
    memset(&info->u.luks, 0, sizeof(info->u.luks));
916
917
0
    qapi_free_QCryptoBlockInfo(info);
918
919
0
    return spec_info;
920
0
}
921
922
static int GRAPH_RDLOCK
923
block_crypto_amend_prepare(BlockDriverState *bs, Error **errp)
924
0
{
925
0
    BlockCrypto *crypto = bs->opaque;
926
0
    int ret;
927
928
    /* apply for exclusive read/write permissions to the underlying file */
929
0
    crypto->updating_keys = true;
930
0
    ret = bdrv_child_refresh_perms(bs, bs->file, errp);
931
0
    if (ret < 0) {
932
        /* Well, in this case we will not be updating any keys */
933
0
        crypto->updating_keys = false;
934
0
    }
935
0
    return ret;
936
0
}
937
938
static void GRAPH_RDLOCK
939
block_crypto_amend_cleanup(BlockDriverState *bs)
940
0
{
941
0
    BlockCrypto *crypto = bs->opaque;
942
0
    Error *err = NULL;
943
944
    /* release exclusive read/write permissions to the underlying file */
945
0
    crypto->updating_keys = false;
946
0
    bdrv_child_refresh_perms(bs, bs->file, &err);
947
948
0
    if (err) {
949
0
        error_report_err(err);
950
0
    }
951
0
}
952
953
static int
954
block_crypto_amend_options_generic_luks(BlockDriverState *bs,
955
                                        QCryptoBlockAmendOptions *amend_options,
956
                                        bool force,
957
                                        Error **errp)
958
0
{
959
0
    BlockCrypto *crypto = bs->opaque;
960
961
0
    assert(crypto);
962
0
    assert(crypto->block);
963
964
0
    return qcrypto_block_amend_options(crypto->block,
965
0
                                       block_crypto_read_func,
966
0
                                       block_crypto_write_func,
967
0
                                       bs,
968
0
                                       amend_options,
969
0
                                       force,
970
0
                                       errp);
971
0
}
972
973
static int GRAPH_RDLOCK
974
block_crypto_amend_options_luks(BlockDriverState *bs,
975
                                QemuOpts *opts,
976
                                BlockDriverAmendStatusCB *status_cb,
977
                                void *cb_opaque,
978
                                bool force,
979
                                Error **errp)
980
0
{
981
0
    BlockCrypto *crypto = bs->opaque;
982
0
    QDict *cryptoopts = NULL;
983
0
    QCryptoBlockAmendOptions *amend_options = NULL;
984
0
    int ret = -EINVAL;
985
986
0
    assert(crypto);
987
0
    assert(crypto->block);
988
989
0
    cryptoopts = qemu_opts_to_qdict(opts, NULL);
990
0
    qdict_put_str(cryptoopts, "format", "luks");
991
0
    amend_options = block_crypto_amend_opts_init(cryptoopts, errp);
992
0
    qobject_unref(cryptoopts);
993
0
    if (!amend_options) {
994
0
        goto cleanup;
995
0
    }
996
997
0
    ret = block_crypto_amend_prepare(bs, errp);
998
0
    if (ret) {
999
0
        goto perm_cleanup;
1000
0
    }
1001
0
    ret = block_crypto_amend_options_generic_luks(bs, amend_options,
1002
0
                                                  force, errp);
1003
1004
0
perm_cleanup:
1005
0
    block_crypto_amend_cleanup(bs);
1006
0
cleanup:
1007
0
    qapi_free_QCryptoBlockAmendOptions(amend_options);
1008
0
    return ret;
1009
0
}
1010
1011
static int
1012
coroutine_fn block_crypto_co_amend_luks(BlockDriverState *bs,
1013
                                        BlockdevAmendOptions *opts,
1014
                                        bool force,
1015
                                        Error **errp)
1016
0
{
1017
0
    QCryptoBlockAmendOptions amend_opts;
1018
1019
0
    amend_opts = (QCryptoBlockAmendOptions) {
1020
0
        .format = QCRYPTO_BLOCK_FORMAT_LUKS,
1021
0
        .u.luks = *qapi_BlockdevAmendOptionsLUKS_base(&opts->u.luks),
1022
0
    };
1023
0
    return block_crypto_amend_options_generic_luks(bs, &amend_opts,
1024
0
                                                   force, errp);
1025
0
}
1026
1027
static void
1028
block_crypto_child_perms(BlockDriverState *bs, BdrvChild *c,
1029
                         const BdrvChildRole role,
1030
                         BlockReopenQueue *reopen_queue,
1031
                         uint64_t perm, uint64_t shared,
1032
                         uint64_t *nperm, uint64_t *nshared)
1033
0
{
1034
1035
0
    BlockCrypto *crypto = bs->opaque;
1036
1037
0
    bdrv_default_perms(bs, c, role, reopen_queue, perm, shared, nperm, nshared);
1038
1039
    /*
1040
     * For backward compatibility, manually share the write
1041
     * and resize permission
1042
     */
1043
0
    *nshared |= shared & (BLK_PERM_WRITE | BLK_PERM_RESIZE);
1044
    /*
1045
     * Since we are not fully a format driver, don't always request
1046
     * the read/resize permission but only when explicitly
1047
     * requested
1048
     */
1049
0
    *nperm &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
1050
0
    *nperm |= perm & (BLK_PERM_WRITE | BLK_PERM_RESIZE);
1051
1052
    /*
1053
     * This driver doesn't modify LUKS metadata except
1054
     * when updating the encryption slots.
1055
     * Thus unlike a proper format driver we don't ask for
1056
     * shared write/read permission. However we need it
1057
     * when we are updating the keys, to ensure that only we
1058
     * have access to the device.
1059
     *
1060
     * Encryption update will set the crypto->updating_keys
1061
     * during that period and refresh permissions
1062
     *
1063
     */
1064
0
    if (crypto->updating_keys) {
1065
        /* need exclusive write access for header update */
1066
0
        *nperm |= BLK_PERM_WRITE;
1067
        /* unshare read and write permission */
1068
0
        *nshared &= ~(BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE);
1069
0
    }
1070
0
}
1071
1072
1073
static const char *const block_crypto_strong_runtime_opts[] = {
1074
    BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET,
1075
1076
    NULL
1077
};
1078
1079
static BlockDriver bdrv_crypto_luks = {
1080
    .format_name        = "luks",
1081
    .instance_size      = sizeof(BlockCrypto),
1082
    .bdrv_probe         = block_crypto_probe_luks,
1083
    .bdrv_open          = block_crypto_open_luks,
1084
    .bdrv_close         = block_crypto_close,
1085
    .bdrv_child_perm    = block_crypto_child_perms,
1086
    .bdrv_co_create     = block_crypto_co_create_luks,
1087
    .bdrv_co_create_opts = block_crypto_co_create_opts_luks,
1088
    .bdrv_co_truncate   = block_crypto_co_truncate,
1089
    .create_opts        = &block_crypto_create_opts_luks,
1090
    .amend_opts         = &block_crypto_amend_opts_luks,
1091
1092
    .bdrv_reopen_prepare = block_crypto_reopen_prepare,
1093
    .bdrv_refresh_limits = block_crypto_refresh_limits,
1094
    .bdrv_co_preadv     = block_crypto_co_preadv,
1095
    .bdrv_co_pwritev    = block_crypto_co_pwritev,
1096
    .bdrv_co_getlength  = block_crypto_co_getlength,
1097
    .bdrv_measure       = block_crypto_measure,
1098
    .bdrv_co_get_info   = block_crypto_co_get_info_luks,
1099
    .bdrv_get_specific_info = block_crypto_get_specific_info_luks,
1100
    .bdrv_amend_options = block_crypto_amend_options_luks,
1101
    .bdrv_co_amend      = block_crypto_co_amend_luks,
1102
    .bdrv_amend_pre_run = block_crypto_amend_prepare,
1103
    .bdrv_amend_clean   = block_crypto_amend_cleanup,
1104
1105
    .is_format          = true,
1106
1107
    .strong_runtime_opts = block_crypto_strong_runtime_opts,
1108
};
1109
1110
static void block_crypto_init(void)
1111
63
{
1112
63
    bdrv_register(&bdrv_crypto_luks);
1113
63
}
1114
1115
block_init(block_crypto_init);