xref: /openbmc/qemu/block/crypto.c (revision 795c40b8)
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-visit.h"
28 #include "qapi/error.h"
29 
30 #define BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET "key-secret"
31 #define BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG "cipher-alg"
32 #define BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE "cipher-mode"
33 #define BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG "ivgen-alg"
34 #define BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG "ivgen-hash-alg"
35 #define BLOCK_CRYPTO_OPT_LUKS_HASH_ALG "hash-alg"
36 #define BLOCK_CRYPTO_OPT_LUKS_ITER_TIME "iter-time"
37 
38 typedef struct BlockCrypto BlockCrypto;
39 
40 struct BlockCrypto {
41     QCryptoBlock *block;
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 ssize_t 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, buf, buflen);
69     if (ret < 0) {
70         error_setg_errno(errp, -ret, "Could not read encryption header");
71         return ret;
72     }
73     return ret;
74 }
75 
76 
77 struct BlockCryptoCreateData {
78     const char *filename;
79     QemuOpts *opts;
80     BlockBackend *blk;
81     uint64_t size;
82 };
83 
84 
85 static ssize_t block_crypto_write_func(QCryptoBlock *block,
86                                        size_t offset,
87                                        const uint8_t *buf,
88                                        size_t buflen,
89                                        void *opaque,
90                                        Error **errp)
91 {
92     struct BlockCryptoCreateData *data = opaque;
93     ssize_t ret;
94 
95     ret = blk_pwrite(data->blk, offset, buf, buflen, 0);
96     if (ret < 0) {
97         error_setg_errno(errp, -ret, "Could not write encryption header");
98         return ret;
99     }
100     return ret;
101 }
102 
103 
104 static ssize_t block_crypto_init_func(QCryptoBlock *block,
105                                       size_t headerlen,
106                                       void *opaque,
107                                       Error **errp)
108 {
109     struct BlockCryptoCreateData *data = opaque;
110     int ret;
111 
112     /* User provided size should reflect amount of space made
113      * available to the guest, so we must take account of that
114      * which will be used by the crypto header
115      */
116     data->size += headerlen;
117 
118     qemu_opt_set_number(data->opts, BLOCK_OPT_SIZE, data->size, &error_abort);
119     ret = bdrv_create_file(data->filename, data->opts, errp);
120     if (ret < 0) {
121         return -1;
122     }
123 
124     data->blk = blk_new_open(data->filename, NULL, NULL,
125                              BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);
126     if (!data->blk) {
127         return -1;
128     }
129 
130     return 0;
131 }
132 
133 
134 static QemuOptsList block_crypto_runtime_opts_luks = {
135     .name = "crypto",
136     .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head),
137     .desc = {
138         {
139             .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET,
140             .type = QEMU_OPT_STRING,
141             .help = "ID of the secret that provides the encryption key",
142         },
143         { /* end of list */ }
144     },
145 };
146 
147 
148 static QemuOptsList block_crypto_create_opts_luks = {
149     .name = "crypto",
150     .head = QTAILQ_HEAD_INITIALIZER(block_crypto_create_opts_luks.head),
151     .desc = {
152         {
153             .name = BLOCK_OPT_SIZE,
154             .type = QEMU_OPT_SIZE,
155             .help = "Virtual disk size"
156         },
157         {
158             .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET,
159             .type = QEMU_OPT_STRING,
160             .help = "ID of the secret that provides the encryption key",
161         },
162         {
163             .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG,
164             .type = QEMU_OPT_STRING,
165             .help = "Name of encryption cipher algorithm",
166         },
167         {
168             .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE,
169             .type = QEMU_OPT_STRING,
170             .help = "Name of encryption cipher mode",
171         },
172         {
173             .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG,
174             .type = QEMU_OPT_STRING,
175             .help = "Name of IV generator algorithm",
176         },
177         {
178             .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG,
179             .type = QEMU_OPT_STRING,
180             .help = "Name of IV generator hash algorithm",
181         },
182         {
183             .name = BLOCK_CRYPTO_OPT_LUKS_HASH_ALG,
184             .type = QEMU_OPT_STRING,
185             .help = "Name of encryption hash algorithm",
186         },
187         {
188             .name = BLOCK_CRYPTO_OPT_LUKS_ITER_TIME,
189             .type = QEMU_OPT_NUMBER,
190             .help = "Time to spend in PBKDF in milliseconds",
191         },
192         { /* end of list */ }
193     },
194 };
195 
196 
197 static QCryptoBlockOpenOptions *
198 block_crypto_open_opts_init(QCryptoBlockFormat format,
199                             QemuOpts *opts,
200                             Error **errp)
201 {
202     Visitor *v;
203     QCryptoBlockOpenOptions *ret = NULL;
204     Error *local_err = NULL;
205 
206     ret = g_new0(QCryptoBlockOpenOptions, 1);
207     ret->format = format;
208 
209     v = opts_visitor_new(opts);
210 
211     visit_start_struct(v, NULL, NULL, 0, &local_err);
212     if (local_err) {
213         goto out;
214     }
215 
216     switch (format) {
217     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
218         visit_type_QCryptoBlockOptionsLUKS_members(
219             v, &ret->u.luks, &local_err);
220         break;
221 
222     default:
223         error_setg(&local_err, "Unsupported block format %d", format);
224         break;
225     }
226     if (!local_err) {
227         visit_check_struct(v, &local_err);
228     }
229 
230     visit_end_struct(v, NULL);
231 
232  out:
233     if (local_err) {
234         error_propagate(errp, local_err);
235         qapi_free_QCryptoBlockOpenOptions(ret);
236         ret = NULL;
237     }
238     visit_free(v);
239     return ret;
240 }
241 
242 
243 static QCryptoBlockCreateOptions *
244 block_crypto_create_opts_init(QCryptoBlockFormat format,
245                               QemuOpts *opts,
246                               Error **errp)
247 {
248     Visitor *v;
249     QCryptoBlockCreateOptions *ret = NULL;
250     Error *local_err = NULL;
251 
252     ret = g_new0(QCryptoBlockCreateOptions, 1);
253     ret->format = format;
254 
255     v = opts_visitor_new(opts);
256 
257     visit_start_struct(v, NULL, NULL, 0, &local_err);
258     if (local_err) {
259         goto out;
260     }
261 
262     switch (format) {
263     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
264         visit_type_QCryptoBlockCreateOptionsLUKS_members(
265             v, &ret->u.luks, &local_err);
266         break;
267 
268     default:
269         error_setg(&local_err, "Unsupported block format %d", format);
270         break;
271     }
272     if (!local_err) {
273         visit_check_struct(v, &local_err);
274     }
275 
276     visit_end_struct(v, NULL);
277 
278  out:
279     if (local_err) {
280         error_propagate(errp, local_err);
281         qapi_free_QCryptoBlockCreateOptions(ret);
282         ret = NULL;
283     }
284     visit_free(v);
285     return ret;
286 }
287 
288 
289 static int block_crypto_open_generic(QCryptoBlockFormat format,
290                                      QemuOptsList *opts_spec,
291                                      BlockDriverState *bs,
292                                      QDict *options,
293                                      int flags,
294                                      Error **errp)
295 {
296     BlockCrypto *crypto = bs->opaque;
297     QemuOpts *opts = NULL;
298     Error *local_err = NULL;
299     int ret = -EINVAL;
300     QCryptoBlockOpenOptions *open_opts = NULL;
301     unsigned int cflags = 0;
302 
303     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
304                                false, errp);
305     if (!bs->file) {
306         return -EINVAL;
307     }
308 
309     opts = qemu_opts_create(opts_spec, NULL, 0, &error_abort);
310     qemu_opts_absorb_qdict(opts, options, &local_err);
311     if (local_err) {
312         error_propagate(errp, local_err);
313         goto cleanup;
314     }
315 
316     open_opts = block_crypto_open_opts_init(format, opts, errp);
317     if (!open_opts) {
318         goto cleanup;
319     }
320 
321     if (flags & BDRV_O_NO_IO) {
322         cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
323     }
324     crypto->block = qcrypto_block_open(open_opts,
325                                        block_crypto_read_func,
326                                        bs,
327                                        cflags,
328                                        errp);
329 
330     if (!crypto->block) {
331         ret = -EIO;
332         goto cleanup;
333     }
334 
335     bs->encrypted = true;
336     bs->valid_key = true;
337 
338     ret = 0;
339  cleanup:
340     qapi_free_QCryptoBlockOpenOptions(open_opts);
341     return ret;
342 }
343 
344 
345 static int block_crypto_create_generic(QCryptoBlockFormat format,
346                                        const char *filename,
347                                        QemuOpts *opts,
348                                        Error **errp)
349 {
350     int ret = -EINVAL;
351     QCryptoBlockCreateOptions *create_opts = NULL;
352     QCryptoBlock *crypto = NULL;
353     struct BlockCryptoCreateData data = {
354         .size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
355                          BDRV_SECTOR_SIZE),
356         .opts = opts,
357         .filename = filename,
358     };
359 
360     create_opts = block_crypto_create_opts_init(format, opts, errp);
361     if (!create_opts) {
362         return -1;
363     }
364 
365     crypto = qcrypto_block_create(create_opts,
366                                   block_crypto_init_func,
367                                   block_crypto_write_func,
368                                   &data,
369                                   errp);
370 
371     if (!crypto) {
372         ret = -EIO;
373         goto cleanup;
374     }
375 
376     ret = 0;
377  cleanup:
378     qcrypto_block_free(crypto);
379     blk_unref(data.blk);
380     qapi_free_QCryptoBlockCreateOptions(create_opts);
381     return ret;
382 }
383 
384 static int block_crypto_truncate(BlockDriverState *bs, int64_t offset,
385                                  Error **errp)
386 {
387     BlockCrypto *crypto = bs->opaque;
388     size_t payload_offset =
389         qcrypto_block_get_payload_offset(crypto->block);
390 
391     offset += payload_offset;
392 
393     return bdrv_truncate(bs->file, offset, errp);
394 }
395 
396 static void block_crypto_close(BlockDriverState *bs)
397 {
398     BlockCrypto *crypto = bs->opaque;
399     qcrypto_block_free(crypto->block);
400 }
401 
402 
403 #define BLOCK_CRYPTO_MAX_SECTORS 32
404 
405 static coroutine_fn int
406 block_crypto_co_readv(BlockDriverState *bs, int64_t sector_num,
407                       int remaining_sectors, QEMUIOVector *qiov)
408 {
409     BlockCrypto *crypto = bs->opaque;
410     int cur_nr_sectors; /* number of sectors in current iteration */
411     uint64_t bytes_done = 0;
412     uint8_t *cipher_data = NULL;
413     QEMUIOVector hd_qiov;
414     int ret = 0;
415     size_t payload_offset =
416         qcrypto_block_get_payload_offset(crypto->block) / 512;
417 
418     qemu_iovec_init(&hd_qiov, qiov->niov);
419 
420     /* Bounce buffer so we have a linear mem region for
421      * entire sector. XXX optimize so we avoid bounce
422      * buffer in case that qiov->niov == 1
423      */
424     cipher_data =
425         qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_SECTORS * 512,
426                                               qiov->size));
427     if (cipher_data == NULL) {
428         ret = -ENOMEM;
429         goto cleanup;
430     }
431 
432     while (remaining_sectors) {
433         cur_nr_sectors = remaining_sectors;
434 
435         if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
436             cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
437         }
438 
439         qemu_iovec_reset(&hd_qiov);
440         qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
441 
442         ret = bdrv_co_readv(bs->file,
443                             payload_offset + sector_num,
444                             cur_nr_sectors, &hd_qiov);
445         if (ret < 0) {
446             goto cleanup;
447         }
448 
449         if (qcrypto_block_decrypt(crypto->block,
450                                   sector_num,
451                                   cipher_data, cur_nr_sectors * 512,
452                                   NULL) < 0) {
453             ret = -EIO;
454             goto cleanup;
455         }
456 
457         qemu_iovec_from_buf(qiov, bytes_done,
458                             cipher_data, cur_nr_sectors * 512);
459 
460         remaining_sectors -= cur_nr_sectors;
461         sector_num += cur_nr_sectors;
462         bytes_done += cur_nr_sectors * 512;
463     }
464 
465  cleanup:
466     qemu_iovec_destroy(&hd_qiov);
467     qemu_vfree(cipher_data);
468 
469     return ret;
470 }
471 
472 
473 static coroutine_fn int
474 block_crypto_co_writev(BlockDriverState *bs, int64_t sector_num,
475                        int remaining_sectors, QEMUIOVector *qiov)
476 {
477     BlockCrypto *crypto = bs->opaque;
478     int cur_nr_sectors; /* number of sectors in current iteration */
479     uint64_t bytes_done = 0;
480     uint8_t *cipher_data = NULL;
481     QEMUIOVector hd_qiov;
482     int ret = 0;
483     size_t payload_offset =
484         qcrypto_block_get_payload_offset(crypto->block) / 512;
485 
486     qemu_iovec_init(&hd_qiov, qiov->niov);
487 
488     /* Bounce buffer so we have a linear mem region for
489      * entire sector. XXX optimize so we avoid bounce
490      * buffer in case that qiov->niov == 1
491      */
492     cipher_data =
493         qemu_try_blockalign(bs->file->bs, MIN(BLOCK_CRYPTO_MAX_SECTORS * 512,
494                                               qiov->size));
495     if (cipher_data == NULL) {
496         ret = -ENOMEM;
497         goto cleanup;
498     }
499 
500     while (remaining_sectors) {
501         cur_nr_sectors = remaining_sectors;
502 
503         if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
504             cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
505         }
506 
507         qemu_iovec_to_buf(qiov, bytes_done,
508                           cipher_data, cur_nr_sectors * 512);
509 
510         if (qcrypto_block_encrypt(crypto->block,
511                                   sector_num,
512                                   cipher_data, cur_nr_sectors * 512,
513                                   NULL) < 0) {
514             ret = -EIO;
515             goto cleanup;
516         }
517 
518         qemu_iovec_reset(&hd_qiov);
519         qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
520 
521         ret = bdrv_co_writev(bs->file,
522                              payload_offset + sector_num,
523                              cur_nr_sectors, &hd_qiov);
524         if (ret < 0) {
525             goto cleanup;
526         }
527 
528         remaining_sectors -= cur_nr_sectors;
529         sector_num += cur_nr_sectors;
530         bytes_done += cur_nr_sectors * 512;
531     }
532 
533  cleanup:
534     qemu_iovec_destroy(&hd_qiov);
535     qemu_vfree(cipher_data);
536 
537     return ret;
538 }
539 
540 
541 static int64_t block_crypto_getlength(BlockDriverState *bs)
542 {
543     BlockCrypto *crypto = bs->opaque;
544     int64_t len = bdrv_getlength(bs->file->bs);
545 
546     ssize_t offset = qcrypto_block_get_payload_offset(crypto->block);
547 
548     len -= offset;
549 
550     return len;
551 }
552 
553 
554 static int block_crypto_probe_luks(const uint8_t *buf,
555                                    int buf_size,
556                                    const char *filename) {
557     return block_crypto_probe_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
558                                       buf, buf_size, filename);
559 }
560 
561 static int block_crypto_open_luks(BlockDriverState *bs,
562                                   QDict *options,
563                                   int flags,
564                                   Error **errp)
565 {
566     return block_crypto_open_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
567                                      &block_crypto_runtime_opts_luks,
568                                      bs, options, flags, errp);
569 }
570 
571 static int block_crypto_create_luks(const char *filename,
572                                     QemuOpts *opts,
573                                     Error **errp)
574 {
575     return block_crypto_create_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
576                                        filename, opts, errp);
577 }
578 
579 static int block_crypto_get_info_luks(BlockDriverState *bs,
580                                       BlockDriverInfo *bdi)
581 {
582     BlockDriverInfo subbdi;
583     int ret;
584 
585     ret = bdrv_get_info(bs->file->bs, &subbdi);
586     if (ret != 0) {
587         return ret;
588     }
589 
590     bdi->unallocated_blocks_are_zero = false;
591     bdi->can_write_zeroes_with_unmap = false;
592     bdi->cluster_size = subbdi.cluster_size;
593 
594     return 0;
595 }
596 
597 static ImageInfoSpecific *
598 block_crypto_get_specific_info_luks(BlockDriverState *bs)
599 {
600     BlockCrypto *crypto = bs->opaque;
601     ImageInfoSpecific *spec_info;
602     QCryptoBlockInfo *info;
603 
604     info = qcrypto_block_get_info(crypto->block, NULL);
605     if (!info) {
606         return NULL;
607     }
608     if (info->format != Q_CRYPTO_BLOCK_FORMAT_LUKS) {
609         qapi_free_QCryptoBlockInfo(info);
610         return NULL;
611     }
612 
613     spec_info = g_new(ImageInfoSpecific, 1);
614     spec_info->type = IMAGE_INFO_SPECIFIC_KIND_LUKS;
615     spec_info->u.luks.data = g_new(QCryptoBlockInfoLUKS, 1);
616     *spec_info->u.luks.data = info->u.luks;
617 
618     /* Blank out pointers we've just stolen to avoid double free */
619     memset(&info->u.luks, 0, sizeof(info->u.luks));
620 
621     qapi_free_QCryptoBlockInfo(info);
622 
623     return spec_info;
624 }
625 
626 BlockDriver bdrv_crypto_luks = {
627     .format_name        = "luks",
628     .instance_size      = sizeof(BlockCrypto),
629     .bdrv_probe         = block_crypto_probe_luks,
630     .bdrv_open          = block_crypto_open_luks,
631     .bdrv_close         = block_crypto_close,
632     .bdrv_child_perm    = bdrv_format_default_perms,
633     .bdrv_create        = block_crypto_create_luks,
634     .bdrv_truncate      = block_crypto_truncate,
635     .create_opts        = &block_crypto_create_opts_luks,
636 
637     .bdrv_co_readv      = block_crypto_co_readv,
638     .bdrv_co_writev     = block_crypto_co_writev,
639     .bdrv_getlength     = block_crypto_getlength,
640     .bdrv_get_info      = block_crypto_get_info_luks,
641     .bdrv_get_specific_info = block_crypto_get_specific_info_luks,
642 };
643 
644 static void block_crypto_init(void)
645 {
646     bdrv_register(&bdrv_crypto_luks);
647 }
648 
649 block_init(block_crypto_init);
650