xref: /openbmc/qemu/block/crypto.c (revision dda2441b)
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 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 "sysemu/block-backend.h"
25 #include "crypto/block.h"
26 #include "qapi/opts-visitor.h"
27 #include "qapi/qapi-visit-crypto.h"
28 #include "qapi/qmp/qdict.h"
29 #include "qapi/qobject-input-visitor.h"
30 #include "qapi/error.h"
31 #include "qemu/option.h"
32 #include "block/crypto.h"
33 
34 typedef struct BlockCrypto BlockCrypto;
35 
36 struct BlockCrypto {
37     QCryptoBlock *block;
38 };
39 
40 
41 static int block_crypto_probe_generic(QCryptoBlockFormat format,
42                                       const uint8_t *buf,
43                                       int buf_size,
44                                       const char *filename)
45 {
46     if (qcrypto_block_has_format(format, buf, buf_size)) {
47         return 100;
48     } else {
49         return 0;
50     }
51 }
52 
53 
54 static ssize_t block_crypto_read_func(QCryptoBlock *block,
55                                       size_t offset,
56                                       uint8_t *buf,
57                                       size_t buflen,
58                                       void *opaque,
59                                       Error **errp)
60 {
61     BlockDriverState *bs = opaque;
62     ssize_t ret;
63 
64     ret = bdrv_pread(bs->file, offset, buf, buflen);
65     if (ret < 0) {
66         error_setg_errno(errp, -ret, "Could not read encryption header");
67         return ret;
68     }
69     return ret;
70 }
71 
72 
73 struct BlockCryptoCreateData {
74     BlockBackend *blk;
75     uint64_t size;
76 };
77 
78 
79 static ssize_t block_crypto_write_func(QCryptoBlock *block,
80                                        size_t offset,
81                                        const uint8_t *buf,
82                                        size_t buflen,
83                                        void *opaque,
84                                        Error **errp)
85 {
86     struct BlockCryptoCreateData *data = opaque;
87     ssize_t ret;
88 
89     ret = blk_pwrite(data->blk, offset, buf, buflen, 0);
90     if (ret < 0) {
91         error_setg_errno(errp, -ret, "Could not write encryption header");
92         return ret;
93     }
94     return ret;
95 }
96 
97 
98 static ssize_t block_crypto_init_func(QCryptoBlock *block,
99                                       size_t headerlen,
100                                       void *opaque,
101                                       Error **errp)
102 {
103     struct BlockCryptoCreateData *data = opaque;
104 
105     if (data->size > INT64_MAX || headerlen > INT64_MAX - data->size) {
106         error_setg(errp, "The requested file size is too large");
107         return -EFBIG;
108     }
109 
110     /* User provided size should reflect amount of space made
111      * available to the guest, so we must take account of that
112      * which will be used by the crypto header
113      */
114     return blk_truncate(data->blk, data->size + headerlen, PREALLOC_MODE_OFF,
115                         errp);
116 }
117 
118 
119 static QemuOptsList block_crypto_runtime_opts_luks = {
120     .name = "crypto",
121     .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head),
122     .desc = {
123         BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""),
124         { /* end of list */ }
125     },
126 };
127 
128 
129 static QemuOptsList block_crypto_create_opts_luks = {
130     .name = "crypto",
131     .head = QTAILQ_HEAD_INITIALIZER(block_crypto_create_opts_luks.head),
132     .desc = {
133         {
134             .name = BLOCK_OPT_SIZE,
135             .type = QEMU_OPT_SIZE,
136             .help = "Virtual disk size"
137         },
138         BLOCK_CRYPTO_OPT_DEF_LUKS_KEY_SECRET(""),
139         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG(""),
140         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE(""),
141         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG(""),
142         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG(""),
143         BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG(""),
144         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME(""),
145         { /* end of list */ }
146     },
147 };
148 
149 
150 QCryptoBlockOpenOptions *
151 block_crypto_open_opts_init(QCryptoBlockFormat format,
152                             QDict *opts,
153                             Error **errp)
154 {
155     Visitor *v;
156     QCryptoBlockOpenOptions *ret = NULL;
157     Error *local_err = NULL;
158 
159     ret = g_new0(QCryptoBlockOpenOptions, 1);
160     ret->format = format;
161 
162     v = qobject_input_visitor_new_keyval(QOBJECT(opts));
163 
164     visit_start_struct(v, NULL, NULL, 0, &local_err);
165     if (local_err) {
166         goto out;
167     }
168 
169     switch (format) {
170     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
171         visit_type_QCryptoBlockOptionsLUKS_members(
172             v, &ret->u.luks, &local_err);
173         break;
174 
175     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
176         visit_type_QCryptoBlockOptionsQCow_members(
177             v, &ret->u.qcow, &local_err);
178         break;
179 
180     default:
181         error_setg(&local_err, "Unsupported block format %d", format);
182         break;
183     }
184     if (!local_err) {
185         visit_check_struct(v, &local_err);
186     }
187 
188     visit_end_struct(v, NULL);
189 
190  out:
191     if (local_err) {
192         error_propagate(errp, local_err);
193         qapi_free_QCryptoBlockOpenOptions(ret);
194         ret = NULL;
195     }
196     visit_free(v);
197     return ret;
198 }
199 
200 
201 QCryptoBlockCreateOptions *
202 block_crypto_create_opts_init(QCryptoBlockFormat format,
203                               QDict *opts,
204                               Error **errp)
205 {
206     Visitor *v;
207     QCryptoBlockCreateOptions *ret = NULL;
208     Error *local_err = NULL;
209 
210     ret = g_new0(QCryptoBlockCreateOptions, 1);
211     ret->format = format;
212 
213     v = qobject_input_visitor_new_keyval(QOBJECT(opts));
214 
215     visit_start_struct(v, NULL, NULL, 0, &local_err);
216     if (local_err) {
217         goto out;
218     }
219 
220     switch (format) {
221     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
222         visit_type_QCryptoBlockCreateOptionsLUKS_members(
223             v, &ret->u.luks, &local_err);
224         break;
225 
226     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
227         visit_type_QCryptoBlockOptionsQCow_members(
228             v, &ret->u.qcow, &local_err);
229         break;
230 
231     default:
232         error_setg(&local_err, "Unsupported block format %d", format);
233         break;
234     }
235     if (!local_err) {
236         visit_check_struct(v, &local_err);
237     }
238 
239     visit_end_struct(v, NULL);
240 
241  out:
242     if (local_err) {
243         error_propagate(errp, local_err);
244         qapi_free_QCryptoBlockCreateOptions(ret);
245         ret = NULL;
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     Error *local_err = NULL;
262     int ret = -EINVAL;
263     QCryptoBlockOpenOptions *open_opts = NULL;
264     unsigned int cflags = 0;
265     QDict *cryptoopts = NULL;
266 
267     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
268                                false, errp);
269     if (!bs->file) {
270         return -EINVAL;
271     }
272 
273     bs->supported_write_flags = BDRV_REQ_FUA &
274         bs->file->bs->supported_write_flags;
275 
276     opts = qemu_opts_create(opts_spec, NULL, 0, &error_abort);
277     qemu_opts_absorb_qdict(opts, options, &local_err);
278     if (local_err) {
279         error_propagate(errp, local_err);
280         goto cleanup;
281     }
282 
283     cryptoopts = qemu_opts_to_qdict(opts, NULL);
284 
285     open_opts = block_crypto_open_opts_init(format, cryptoopts, errp);
286     if (!open_opts) {
287         goto cleanup;
288     }
289 
290     if (flags & BDRV_O_NO_IO) {
291         cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
292     }
293     crypto->block = qcrypto_block_open(open_opts, NULL,
294                                        block_crypto_read_func,
295                                        bs,
296                                        cflags,
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     QDECREF(cryptoopts);
309     qapi_free_QCryptoBlockOpenOptions(open_opts);
310     return ret;
311 }
312 
313 
314 static int block_crypto_co_create_generic(BlockDriverState *bs,
315                                           int64_t size,
316                                           QCryptoBlockCreateOptions *opts,
317                                           Error **errp)
318 {
319     int ret;
320     BlockBackend *blk;
321     QCryptoBlock *crypto = NULL;
322     struct BlockCryptoCreateData data;
323 
324     blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
325 
326     ret = blk_insert_bs(blk, bs, errp);
327     if (ret < 0) {
328         goto cleanup;
329     }
330 
331     data = (struct BlockCryptoCreateData) {
332         .blk = blk,
333         .size = size,
334     };
335 
336     crypto = qcrypto_block_create(opts, NULL,
337                                   block_crypto_init_func,
338                                   block_crypto_write_func,
339                                   &data,
340                                   errp);
341 
342     if (!crypto) {
343         ret = -EIO;
344         goto cleanup;
345     }
346 
347     ret = 0;
348  cleanup:
349     qcrypto_block_free(crypto);
350     blk_unref(blk);
351     return ret;
352 }
353 
354 static int block_crypto_truncate(BlockDriverState *bs, int64_t offset,
355                                  PreallocMode prealloc, Error **errp)
356 {
357     BlockCrypto *crypto = bs->opaque;
358     uint64_t payload_offset =
359         qcrypto_block_get_payload_offset(crypto->block);
360     assert(payload_offset < (INT64_MAX - offset));
361 
362     offset += payload_offset;
363 
364     return bdrv_truncate(bs->file, offset, prealloc, errp);
365 }
366 
367 static void block_crypto_close(BlockDriverState *bs)
368 {
369     BlockCrypto *crypto = bs->opaque;
370     qcrypto_block_free(crypto->block);
371 }
372 
373 static int block_crypto_reopen_prepare(BDRVReopenState *state,
374                                        BlockReopenQueue *queue, Error **errp)
375 {
376     /* nothing needs checking */
377     return 0;
378 }
379 
380 /*
381  * 1 MB bounce buffer gives good performance / memory tradeoff
382  * when using cache=none|directsync.
383  */
384 #define BLOCK_CRYPTO_MAX_IO_SIZE (1024 * 1024)
385 
386 static coroutine_fn int
387 block_crypto_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
388                        QEMUIOVector *qiov, int flags)
389 {
390     BlockCrypto *crypto = bs->opaque;
391     uint64_t cur_bytes; /* number of bytes in current iteration */
392     uint64_t bytes_done = 0;
393     uint8_t *cipher_data = NULL;
394     QEMUIOVector hd_qiov;
395     int ret = 0;
396     uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
397     uint64_t payload_offset = qcrypto_block_get_payload_offset(crypto->block);
398 
399     assert(!flags);
400     assert(payload_offset < INT64_MAX);
401     assert(QEMU_IS_ALIGNED(offset, sector_size));
402     assert(QEMU_IS_ALIGNED(bytes, sector_size));
403 
404     qemu_iovec_init(&hd_qiov, qiov->niov);
405 
406     /* Bounce buffer because we don't wish to expose cipher text
407      * in qiov which points to guest memory.
408      */
409     cipher_data =
410         qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_IO_SIZE,
411                                               qiov->size));
412     if (cipher_data == NULL) {
413         ret = -ENOMEM;
414         goto cleanup;
415     }
416 
417     while (bytes) {
418         cur_bytes = MIN(bytes, BLOCK_CRYPTO_MAX_IO_SIZE);
419 
420         qemu_iovec_reset(&hd_qiov);
421         qemu_iovec_add(&hd_qiov, cipher_data, cur_bytes);
422 
423         ret = bdrv_co_preadv(bs->file, payload_offset + offset + bytes_done,
424                              cur_bytes, &hd_qiov, 0);
425         if (ret < 0) {
426             goto cleanup;
427         }
428 
429         if (qcrypto_block_decrypt(crypto->block, offset + bytes_done,
430                                   cipher_data, cur_bytes, NULL) < 0) {
431             ret = -EIO;
432             goto cleanup;
433         }
434 
435         qemu_iovec_from_buf(qiov, bytes_done, cipher_data, cur_bytes);
436 
437         bytes -= cur_bytes;
438         bytes_done += cur_bytes;
439     }
440 
441  cleanup:
442     qemu_iovec_destroy(&hd_qiov);
443     qemu_vfree(cipher_data);
444 
445     return ret;
446 }
447 
448 
449 static coroutine_fn int
450 block_crypto_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
451                         QEMUIOVector *qiov, int flags)
452 {
453     BlockCrypto *crypto = bs->opaque;
454     uint64_t cur_bytes; /* number of bytes in current iteration */
455     uint64_t bytes_done = 0;
456     uint8_t *cipher_data = NULL;
457     QEMUIOVector hd_qiov;
458     int ret = 0;
459     uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
460     uint64_t payload_offset = qcrypto_block_get_payload_offset(crypto->block);
461 
462     assert(!(flags & ~BDRV_REQ_FUA));
463     assert(payload_offset < INT64_MAX);
464     assert(QEMU_IS_ALIGNED(offset, sector_size));
465     assert(QEMU_IS_ALIGNED(bytes, sector_size));
466 
467     qemu_iovec_init(&hd_qiov, qiov->niov);
468 
469     /* Bounce buffer because we're not permitted to touch
470      * contents of qiov - it points to guest memory.
471      */
472     cipher_data =
473         qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_IO_SIZE,
474                                               qiov->size));
475     if (cipher_data == NULL) {
476         ret = -ENOMEM;
477         goto cleanup;
478     }
479 
480     while (bytes) {
481         cur_bytes = MIN(bytes, BLOCK_CRYPTO_MAX_IO_SIZE);
482 
483         qemu_iovec_to_buf(qiov, bytes_done, cipher_data, cur_bytes);
484 
485         if (qcrypto_block_encrypt(crypto->block, offset + bytes_done,
486                                   cipher_data, cur_bytes, NULL) < 0) {
487             ret = -EIO;
488             goto cleanup;
489         }
490 
491         qemu_iovec_reset(&hd_qiov);
492         qemu_iovec_add(&hd_qiov, cipher_data, cur_bytes);
493 
494         ret = bdrv_co_pwritev(bs->file, payload_offset + offset + bytes_done,
495                               cur_bytes, &hd_qiov, flags);
496         if (ret < 0) {
497             goto cleanup;
498         }
499 
500         bytes -= cur_bytes;
501         bytes_done += cur_bytes;
502     }
503 
504  cleanup:
505     qemu_iovec_destroy(&hd_qiov);
506     qemu_vfree(cipher_data);
507 
508     return ret;
509 }
510 
511 static void block_crypto_refresh_limits(BlockDriverState *bs, Error **errp)
512 {
513     BlockCrypto *crypto = bs->opaque;
514     uint64_t sector_size = qcrypto_block_get_sector_size(crypto->block);
515     bs->bl.request_alignment = sector_size; /* No sub-sector I/O */
516 }
517 
518 
519 static int64_t block_crypto_getlength(BlockDriverState *bs)
520 {
521     BlockCrypto *crypto = bs->opaque;
522     int64_t len = bdrv_getlength(bs->file->bs);
523 
524     uint64_t offset = qcrypto_block_get_payload_offset(crypto->block);
525     assert(offset < INT64_MAX);
526 
527     if (offset > len) {
528         return -EIO;
529     }
530 
531     len -= offset;
532 
533     return len;
534 }
535 
536 
537 static int block_crypto_probe_luks(const uint8_t *buf,
538                                    int buf_size,
539                                    const char *filename) {
540     return block_crypto_probe_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
541                                       buf, buf_size, filename);
542 }
543 
544 static int block_crypto_open_luks(BlockDriverState *bs,
545                                   QDict *options,
546                                   int flags,
547                                   Error **errp)
548 {
549     return block_crypto_open_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
550                                      &block_crypto_runtime_opts_luks,
551                                      bs, options, flags, errp);
552 }
553 
554 static int coroutine_fn
555 block_crypto_co_create_luks(BlockdevCreateOptions *create_options, Error **errp)
556 {
557     BlockdevCreateOptionsLUKS *luks_opts;
558     BlockDriverState *bs = NULL;
559     QCryptoBlockCreateOptions create_opts;
560     int ret;
561 
562     assert(create_options->driver == BLOCKDEV_DRIVER_LUKS);
563     luks_opts = &create_options->u.luks;
564 
565     bs = bdrv_open_blockdev_ref(luks_opts->file, errp);
566     if (bs == NULL) {
567         return -EIO;
568     }
569 
570     create_opts = (QCryptoBlockCreateOptions) {
571         .format = Q_CRYPTO_BLOCK_FORMAT_LUKS,
572         .u.luks = *qapi_BlockdevCreateOptionsLUKS_base(luks_opts),
573     };
574 
575     ret = block_crypto_co_create_generic(bs, luks_opts->size, &create_opts,
576                                          errp);
577     if (ret < 0) {
578         goto fail;
579     }
580 
581     ret = 0;
582 fail:
583     bdrv_unref(bs);
584     return ret;
585 }
586 
587 static int coroutine_fn block_crypto_co_create_opts_luks(const char *filename,
588                                                          QemuOpts *opts,
589                                                          Error **errp)
590 {
591     QCryptoBlockCreateOptions *create_opts = NULL;
592     BlockDriverState *bs = NULL;
593     QDict *cryptoopts;
594     int64_t size;
595     int ret;
596 
597     /* Parse options */
598     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
599 
600     cryptoopts = qemu_opts_to_qdict_filtered(opts, NULL,
601                                              &block_crypto_create_opts_luks,
602                                              true);
603 
604     create_opts = block_crypto_create_opts_init(Q_CRYPTO_BLOCK_FORMAT_LUKS,
605                                                 cryptoopts, errp);
606     if (!create_opts) {
607         ret = -EINVAL;
608         goto fail;
609     }
610 
611     /* Create protocol layer */
612     ret = bdrv_create_file(filename, opts, errp);
613     if (ret < 0) {
614         return ret;
615     }
616 
617     bs = bdrv_open(filename, NULL, NULL,
618                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
619     if (!bs) {
620         ret = -EINVAL;
621         goto fail;
622     }
623 
624     /* Create format layer */
625     ret = block_crypto_co_create_generic(bs, size, create_opts, errp);
626     if (ret < 0) {
627         goto fail;
628     }
629 
630     ret = 0;
631 fail:
632     bdrv_unref(bs);
633     qapi_free_QCryptoBlockCreateOptions(create_opts);
634     QDECREF(cryptoopts);
635     return ret;
636 }
637 
638 static int block_crypto_get_info_luks(BlockDriverState *bs,
639                                       BlockDriverInfo *bdi)
640 {
641     BlockDriverInfo subbdi;
642     int ret;
643 
644     ret = bdrv_get_info(bs->file->bs, &subbdi);
645     if (ret != 0) {
646         return ret;
647     }
648 
649     bdi->unallocated_blocks_are_zero = false;
650     bdi->cluster_size = subbdi.cluster_size;
651 
652     return 0;
653 }
654 
655 static ImageInfoSpecific *
656 block_crypto_get_specific_info_luks(BlockDriverState *bs)
657 {
658     BlockCrypto *crypto = bs->opaque;
659     ImageInfoSpecific *spec_info;
660     QCryptoBlockInfo *info;
661 
662     info = qcrypto_block_get_info(crypto->block, NULL);
663     if (!info) {
664         return NULL;
665     }
666     if (info->format != Q_CRYPTO_BLOCK_FORMAT_LUKS) {
667         qapi_free_QCryptoBlockInfo(info);
668         return NULL;
669     }
670 
671     spec_info = g_new(ImageInfoSpecific, 1);
672     spec_info->type = IMAGE_INFO_SPECIFIC_KIND_LUKS;
673     spec_info->u.luks.data = g_new(QCryptoBlockInfoLUKS, 1);
674     *spec_info->u.luks.data = info->u.luks;
675 
676     /* Blank out pointers we've just stolen to avoid double free */
677     memset(&info->u.luks, 0, sizeof(info->u.luks));
678 
679     qapi_free_QCryptoBlockInfo(info);
680 
681     return spec_info;
682 }
683 
684 BlockDriver bdrv_crypto_luks = {
685     .format_name        = "luks",
686     .instance_size      = sizeof(BlockCrypto),
687     .bdrv_probe         = block_crypto_probe_luks,
688     .bdrv_open          = block_crypto_open_luks,
689     .bdrv_close         = block_crypto_close,
690     .bdrv_child_perm    = bdrv_format_default_perms,
691     .bdrv_co_create     = block_crypto_co_create_luks,
692     .bdrv_co_create_opts = block_crypto_co_create_opts_luks,
693     .bdrv_truncate      = block_crypto_truncate,
694     .create_opts        = &block_crypto_create_opts_luks,
695 
696     .bdrv_reopen_prepare = block_crypto_reopen_prepare,
697     .bdrv_refresh_limits = block_crypto_refresh_limits,
698     .bdrv_co_preadv     = block_crypto_co_preadv,
699     .bdrv_co_pwritev    = block_crypto_co_pwritev,
700     .bdrv_getlength     = block_crypto_getlength,
701     .bdrv_get_info      = block_crypto_get_info_luks,
702     .bdrv_get_specific_info = block_crypto_get_specific_info_luks,
703 };
704 
705 static void block_crypto_init(void)
706 {
707     bdrv_register(&bdrv_crypto_luks);
708 }
709 
710 block_init(block_crypto_init);
711