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