Skip to contentSkip to conversation

Add new LUKS block driver (for 2.6)

PATCH Superseded Daniel P. Berrange 3 participants 17 messages Mar 17, 2016 – Mar 23, 2016 Block layer

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#3 lore raw

PATCH v5 2/7 qemu-img/qemu-io: don't prompt for passwords if not required

In reply to Daniel P. Berrange

The qemu-img/qemu-io tools prompt for disk encryption passwords regardless of whether any are actually required. Adding a check on bdrv_key_required() avoids this prompt for disk formats which have been converted to the QCryptoSecret APIs.

This is just a temporary hack to ensure the block I/O tests continue to work after each patch, since the last patch will completely delete all the password prompting code.

---
 qemu-img.c | 3 ++-
 qemu-io.c  | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)
qemu-img.c +2 -1
index a03e501..21b45fd 100644
@@ -230,7 +230,8 @@ static int img_open_password(BlockBackend *blk, const char *filename,
     char password[256];
 
     bs = blk_bs(blk);
-    if (bdrv_is_encrypted(bs) && !(flags & BDRV_O_NO_IO)) {
+    if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&
+        !(flags & BDRV_O_NO_IO)) {
         qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
         if (qemu_read_password(password, sizeof(password)) < 0) {
             error_report("No password given");
qemu-io.c +1 -1
index 8c31257..d825723 100644
@@ -69,7 +69,7 @@ static int openfile(char *name, int flags, QDict *opts)
     }
 
     bs = blk_bs(qemuio_blk);
-    if (bdrv_is_encrypted(bs)) {
+    if (bdrv_is_encrypted(bs) && bdrv_key_required(bs)) {
         char password[256];
         printf("Disk image '%s' is encrypted.\n", name);
         if (qemu_read_password(password, sizeof(password)) < 0) {
Signature · 1 line
2.5.0
#0 lore raw

v5 cover Add new LUKS block driver (for 2.6)

This series is just the block layer parts needed to add a LUKS driver to QEMU. It was previously posted as part of the larger series

v1: https://lists.gnu.org/archive/html/qemu-devel/2015-11/msg04748.html
v2: https://lists.gnu.org/archive/html/qemu-block/2016-01/msg00534.html
v3: https://lists.gnu.org/archive/html/qemu-devel/2016-02/msg03176.html
v4: https://lists.gnu.org/archive/html/qemu-devel/2016-02/msg06552.html

The crypto subsystem pieces that this series depends on have been submitted for merge

https://lists.gnu.org/archive/html/qemu-devel/2016-03/msg04371.html

In this posting I am only proposing merge of the generic LUKS driver. This can be added as a layer above any of the existing drivers for accessing LUKS formatted volumes.

When creating new volumes, however, only the file backend can be used, since the block driver API doesn't allow for arbitrary stacking of protocols when creating images.

The integration with the qcow2 driver to replace the existing built-in AES-CBC code is dropped from this series, postponed until the 2.7 development cycle.

There is a QEMU I/O test 149 that exercises the LUKS driver and checks for compatibility with the dm-crypt/cryptsetup impl.

Daniel P. Berrange (7):
block: add flag to indicate that no I/O will be performed qemu-img/qemu-io: don't prompt for passwords if not required
tests: redirect stderr to stdout for iotests
tests: refactor python I/O tests helper main method
tests: add output filter to python I/O tests helper
block: add generic full disk encryption driver
block: drop support for using qcow[2] encryption with system emulators

 block.c                       |   17 +-
 block/Makefile.objs           |    2 +
 block/crypto.c                |  587 +++++++++++++
 block/io.c                    |    2 +
 block/qcow.c                  |   11 +
 block/qcow2.c                 |   11 +
 include/block/block.h         |    2 +
 qapi/block-core.json          |   22 +-
 qemu-img.c                    |   45 +-
 qemu-io.c                     |    2 +-
 tests/qemu-iotests/049.out    |    6 -
 tests/qemu-iotests/087.out    |   22 +-
 tests/qemu-iotests/134.out    |   18 -
 tests/qemu-iotests/149        |  521 ++++++++++++
 tests/qemu-iotests/149.out    | 1880 +++++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/common     |    7 +
 tests/qemu-iotests/group      |    1 +
 tests/qemu-iotests/iotests.py |   48 +-
 18 files changed, 3118 insertions(+), 86 deletions(-)
 create mode 100644 block/crypto.c
 create mode 100755 tests/qemu-iotests/149
 create mode 100644 tests/qemu-iotests/149.out
Signature · 1 line
2.5.0
#4 lore raw

PATCH v5 3/7 tests: redirect stderr to stdout for iotests

The python I/O tests helper for running qemu-img/qemu-io setup stdout to be captured to a pipe, but left stderr untouched. As a result, if something failed in qemu-img/ qemu-io, data written to stderr would get output directly and not line up with data on the test stdout due to buffering. If we explicitly redirect stderr to the same pipe as stdout, things are much clearer when they go wrong.

---
 tests/qemu-iotests/iotests.py | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
tests/qemu-iotests/iotests.py +5 -2
index 0a238ec..5f82bbe 100644
@@ -71,7 +71,9 @@ def qemu_img_verbose(*args):
 
 def qemu_img_pipe(*args):
     '''Run qemu-img and return its output'''
-    subp = subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE)
+    subp = subprocess.Popen(qemu_img_args + list(args),
+                            stdout=subprocess.PIPE,
+                            stderr=subprocess.STDOUT)
     exitcode = subp.wait()
     if exitcode < 0:
         sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
@@ -80,7 +82,8 @@ def qemu_img_pipe(*args):
 def qemu_io(*args):
     '''Run qemu-io and return the stdout data'''
     args = qemu_io_args + list(args)
-    subp = subprocess.Popen(args, stdout=subprocess.PIPE)
+    subp = subprocess.Popen(args, stdout=subprocess.PIPE,
+                            stderr=subprocess.STDOUT)
     exitcode = subp.wait()
     if exitcode < 0:
         sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
Signature · 1 line
2.5.0
#5 lore raw

PATCH v5 4/7 tests: refactor python I/O tests helper main method

In reply to Daniel P. Berrange

The iotests.py helper provides a main() method for running tests via the python unit test framework. Not all tests will want to use this, so refactor it to split the testing of compatible formats and platforms into separate helper methods

---
 tests/qemu-iotests/iotests.py | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
tests/qemu-iotests/iotests.py +12 -6
index 5f82bbe..51e53bb 100644
@@ -29,7 +29,8 @@ import qtest
 import struct
 
 __all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
-           'VM', 'QMPTestCase', 'notrun', 'main']
+           'VM', 'QMPTestCase', 'notrun', 'main', 'verify_image_format',
+           'verify_platform']
 
 # This will not work if arguments contain spaces but is necessary if we
 # want to support the override options that ./check supports.
@@ -394,17 +395,22 @@ def notrun(reason):
     print '%s not run: %s' % (seq, reason)
     sys.exit(0)
 
-def main(supported_fmts=[], supported_oses=['linux']):
-    '''Run tests'''
-
-    debug = '-d' in sys.argv
-    verbosity = 1
+def verify_image_format(supported_fmts=[]):
     if supported_fmts and (imgfmt not in supported_fmts):
         notrun('not suitable for this image format: %s' % imgfmt)
 
+def verify_platform(supported_oses=['linux']):
     if True not in [sys.platform.startswith(x) for x in supported_oses]:
         notrun('not suitable for this OS: %s' % sys.platform)
 
+def main(supported_fmts=[], supported_oses=['linux']):
+    '''Run tests'''
+
+    debug = '-d' in sys.argv
+    verbosity = 1
+    verify_image_format(supported_fmts)
+    verify_platform(supported_oses)
+
     # We need to filter out the time taken from the output so that qemu-iotest
     # can reliably diff the results against master output.
     import StringIO
Signature · 1 line
2.5.0
#1 lore raw

PATCH v5 1/7 block: add flag to indicate that no I/O will be performed

In reply to Daniel P. Berrange

When opening an image it is useful to know whether the caller intends to perform I/O on the image or not. In the case of encrypted images this will allow the block driver to avoid having to prompt for decryption keys when we merely want to query header metadata about the image. eg qemu-img info

This flag is enforced at the top level only, since even if we don't want todo I/O on the 'qcow2' file payload, the underlying 'file' driver will still need todo I/O to read the qcow2 header, for example.

---
 block.c               |  5 +++--
 block/io.c            |  2 ++
 include/block/block.h |  1 +
 qemu-img.c            | 44 ++++++++++++++++++++++----------------------
 4 files changed, 28 insertions(+), 24 deletions(-)
block.c +3 -2
index 59a18a3..4d1a9d3 100644
@@ -706,7 +706,8 @@ static void bdrv_inherited_options(int *child_flags, QDict *child_options,
     flags |= BDRV_O_UNMAP;
 
     /* Clear flags that only apply to the top layer */
-    flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
+    flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
+               BDRV_O_NO_IO);
 
     *child_flags = flags;
 }
@@ -726,7 +727,7 @@ static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
     child_file.inherit_options(child_flags, child_options,
                                parent_flags, parent_options);
 
-    *child_flags &= ~BDRV_O_PROTOCOL;
+    *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
 }
 
 const BdrvChildRole child_format = {
block/io.c +2 -0
index a69bfc4..010e25a 100644
@@ -862,6 +862,7 @@ static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
     assert(!qiov || bytes == qiov->size);
+    assert((bs->open_flags & BDRV_O_NO_IO) == 0);
 
     /* Handle Copy on Read and associated serialisation */
     if (flags & BDRV_REQ_COPY_ON_READ) {
@@ -1148,6 +1149,7 @@ static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
     assert(!qiov || bytes == qiov->size);
+    assert((bs->open_flags & BDRV_O_NO_IO) == 0);
 
     waited = wait_serialising_requests(req);
     assert(!waited || !req->serialising);
include/block/block.h +1 -0
index eaa6426..bb8e97d 100644
@@ -93,6 +93,7 @@ typedef struct HDGeometry {
 #define BDRV_O_PROTOCOL    0x8000  /* if no block driver is explicitly given:
                                       select an appropriate protocol driver,
                                       ignoring the format layer */
+#define BDRV_O_NO_IO       0x10000 /* don't initialize for I/O */
 
 #define BDRV_O_CACHE_MASK  (BDRV_O_NOCACHE | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH)
 
qemu-img.c +22 -22

163 lines not on this page · raw message

Signature · 1 line
2.5.0
#6 lore raw

PATCH v5 5/7 tests: add output filter to python I/O tests helper

In reply to Daniel P. Berrange

Add a 'log' method to iotests.py which prints messages to stdout, with optional filtering of data. Port over some standard filters already present in the shell common.filter code to be usable in python too.

---
 tests/qemu-iotests/iotests.py | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)
tests/qemu-iotests/iotests.py +24 -1
index 51e53bb..8499e1b 100644
@@ -30,7 +30,8 @@ import struct
 
 __all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
            'VM', 'QMPTestCase', 'notrun', 'main', 'verify_image_format',
-           'verify_platform']
+           'verify_platform', 'filter_test_dir', 'filter_win32',
+           'filter_qemu_io', 'filter_chown', 'log']
 
 # This will not work if arguments contain spaces but is necessary if we
 # want to support the override options that ./check supports.
@@ -105,6 +106,28 @@ def create_image(name, size):
         i = i + 512
     file.close()
 
+test_dir_re = re.compile(r"%s" % test_dir)
+def filter_test_dir(msg):
+    return test_dir_re.sub("TEST_DIR", msg)
+
+win32_re = re.compile(r"\r")
+def filter_win32(msg):
+    return win32_re.sub("", msg)
+
+qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
+def filter_qemu_io(msg):
+    msg = filter_win32(msg)
+    return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
+
+chown_re = re.compile(r"chown [0-9]+:[0-9]+")
+def filter_chown(msg):
+    return chown_re.sub("chown UID:GID", msg)
+
+def log(msg, filters=[]):
+    for flt in filters:
+        msg = flt(msg)
+    print msg
+
 # Test if 'match' is a recursive subset of 'event'
 def event_match(event, match=None):
     if match is None:
Signature · 1 line
2.5.0
#14 lore raw

PATCH v5 7/7 block: drop support for using qcow[2] encryption with system emulators

In reply to Daniel P. Berrange

For a couple of releases we have been warning

Encrypted images are deprecated
Support for them will be removed in a future release.
You can use 'qemu-img convert' to convert your image to an unencrypted one.

This warning was issued by system emulators, qemu-img, qemu-nbd and qemu-io. Such a broad warning was issued because the original intention was to rip out all the code for dealing with encryption inside the QEMU block layer APIs.

The new block encryption framework used for the LUKS driver does not rely on the unloved block layer API for encryption keys, instead using the QOM 'secret' object type. It is thus no longer appropriate to warn about encryption unconditionally.

When the qcow/qcow2 drivers are converted to use the new encryption framework too, it will be practical to keep AES-CBC support present for use in qemu-img, qemu-io & qemu-nbd to allow for interoperability with older QEMU versions and liberation of data from existing encrypted qcow2 files.

Thus this change, removes the deprecation warning, in its place adding a fatal error preventing use of qcow[2] built-in encryption inside the system emulators. Use of qcow[2] encryption in qemu-img, qemu-io, qemu-nbd no longer triggers any warning message, since that support is now expected to remain available long term, given the maint burden has been eliminated.

---
 block.c                    |  12 +-
 block/qcow.c               |  11 ++
 block/qcow2.c              |  11 ++
 include/block/block.h      |   1 +
 tests/qemu-iotests/049.out |   6 -
 tests/qemu-iotests/087.out |  22 +--
 tests/qemu-iotests/134.out |  18 ---
 tests/qemu-iotests/149.out | 372 ---------------------------------------------
 8 files changed, 30 insertions(+), 423 deletions(-)
block.c +5 -7
index 4d1a9d3..d105ae4 100644
@@ -293,6 +293,11 @@ static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
     return 0;
 }
 
+bool bdrv_uses_whitelist(void)
+{
+    return use_bdrv_whitelist;
+}
+
 typedef struct CreateCo {
     BlockDriver *drv;
     char *filename;
@@ -1009,13 +1014,6 @@ static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
         goto free_and_fail;
     }
 
-    if (bs->encrypted) {
-        error_report("Encrypted images are deprecated");
-        error_printf("Support for them will be removed in a future release.\n"
-                     "You can use 'qemu-img convert' to convert your image"
-                     " to an unencrypted one.\n");
-    }
-
     ret = refresh_total_sectors(bs, bs->total_sectors);
     if (ret < 0) {
         error_setg_errno(errp, -ret, "Could not refresh total sector count");
block/qcow.c +11 -0
index 2fd5ee6..cfa3781 100644
@@ -161,6 +161,17 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
+        if (s->crypt_method_header == QCOW_CRYPT_AES &&
+            bdrv_uses_whitelist()) {
+            error_setg(errp,
+                       "Use of AES-CBC encrypted qcow images is no longer "
+                       "supported in system emulators. You can use "
+                       "'qemu-img convert' to convert your image to use "
+                       "the LUKS format instead.");
+            ret = -ENOSYS;
+            goto fail;
+        }
+
         bs->encrypted = 1;
     }
     s->cluster_bits = header.cluster_bits;
block/qcow2.c +11 -0
index 1ce6264..ba8b818 100644
@@ -979,6 +979,17 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
+        if (s->crypt_method_header == QCOW_CRYPT_AES &&
+            bdrv_uses_whitelist()) {
+            error_setg(errp,
+                       "Use of AES-CBC encrypted qcow2 images is no longer "
+                       "supported in system emulators. You can use "
+                       "'qemu-img convert' to convert your image to use "
+                       "the LUKS format instead.");
+            ret = -ENOSYS;
+            goto fail;
+        }
+
         bs->encrypted = 1;
     }
 
include/block/block.h +1 -0
index bb8e97d..2920a1d 100644
@@ -193,6 +193,7 @@ void bdrv_io_limits_update_group(BlockDriverState *bs, const char *group);
 
 void bdrv_init(void);
 void bdrv_init_with_whitelist(void);
+bool bdrv_uses_whitelist(void);
 BlockDriver *bdrv_find_protocol(const char *filename,
                                 bool allow_protocol_prefix,
                                 Error **errp);
tests/qemu-iotests/049.out +0 -6
index a2b6703..4673b67 100644
@@ -187,12 +187,6 @@ qemu-img create -f qcow2 -o encryption=off TEST_DIR/t.qcow2 64M
 Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_size=65536 lazy_refcounts=off refcount_bits=16
 
 qemu-img create -f qcow2 -o encryption=on TEST_DIR/t.qcow2 64M
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16
 
 == Check lazy_refcounts option (only with v3) ==
tests/qemu-iotests/087.out +2 -20
index 7d62cd5..f47d8d9 100644
@@ -38,42 +38,24 @@ QMP_VERSION
 
 === Encrypted image ===
 
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on
 Testing: -S
 QMP_VERSION
 {"return": {}}
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-{"error": {"class": "GenericError", "desc": "blockdev-add doesn't support encrypted devices"}}
+{"error": {"class": "GenericError", "desc": "Use of AES-CBC encrypted qcow2 images is no longer supported in system emulators. You can use 'qemu-img convert' to convert your image to use the LUKS format instead."}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
 Testing:
 QMP_VERSION
 {"return": {}}
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-{"error": {"class": "GenericError", "desc": "Guest must be stopped for opening of encrypted image"}}
+{"error": {"class": "GenericError", "desc": "Use of AES-CBC encrypted qcow2 images is no longer supported in system emulators. You can use 'qemu-img convert' to convert your image to use the LUKS format instead."}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
 
 === Missing driver ===
 
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on
 Testing: -S
 QMP_VERSION
tests/qemu-iotests/134.out +0 -18
index a16acb8..6493704 100644
@@ -1,43 +1,25 @@
 QA output created by 134
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
-qemu-img: Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on
 
 == reading whole image ==
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Disk image 'TEST_DIR/t.qcow2' is encrypted.
 password:
 read 134217728/134217728 bytes at offset 0
 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == rewriting whole image ==
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Disk image 'TEST_DIR/t.qcow2' is encrypted.
 password:
 wrote 134217728/134217728 bytes at offset 0
 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == verify pattern ==
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Disk image 'TEST_DIR/t.qcow2' is encrypted.
 password:
 read 134217728/134217728 bytes at offset 0
 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
 == verify pattern failure with wrong password ==
-Encrypted images are deprecated
-Support for them will be removed in a future release.
-You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Disk image 'TEST_DIR/t.qcow2' is encrypted.
 password:
 Pattern verification failed at offset 0, 134217728 bytes
tests/qemu-iotests/149.out +0 -372

1,023 lines not on this page · raw message

Signature · 1 line
2.5.0
#7 lore raw

PATCH v5 6/7 block: add generic full disk encryption driver

In reply to Daniel P. Berrange

Add a block driver that is capable of supporting any full disk encryption format. This utilizes the previously added block encryption code, and at this time supports the LUKS format.

The driver code is capable of supporting any format supported by the QCryptoBlock module, so it registers one block driver for each format. This patch only registers the "luks" driver since the "qcow" driver is there only for back-compatibility with existing qcow built-in encryption.

New LUKS compatible volumes can be formatted using qemu-img with defaults for all settings.

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0 demo.luks 10G

Alternatively the cryptographic settings can be explicitly set

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0,cipher-alg=aes-256,\
                 cipher-mode=cbc,ivgen-alg=plain64,hash-alg=sha256 \
      demo.luks 10G

And query its size

$ qemu-img info demo.img
image: demo.img
file format: luks
virtual size: 10G (10737418240 bytes)
disk size: 132K
encrypted: yes

Note that it was not necessary to provide the password when querying info for the volume. The password is only required when performing I/O on the volume

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver.

The only algorithms listed in the LUKS spec that are not currently supported by this impl are sha512 and ripemd160 hashes and cast6 cipher.

A new I/O test is added which is used to validate the interoperability of the QEMU implementation of LUKS, with the dm-crypt/cryptsetup implementation. Due to the need to run cryptsetup as root, this test requires that the user have password-less sudo configured.

The test is set to only run against the 'luks' format so needs to be manually invoked with

cd tests/qemu-iotests
./check -luks 149

---
 block/Makefile.objs        |    2 +
 block/crypto.c             |  587 ++++++++++++
 qapi/block-core.json       |   22 +-
 tests/qemu-iotests/149     |  521 ++++++++++
 tests/qemu-iotests/149.out | 2252 ++++++++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/common  |    7 +
 tests/qemu-iotests/group   |    1 +
 7 files changed, 3390 insertions(+), 2 deletions(-)
 create mode 100644 block/crypto.c
 create mode 100755 tests/qemu-iotests/149
 create mode 100644 tests/qemu-iotests/149.out
block/Makefile.objs +2 -0
index cdd8655..3426a15 100644
@@ -23,6 +23,8 @@ block-obj-$(CONFIG_LIBSSH2) += ssh.o
 block-obj-y += accounting.o dirty-bitmap.o
 block-obj-y += write-threshold.o
 
+block-obj-y += crypto.o
+
 common-obj-y += stream.o
 common-obj-y += commit.o
 common-obj-y += backup.o
block/crypto.c new file +587 -0

587 lines not on this page · raw message

qapi/block-core.json +20 -2
index 9bf1b22..f2103b6 100644
@@ -242,11 +242,12 @@
 # @drv: the name of the block format used to open the backing device. As of
 #       0.14.0 this can be: 'blkdebug', 'bochs', 'cloop', 'cow', 'dmg',
 #       'file', 'file', 'ftp', 'ftps', 'host_cdrom', 'host_device',
-#       'http', 'https', 'nbd', 'parallels', 'qcow',
+#       'http', 'https', 'luks', 'nbd', 'parallels', 'qcow',
 #       'qcow2', 'raw', 'tftp', 'vdi', 'vmdk', 'vpc', 'vvfat'
 #       2.2: 'archipelago' added, 'cow' dropped
 #       2.3: 'host_floppy' deprecated
 #       2.5: 'host_floppy' dropped
+#       2.6: 'luks' added
 #
 # @backing_file: #optional the name of the backing file (for copy-on-write)
 #
@@ -1639,7 +1640,7 @@
 { 'enum': 'BlockdevDriver',
   'data': [ 'archipelago', 'blkdebug', 'blkverify', 'bochs', 'cloop',
             'dmg', 'file', 'ftp', 'ftps', 'host_cdrom', 'host_device',
-            'http', 'https', 'null-aio', 'null-co', 'parallels',
+            'http', 'https', 'luks', 'null-aio', 'null-co', 'parallels',
             'qcow', 'qcow2', 'qed', 'quorum', 'raw', 'tftp', 'vdi', 'vhdx',
             'vmdk', 'vpc', 'vvfat' ] }
 
@@ -1757,6 +1758,22 @@
   'data': { 'file': 'BlockdevRef' } }
 
 ##
+# @BlockdevOptionsLUKS
+#
+# Driver specific block device options for LUKS.
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing
+#              the decryption key (since 2.6). Mandatory except when
+#              doing a metadata-only probe of the image.
+#
+# Since: 2.6
+##
+{ 'struct': 'BlockdevOptionsLUKS',
+  'base': 'BlockdevOptionsGenericFormat',
+  'data': { '*key-secret': 'str' } }
+
+
+##
 # @BlockdevOptionsGenericCOWFormat
 #
 # Driver specific block device options for image format that have no option
@@ -2093,6 +2110,7 @@
       'http':       'BlockdevOptionsFile',
       'https':      'BlockdevOptionsFile',
 # TODO iscsi: Wait for structured options
+      'luks':       'BlockdevOptionsLUKS',
 # TODO nbd: Should take InetSocketAddress for 'host'?
 # TODO nfs: Wait for structured options
       'null-aio':   'BlockdevOptionsNull',
tests/qemu-iotests/149 new file +521 -0

521 lines not on this page · raw message

tests/qemu-iotests/149.out new file +2252 -0

1,834 lines not on this page · raw message

tests/qemu-iotests/common +7 -0
index ff84f4b..5575ddd 100644

Lines of this file are not shown. View the raw message.

tests/qemu-iotests/group +1 -0
index faf0f21..92ae8ec 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.5.0

Part of the diff is not shown here. View the raw message.

#2 lore raw

Re: [Qemu-devel] [PATCH v5 1/7] block: add flag to indicate that no I/O will be performed

In reply to Daniel P. Berrange

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 6 lines

When opening an image it is useful to know whether the caller intends to perform I/O on the image or not. In the case of encrypted images this will allow the block driver to avoid having to prompt for decryption keys when we merely want to query header metadata about the image. eg qemu-img info

Quoted 7 lines

This flag is enforced at the top level only, since even if we don't want todo I/O on the 'qcow2' file payload, the underlying 'file' driver will still need todo I/O to read the qcow2 header, for example.

Looks good to me, but it needs a rebase because it conflicts with the latest changes to qemu-img.

Kevin

#8 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

In reply to Daniel P. Berrange

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 50 lines

Add a block driver that is capable of supporting any full disk encryption format. This utilizes the previously added block encryption code, and at this time supports the LUKS format.

The driver code is capable of supporting any format supported by the QCryptoBlock module, so it registers one block driver for each format. This patch only registers the "luks" driver since the "qcow" driver is there only for back-compatibility with existing qcow built-in encryption.

New LUKS compatible volumes can be formatted using qemu-img with defaults for all settings.

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0 demo.luks 10G

Alternatively the cryptographic settings can be explicitly set

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0,cipher-alg=aes-256,\
                 cipher-mode=cbc,ivgen-alg=plain64,hash-alg=sha256 \
      demo.luks 10G

And query its size

$ qemu-img info demo.img
image: demo.img
file format: luks
virtual size: 10G (10737418240 bytes)
disk size: 132K
encrypted: yes

Note that it was not necessary to provide the password when querying info for the volume. The password is only required when performing I/O on the volume

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver.

The only algorithms listed in the LUKS spec that are not currently supported by this impl are sha512 and ripemd160 hashes and cast6 cipher.

A new I/O test is added which is used to validate the interoperability of the QEMU implementation of LUKS, with the dm-crypt/cryptsetup implementation. Due to the need to run cryptsetup as root, this test requires that the user have password-less sudo configured.

Quoted 8 lines

The test is set to only run against the 'luks' format so needs to be manually invoked with

cd tests/qemu-iotests
./check -luks 149

This is a huge patch. I'm not sure if it wouldn't be better to split off the test. I also think that having some test cases that don't require root privileges would be helpful, so maybe the test can be split in two halves as well, one requiring passwordless sudo and the other without special requirements.

Quoted 70 lines
 block/Makefile.objs        |    2 +
 block/crypto.c             |  587 ++++++++++++
 qapi/block-core.json       |   22 +-
 tests/qemu-iotests/149     |  521 ++++++++++
 tests/qemu-iotests/149.out | 2252 ++++++++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/common  |    7 +
 tests/qemu-iotests/group   |    1 +
 7 files changed, 3390 insertions(+), 2 deletions(-)
 create mode 100644 block/crypto.c
 create mode 100755 tests/qemu-iotests/149
 create mode 100644 tests/qemu-iotests/149.out
block/Makefile.objs +2 -0
index cdd8655..3426a15 100644
@@ -23,6 +23,8 @@ block-obj-$(CONFIG_LIBSSH2) += ssh.o
 block-obj-y += accounting.o dirty-bitmap.o
 block-obj-y += write-threshold.o
 
+block-obj-y += crypto.o
+
 common-obj-y += stream.o
 common-obj-y += commit.o
 common-obj-y += backup.o
block/crypto.c new file +39 -0
new file mode 100644
index 0000000..5efca6c
@@ -0,0 +1,587 @@
+/*
+ * QEMU block full disk encryption
+ *
+ * Copyright (c) 2015-2016 Red Hat, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "qemu/osdep.h"
+
+#include "block/block_int.h"
+#include "crypto/block.h"
+#include "qapi/opts-visitor.h"
+#include "qapi-visit.h"
+
+#define BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET "key-secret"
+#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG "cipher-alg"
+#define BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE "cipher-mode"
+#define BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG "ivgen-alg"
+#define BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG "ivgen-hash-alg"
+#define BLOCK_CRYPTO_OPT_LUKS_HASH_ALG "hash-alg"
+
+typedef struct BlockCrypto BlockCrypto;
+
+struct BlockCrypto {
+    QCryptoBlock *block;
+    CoMutex lock;

block/crypto.c line 49

Quoted 10 lines
block/crypto.c new file +10 -0
+};
+
+
+static int block_crypto_probe_generic(QCryptoBlockFormat format,
+                                      const uint8_t *buf,
+                                      int buf_size,
+                                      const char *filename)
+{
+    if (qcrypto_block_has_format(format,
+                                 buf, buf_size)) {

This is short enough for a single line.

Quoted 65 lines
block/crypto.c new file +65 -0
+        return 100;
+    } else {
+        return 0;
+    }
+}
+
+
+static ssize_t block_crypto_read_func(QCryptoBlock *block,
+                                      size_t offset,
+                                      uint8_t *buf,
+                                      size_t buflen,
+                                      Error **errp,
+                                      void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    ssize_t ret;
+
+    ret = bdrv_pread(bs->file->bs, offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not read encryption header");
+        return ret;
+    }
+    return ret;
+}
+
+
+struct BlockCryptoCreateData {
+    const char *filename;
+    QemuOpts *opts;
+    BlockDriverState *bs;
+    uint64_t size;
+};
+
+
+static ssize_t block_crypto_write_func(QCryptoBlock *block,
+                                       size_t offset,
+                                       const uint8_t *buf,
+                                       size_t buflen,
+                                       Error **errp,
+                                       void *opaque)
+{
+    struct BlockCryptoCreateData *data = opaque;
+    ssize_t ret;
+
+    ret = bdrv_pwrite(data->bs, offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not write encryption header");
+        return ret;
+    }
+    return ret;
+}
+
+
+static ssize_t block_crypto_init_func(QCryptoBlock *block,
+                                      size_t headerlen,
+                                      Error **errp,
+                                      void *opaque)
+{
+    struct BlockCryptoCreateData *data = opaque;
+    int ret;
+
+    /* User provided size should reflect amount of space made
+     * available to the guest, so we must take account of that
+     * which will be used by the crypto header
+     */

block/crypto.c line 124

Quoted 10 lines
block/crypto.c new file +10 -0
+    data->size += headerlen;
+
+    qemu_opt_set_number(data->opts, BLOCK_OPT_SIZE, data->size, &error_abort);
+    ret = bdrv_create_file(data->filename, data->opts, errp);
+    if (ret < 0) {
+        return -1;
+    }
+
+    ret = bdrv_open(&data->bs, data->filename, NULL, NULL,
+                    BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);

We should probably use blk_open() here like the other image format drivers do now, and preferably use blk_*() functions to access the image.

You will also want to specify BDRV_O_CACHE_WB (while it exists, I'm going to remove it soon).

Quoted 72 lines
block/crypto.c new file +72 -0
+    if (ret < 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+
+static QemuOptsList block_crypto_runtime_opts_luks = {
+    .name = "crypto",
+    .head = QTAILQ_HEAD_INITIALIZER(block_crypto_runtime_opts_luks.head),
+    .desc = {
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET,
+            .type = QEMU_OPT_STRING,
+            .help = "ID of the secret that provides the encryption key",
+        },
+        { /* end of list */ }
+    },
+};
+
+
+static QemuOptsList block_crypto_create_opts_luks = {
+    .name = "crypto",
+    .head = QTAILQ_HEAD_INITIALIZER(block_crypto_create_opts_luks.head),
+    .desc = {
+        {
+            .name = BLOCK_OPT_SIZE,
+            .type = QEMU_OPT_SIZE,
+            .help = "Virtual disk size"
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_KEY_SECRET,
+            .type = QEMU_OPT_STRING,
+            .help = "ID of the secret that provides the encryption key",
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_ALG,
+            .type = QEMU_OPT_STRING,
+            .help = "Name of encryption cipher algorithm",
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_CIPHER_MODE,
+            .type = QEMU_OPT_STRING,
+            .help = "Name of encryption cipher mode",
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_ALG,
+            .type = QEMU_OPT_STRING,
+            .help = "Name of IV generator algorithm",
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_IVGEN_HASH_ALG,
+            .type = QEMU_OPT_STRING,
+            .help = "Name of IV generator hash algorithm",
+        },
+        {
+            .name = BLOCK_CRYPTO_OPT_LUKS_HASH_ALG,
+            .type = QEMU_OPT_STRING,
+            .help = "Name of encryption hash algorithm",
+        },
+        { /* end of list */ }
+    },
+};
+
+
+static QCryptoBlockOpenOptions *
+block_crypto_open_opts_init(QCryptoBlockFormat format,
+                            QemuOpts *opts,
+                            Error **errp)
+{
+    OptsVisitor *ov;

block/crypto.c line 206

Quoted 10 lines
block/crypto.c new file +10 -0
+    QCryptoBlockOpenOptions *ret = NULL;
+    Error *local_err = NULL;
+
+    ret = g_new0(QCryptoBlockOpenOptions, 1);
+    ret->format = format;
+
+    ov = opts_visitor_new(opts);
+
+    visit_start_struct(opts_get_visitor(ov),
+                       "luks", NULL, 0, &local_err);

As this refers to "luks" specifically, shouldn't it be inside the switch below?

Quoted 36 lines
block/crypto.c new file +36 -0
+    if (local_err) {
+        goto out;
+    }
+
+    switch (format) {
+    case Q_CRYPTO_BLOCK_FORMAT_LUKS:
+        visit_type_QCryptoBlockOptionsLUKS_members(
+            opts_get_visitor(ov), &ret->u.luks, &local_err);
+        break;
+
+    default:
+        error_setg(&local_err, "Unsupported block format %d", format);
+        break;
+    }
+    error_propagate(errp, local_err);
+    local_err = NULL;
+
+    visit_end_struct(opts_get_visitor(ov), &local_err);
+
+ out:
+    if (local_err) {
+        error_propagate(errp, local_err);
+        qapi_free_QCryptoBlockOpenOptions(ret);
+        ret = NULL;
+    }
+    opts_visitor_cleanup(ov);
+    return ret;
+}
+
+
+static QCryptoBlockCreateOptions *
+block_crypto_create_opts_init(QCryptoBlockFormat format,
+                              QemuOpts *opts,
+                              Error **errp)
+{
+    OptsVisitor *ov;

block/crypto.c line 252

Quoted 10 lines
block/crypto.c new file +10 -0
+    QCryptoBlockCreateOptions *ret = NULL;
+    Error *local_err = NULL;
+
+    ret = g_new0(QCryptoBlockCreateOptions, 1);
+    ret->format = format;
+
+    ov = opts_visitor_new(opts);
+
+    visit_start_struct(opts_get_visitor(ov),
+                       "luks", NULL, 0, &local_err);

Same here.

Quoted 144 lines
block/crypto.c new file +144 -0
+    if (local_err) {
+        goto out;
+    }
+
+    switch (format) {
+    case Q_CRYPTO_BLOCK_FORMAT_LUKS:
+        visit_type_QCryptoBlockCreateOptionsLUKS_members(
+            opts_get_visitor(ov), &ret->u.luks, &local_err);
+        break;
+
+    default:
+        error_setg(&local_err, "Unsupported block format %d", format);
+        break;
+    }
+    error_propagate(errp, local_err);
+    local_err = NULL;
+
+    visit_end_struct(opts_get_visitor(ov), &local_err);
+
+ out:
+    if (local_err) {
+        error_propagate(errp, local_err);
+        qapi_free_QCryptoBlockCreateOptions(ret);
+        ret = NULL;
+    }
+    opts_visitor_cleanup(ov);
+    return ret;
+}
+
+
+static int block_crypto_open_generic(QCryptoBlockFormat format,
+                                     QemuOptsList *opts_spec,
+                                     BlockDriverState *bs,
+                                     QDict *options,
+                                     int flags,
+                                     Error **errp)
+{
+    BlockCrypto *crypto = bs->opaque;
+    QemuOpts *opts = NULL;
+    Error *local_err = NULL;
+    int ret = -EINVAL;
+    QCryptoBlockOpenOptions *open_opts = NULL;
+    unsigned int cflags = 0;
+
+    opts = qemu_opts_create(opts_spec, NULL, 0, &error_abort);
+    qemu_opts_absorb_qdict(opts, options, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        goto cleanup;
+    }
+
+    open_opts = block_crypto_open_opts_init(format, opts, errp);
+    if (!open_opts) {
+        goto cleanup;
+    }
+
+    if (flags & BDRV_O_NO_IO) {
+        cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
+    }
+    crypto->block = qcrypto_block_open(open_opts,
+                                       block_crypto_read_func,
+                                       bs,
+                                       cflags,
+                                       errp);
+
+    if (!crypto->block) {
+        ret = -EIO;
+        goto cleanup;
+    }
+
+    bs->encrypted = 1;
+    bs->valid_key = 1;
+
+    qemu_co_mutex_init(&crypto->lock);
+
+    ret = 0;
+ cleanup:
+    qapi_free_QCryptoBlockOpenOptions(open_opts);
+    return ret;
+}
+
+
+static int block_crypto_create_generic(QCryptoBlockFormat format,
+                                       const char *filename,
+                                       QemuOpts *opts,
+                                       Error **errp)
+{
+    int ret = -EINVAL;
+    QCryptoBlockCreateOptions *create_opts = NULL;
+    QCryptoBlock *crypto = NULL;
+    struct BlockCryptoCreateData data;
+
+    data.size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
+                         BDRV_SECTOR_SIZE);
+    data.opts = opts;
+    data.filename = filename;
+    data.bs = NULL;
+
+    create_opts = block_crypto_create_opts_init(format, opts, errp);
+    if (!create_opts) {
+        return -1;
+    }
+
+    crypto = qcrypto_block_create(create_opts,
+                                  block_crypto_init_func,
+                                  block_crypto_write_func,
+                                  &data,
+                                  errp);
+
+    if (!crypto) {
+        ret = -EIO;
+        goto cleanup;
+    }
+
+    ret = 0;
+ cleanup:
+    qcrypto_block_free(crypto);
+    bdrv_unref(data.bs);
+    qapi_free_QCryptoBlockCreateOptions(create_opts);
+    return ret;
+}
+
+static void block_crypto_close(BlockDriverState *bs)
+{
+    BlockCrypto *crypto = bs->opaque;
+    qcrypto_block_free(crypto->block);
+}
+
+
+#define BLOCK_CRYPTO_MAX_SECTORS 32
+
+static coroutine_fn int
+block_crypto_co_readv(BlockDriverState *bs, int64_t sector_num,
+                      int remaining_sectors, QEMUIOVector *qiov)
+{
+    BlockCrypto *crypto = bs->opaque;
+    int cur_nr_sectors; /* number of sectors in current iteration */
+    uint64_t bytes_done = 0;
+    uint8_t *cipher_data = NULL;
+    QEMUIOVector hd_qiov;
+    int ret = 0;
+    size_t payload_offset =
+        qcrypto_block_get_payload_offset(crypto->block) / 512;
+

block/crypto.c line 406

Quoted 10 lines
block/crypto.c new file +10 -0
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+
+    qemu_co_mutex_lock(&crypto->lock);
+
+    /* Bounce buffer so we have a linear mem region for
+     * entire sector. XXX optimize so we avoid bounce
+     * buffer in case that qiov->niov == 1
+     */
+    cipher_data =
+        qemu_try_blockalign(bs->file->bs, BLOCK_CRYPTO_MAX_SECTORS * 512);

As long as we create an individual buffer for each request, shouldn't MIN(BLOCK_CRYPTO_MAX_SECTORS * 512, qiov->size) be enough?

Quoted 6 lines
block/crypto.c new file +6 -0
+    if (cipher_data == NULL) {
+        ret = -ENOMEM;
+        goto cleanup;
+    }
+
+    while (remaining_sectors) {

block/crypto.c line 422

Quoted 10 lines
block/crypto.c new file +10 -0
+        cur_nr_sectors = remaining_sectors;
+
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+
+        qemu_iovec_reset(&hd_qiov);
+        qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
+
+        qemu_co_mutex_unlock(&crypto->lock);

Between qemu_co_mutex_lock() and here, there is no yield point...

block/crypto.c line 435

Quoted 13 lines
block/crypto.c new file +13 -0
+        ret = bdrv_co_readv(bs->file->bs,
+                            payload_offset + sector_num,
+                            cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        if (qcrypto_block_decrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;

Need a real -errno code here.

block/crypto.c line 437

Quoted 2 lines
block/crypto.c new file +2 -0
+            goto cleanup;
+        }

...nor is there one between here and the end of the function.

So what does this CoMutex protect? If qcrypto_block_decrypt() needs this for some reason (it doesn't seem to be touching anything that isn't per request, but maybe I'm missing something), would it be clearer to put the locking only around that call?

Quoted 25 lines
block/crypto.c new file +25 -0
+
+        qemu_iovec_from_buf(qiov, bytes_done,
+                            cipher_data, cur_nr_sectors * 512);
+
+        remaining_sectors -= cur_nr_sectors;
+        sector_num += cur_nr_sectors;
+        bytes_done += cur_nr_sectors * 512;
+    }
+
+ cleanup:
+    qemu_co_mutex_unlock(&crypto->lock);
+
+    qemu_iovec_destroy(&hd_qiov);
+    qemu_vfree(cipher_data);
+
+    return ret;
+}
+
+
+static coroutine_fn int
+block_crypto_co_writev(BlockDriverState *bs, int64_t sector_num,
+                       int remaining_sectors, QEMUIOVector *qiov)
+{
+    BlockCrypto *crypto = bs->opaque;
+    int cur_nr_sectors; /* number of sectors in current iteration */

block/crypto.c line 472

Quoted 10 lines
block/crypto.c new file +10 -0
+    uint64_t bytes_done = 0;
+    uint8_t *cipher_data = NULL;
+    QEMUIOVector hd_qiov;
+    int ret = 0;
+    size_t payload_offset =
+        qcrypto_block_get_payload_offset(crypto->block) / 512;
+
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+
+    qemu_co_mutex_lock(&crypto->lock);

Same locking question as above.

block/crypto.c line 406

Quoted 6 lines
block/crypto.c new file +6 -0
+    /* Bounce buffer so we have a linear mem region for
+     * entire sector. XXX optimize so we avoid bounce
+     * buffer in case that qiov->niov == 1
+     */
+    cipher_data =
+        qemu_try_blockalign(bs->file->bs, BLOCK_CRYPTO_MAX_SECTORS * 512);

Same as above as well.

Quoted 91 lines
block/crypto.c new file +91 -0
+    if (cipher_data == NULL) {
+        ret = -ENOMEM;
+        goto cleanup;
+    }
+
+    while (remaining_sectors) {
+        cur_nr_sectors = remaining_sectors;
+
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+
+        qemu_iovec_to_buf(qiov, bytes_done,
+                          cipher_data, cur_nr_sectors * 512);
+
+        if (qcrypto_block_encrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;
+            goto cleanup;
+        }
+
+        qemu_iovec_reset(&hd_qiov);
+        qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
+
+        qemu_co_mutex_unlock(&crypto->lock);
+        ret = bdrv_co_writev(bs->file->bs,
+                             payload_offset + sector_num,
+                             cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        remaining_sectors -= cur_nr_sectors;
+        sector_num += cur_nr_sectors;
+        bytes_done += cur_nr_sectors * 512;
+    }
+
+ cleanup:
+    qemu_co_mutex_unlock(&crypto->lock);
+
+    qemu_iovec_destroy(&hd_qiov);
+    qemu_vfree(cipher_data);
+
+    return ret;
+}
+
+
+static int64_t block_crypto_getlength(BlockDriverState *bs)
+{
+    BlockCrypto *crypto = bs->opaque;
+    int64_t len = bdrv_getlength(bs->file->bs);
+
+    ssize_t offset = qcrypto_block_get_payload_offset(crypto->block);
+
+    len -= offset;
+
+    return len;
+}
+
+
+static int block_crypto_probe_luks(const uint8_t *buf,
+                                   int buf_size,
+                                   const char *filename) {
+    return block_crypto_probe_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
+                                      buf, buf_size, filename);
+}
+
+static int block_crypto_open_luks(BlockDriverState *bs,
+                                  QDict *options,
+                                  int flags,
+                                  Error **errp)
+{
+    return block_crypto_open_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
+                                     &block_crypto_runtime_opts_luks,
+                                     bs, options, flags, errp);
+}
+
+static int block_crypto_create_luks(const char *filename,
+                                    QemuOpts *opts,
+                                    Error **errp)
+{
+    return block_crypto_create_generic(Q_CRYPTO_BLOCK_FORMAT_LUKS,
+                                       filename, opts, errp);
+}
+
+BlockDriver bdrv_crypto_luks = {
+    .format_name        = "luks",
+    .instance_size      = sizeof(BlockCrypto),

block/crypto.c line 580

Quoted 10 lines
block/crypto.c new file +10 -0
+    .bdrv_probe         = block_crypto_probe_luks,
+    .bdrv_open          = block_crypto_open_luks,
+    .bdrv_close         = block_crypto_close,
+    .bdrv_create        = block_crypto_create_luks,
+    .create_opts        = &block_crypto_create_opts_luks,
+
+    .bdrv_co_readv      = block_crypto_co_readv,
+    .bdrv_co_writev     = block_crypto_co_writev,
+    .bdrv_getlength     = block_crypto_getlength,
+};

Rather minimalistic, but we can always add the missing functions later.

Quoted 57 lines
block/crypto.c new file +6 -0
+static void block_crypto_init(void)
+{
+    bdrv_register(&bdrv_crypto_luks);
+}
+
+block_init(block_crypto_init);
qapi/block-core.json +19 -2
index 9bf1b22..f2103b6 100644
@@ -242,11 +242,12 @@
 # @drv: the name of the block format used to open the backing device. As of
 #       0.14.0 this can be: 'blkdebug', 'bochs', 'cloop', 'cow', 'dmg',
 #       'file', 'file', 'ftp', 'ftps', 'host_cdrom', 'host_device',
-#       'http', 'https', 'nbd', 'parallels', 'qcow',
+#       'http', 'https', 'luks', 'nbd', 'parallels', 'qcow',
 #       'qcow2', 'raw', 'tftp', 'vdi', 'vmdk', 'vpc', 'vvfat'
 #       2.2: 'archipelago' added, 'cow' dropped
 #       2.3: 'host_floppy' deprecated
 #       2.5: 'host_floppy' dropped
+#       2.6: 'luks' added
 #
 # @backing_file: #optional the name of the backing file (for copy-on-write)
 #
@@ -1639,7 +1640,7 @@
 { 'enum': 'BlockdevDriver',
   'data': [ 'archipelago', 'blkdebug', 'blkverify', 'bochs', 'cloop',
             'dmg', 'file', 'ftp', 'ftps', 'host_cdrom', 'host_device',
-            'http', 'https', 'null-aio', 'null-co', 'parallels',
+            'http', 'https', 'luks', 'null-aio', 'null-co', 'parallels',
             'qcow', 'qcow2', 'qed', 'quorum', 'raw', 'tftp', 'vdi', 'vhdx',
             'vmdk', 'vpc', 'vvfat' ] }
 
@@ -1757,6 +1758,22 @@
   'data': { 'file': 'BlockdevRef' } }
 
 ##
+# @BlockdevOptionsLUKS
+#
+# Driver specific block device options for LUKS.
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing
+#              the decryption key (since 2.6). Mandatory except when
+#              doing a metadata-only probe of the image.
+#
+# Since: 2.6
+##
+{ 'struct': 'BlockdevOptionsLUKS',
+  'base': 'BlockdevOptionsGenericFormat',
+  'data': { '*key-secret': 'str' } }
+
+
+##
 # @BlockdevOptionsGenericCOWFormat
 #
 # Driver specific block device options for image format that have no option

qapi/block-core.json line 2116

Quoted 7 lines
qapi/block-core.json +1 -0
@@ -2093,6 +2110,7 @@
       'http':       'BlockdevOptionsFile',
       'https':      'BlockdevOptionsFile',
 # TODO iscsi: Wait for structured options
+      'luks':       'BlockdevOptionsLUKS',
 # TODO nbd: Should take InetSocketAddress for 'host'?
 # TODO nfs: Wait for structured options
       'null-aio':   'BlockdevOptionsNull',

Kevin

#15 lore raw

Re: [Qemu-devel] [PATCH v5 7/7] block: drop support for using qcow[2] encryption with system emulators

In reply to Daniel P. Berrange

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 22 lines

For a couple of releases we have been warning

Encrypted images are deprecated
Support for them will be removed in a future release.
You can use 'qemu-img convert' to convert your image to an unencrypted one.

This warning was issued by system emulators, qemu-img, qemu-nbd and qemu-io. Such a broad warning was issued because the original intention was to rip out all the code for dealing with encryption inside the QEMU block layer APIs.

The new block encryption framework used for the LUKS driver does not rely on the unloved block layer API for encryption keys, instead using the QOM 'secret' object type. It is thus no longer appropriate to warn about encryption unconditionally.

When the qcow/qcow2 drivers are converted to use the new encryption framework too, it will be practical to keep AES-CBC support present for use in qemu-img, qemu-io & qemu-nbd to allow for interoperability with older QEMU versions and liberation of data from existing encrypted qcow2 files.

Quoted 7 lines

Thus this change, removes the deprecation warning, in its place adding a fatal error preventing use of qcow[2] built-in encryption inside the system emulators. Use of qcow[2] encryption in qemu-img, qemu-io, qemu-nbd no longer triggers any warning message, since that support is now expected to remain available long term, given the maint burden has been eliminated.

Let's do this only after the qcow2 LUKS support has been merged so that users have an alternative to switch to.

Kevin

#16 lore raw

Re: [Qemu-devel] [PATCH v5 7/7] block: drop support for using qcow[2] encryption with system emulators

Quoted 29 lines · Kevin Wolf

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 28 lines

For a couple of releases we have been warning

Encrypted images are deprecated
Support for them will be removed in a future release.
You can use 'qemu-img convert' to convert your image to an unencrypted one.

This warning was issued by system emulators, qemu-img, qemu-nbd and qemu-io. Such a broad warning was issued because the original intention was to rip out all the code for dealing with encryption inside the QEMU block layer APIs.

The new block encryption framework used for the LUKS driver does not rely on the unloved block layer API for encryption keys, instead using the QOM 'secret' object type. It is thus no longer appropriate to warn about encryption unconditionally.

When the qcow/qcow2 drivers are converted to use the new encryption framework too, it will be practical to keep AES-CBC support present for use in qemu-img, qemu-io & qemu-nbd to allow for interoperability with older QEMU versions and liberation of data from existing encrypted qcow2 files.

Thus this change, removes the deprecation warning, in its place adding a fatal error preventing use of qcow[2] built-in encryption inside the system emulators. Use of qcow[2] encryption in qemu-img, qemu-io, qemu-nbd no longer triggers any warning message, since that support is now expected to remain available long term, given the maint burden has been eliminated.

Quoted 4 lines
Quoted 1 line

Let's do this only after the qcow2 LUKS support has been merged so that users have an alternative to switch to.

Ok, I'll need to respin this to just move the deprecation warning then

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#9 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

In reply to Kevin Wolf
Quoted 57 lines · Kevin Wolf

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 56 lines

Add a block driver that is capable of supporting any full disk encryption format. This utilizes the previously added block encryption code, and at this time supports the LUKS format.

The driver code is capable of supporting any format supported by the QCryptoBlock module, so it registers one block driver for each format. This patch only registers the "luks" driver since the "qcow" driver is there only for back-compatibility with existing qcow built-in encryption.

New LUKS compatible volumes can be formatted using qemu-img with defaults for all settings.

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0 demo.luks 10G

Alternatively the cryptographic settings can be explicitly set

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0,cipher-alg=aes-256,\
                 cipher-mode=cbc,ivgen-alg=plain64,hash-alg=sha256 \
      demo.luks 10G

And query its size

$ qemu-img info demo.img
image: demo.img
file format: luks
virtual size: 10G (10737418240 bytes)
disk size: 132K
encrypted: yes

Note that it was not necessary to provide the password when querying info for the volume. The password is only required when performing I/O on the volume

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver.

The only algorithms listed in the LUKS spec that are not currently supported by this impl are sha512 and ripemd160 hashes and cast6 cipher.

A new I/O test is added which is used to validate the interoperability of the QEMU implementation of LUKS, with the dm-crypt/cryptsetup implementation. Due to the need to run cryptsetup as root, this test requires that the user have password-less sudo configured.

The test is set to only run against the 'luks' format so needs to be manually invoked with

cd tests/qemu-iotests
./check -luks 149

Quoted 8 lines
Quoted 2 lines

This is a huge patch. I'm not sure if it wouldn't be better to split off the test. I also think that having some test cases that don't require root privileges would be helpful, so maybe the test can be split in two halves as well, one requiring passwordless sudo and the other without special requirements.

I can certainly split off the test, however, I don't think it can be split into 2 as you describe, as both halves of the two require sudo privileges. So in one half we're creating images with dm-crypt and processing them with qemu, and in the other half we're creating images with qemu-img and processing them with dm-crypt.

This test was specifically designed to validate dm-crypt interoperability, and my intention was that "pure" QEMU block driver testing of it would be covered by the various pre-existing I/O tests. The problem is that I need to update those existing tests to know how to pass the right args to qemu-img to setup passwords. If I can do that, then we'll have some good testing cover of the luks driver without needing sudo.

So I'll look at converting a couple of key pre-existing tests to get such coverage, and put this test in its own patch.

Quoted 27 lines
Quoted 12 lines
block/crypto.c new file +12 -0
+static ssize_t block_crypto_init_func(QCryptoBlock *block,
+                                      size_t headerlen,
+                                      Error **errp,
+                                      void *opaque)
+{
+    struct BlockCryptoCreateData *data = opaque;
+    int ret;
+
+    /* User provided size should reflect amount of space made
+     * available to the guest, so we must take account of that
+     * which will be used by the crypto header
+     */

block/crypto.c line 124

Quoted 10 lines
block/crypto.c new file +10 -0
+    data->size += headerlen;
+
+    qemu_opt_set_number(data->opts, BLOCK_OPT_SIZE, data->size, &error_abort);
+    ret = bdrv_create_file(data->filename, data->opts, errp);
+    if (ret < 0) {
+        return -1;
+    }
+
+    ret = bdrv_open(&data->bs, data->filename, NULL, NULL,
+                    BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);

We should probably use blk_open() here like the other image format drivers do now, and preferably use blk_*() functions to access the image.

Quoted 2 lines

You will also want to specify BDRV_O_CACHE_WB (while it exists, I'm going to remove it soon).

Ok, will do.

Quoted 11 lines
Quoted 11 lines
block/crypto.c new file +11 -0
+static QCryptoBlockOpenOptions *
+block_crypto_open_opts_init(QCryptoBlockFormat format,
+                            QemuOpts *opts,
+                            Error **errp)
+{
+    OptsVisitor *ov;
+    QCryptoBlockOpenOptions *ret = NULL;
+    Error *local_err = NULL;
+
+    ret = g_new0(QCryptoBlockOpenOptions, 1);
+    ret->format = format;
Quoted 8 lines

block/crypto.c line 206

Quoted 5 lines
block/crypto.c new file +5 -0
+
+    ov = opts_visitor_new(opts);
+
+    visit_start_struct(opts_get_visitor(ov),
+                       "luks", NULL, 0, &local_err);

As this refers to "luks" specifically, shouldn't it be inside the switch below?

Or probably better if I just change it to "", since this parameter is not actually used in this context IIRC.

Quoted 50 lines
Quoted 50 lines
block/crypto.c new file +48 -0
+    if (local_err) {
+        goto out;
+    }
+
+    switch (format) {
+    case Q_CRYPTO_BLOCK_FORMAT_LUKS:
+        visit_type_QCryptoBlockOptionsLUKS_members(
+            opts_get_visitor(ov), &ret->u.luks, &local_err);
+        break;
+
+    default:
+        error_setg(&local_err, "Unsupported block format %d", format);
+        break;
+    }
+    error_propagate(errp, local_err);
+    local_err = NULL;
+
+    visit_end_struct(opts_get_visitor(ov), &local_err);
+
+ out:
+    if (local_err) {
+        error_propagate(errp, local_err);
+        qapi_free_QCryptoBlockOpenOptions(ret);
+        ret = NULL;
+    }
+    opts_visitor_cleanup(ov);
+    return ret;
+}
 
 
+#define BLOCK_CRYPTO_MAX_SECTORS 32
+
+static coroutine_fn int
+block_crypto_co_readv(BlockDriverState *bs, int64_t sector_num,
+                      int remaining_sectors, QEMUIOVector *qiov)
+{
+    BlockCrypto *crypto = bs->opaque;
+    int cur_nr_sectors; /* number of sectors in current iteration */
+    uint64_t bytes_done = 0;
+    uint8_t *cipher_data = NULL;
+    QEMUIOVector hd_qiov;
+    int ret = 0;
+    size_t payload_offset =
+        qcrypto_block_get_payload_offset(crypto->block) / 512;
+
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+
+    qemu_co_mutex_lock(&crypto->lock);
+
+    /* Bounce buffer so we have a linear mem region for
Quoted 8 lines

block/crypto.c line 406

Quoted 5 lines
block/crypto.c new file +5 -0
+     * entire sector. XXX optimize so we avoid bounce
+     * buffer in case that qiov->niov == 1
+     */
+    cipher_data =
+        qemu_try_blockalign(bs->file->bs, BLOCK_CRYPTO_MAX_SECTORS * 512);

As long as we create an individual buffer for each request, shouldn't MIN(BLOCK_CRYPTO_MAX_SECTORS * 512, qiov->size) be enough?

Yes, you're right. I didn't realize there was a pre-calcuated total size field in QEMUIOVector

Quoted 38 lines
Quoted 6 lines
block/crypto.c new file +6 -0
+    if (cipher_data == NULL) {
+        ret = -ENOMEM;
+        goto cleanup;
+    }
+
+    while (remaining_sectors) {

block/crypto.c line 422

Quoted 10 lines
block/crypto.c new file +10 -0
+        cur_nr_sectors = remaining_sectors;
+
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+
+        qemu_iovec_reset(&hd_qiov);
+        qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
+
+        qemu_co_mutex_unlock(&crypto->lock);

Between qemu_co_mutex_lock() and here, there is no yield point...

block/crypto.c line 435

Quoted 13 lines
block/crypto.c new file +13 -0
+        ret = bdrv_co_readv(bs->file->bs,
+                            payload_offset + sector_num,
+                            cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        if (qcrypto_block_decrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;

Need a real -errno code here.

Review

Quoted 2 lines
(quoted diff) +2 -0
+            goto cleanup;
+        }
Quoted 6 lines

...nor is there one between here and the end of the function.

So what does this CoMutex protect? If qcrypto_block_decrypt() needs this for some reason (it doesn't seem to be touching anything that isn't per request, but maybe I'm missing something), would it be clearer to put the locking only around that call?

This just a result of me blindly copying the locking pattern from qcow2.c qcow2_co_readv() method without really understanding what it was protecting.

If it not possible for two calls to bdrv_co_readv() to run in parallel, then I can drop this mutex.

Quoted 20 lines
Quoted 19 lines
block/crypto.c new file +18 -0
+
+        qemu_iovec_from_buf(qiov, bytes_done,
+                            cipher_data, cur_nr_sectors * 512);
+
+        remaining_sectors -= cur_nr_sectors;
+        sector_num += cur_nr_sectors;
+        bytes_done += cur_nr_sectors * 512;
+    }
+
+ cleanup:
+    qemu_co_mutex_unlock(&crypto->lock);
+
+    qemu_iovec_destroy(&hd_qiov);
+    qemu_vfree(cipher_data);
+
+    return ret;
+}
+
Quoted 15 lines

block/crypto.c line 580

Quoted 13 lines
block/crypto.c new file +13 -0
+BlockDriver bdrv_crypto_luks = {
+    .format_name        = "luks",
+    .instance_size      = sizeof(BlockCrypto),
+    .bdrv_probe         = block_crypto_probe_luks,
+    .bdrv_open          = block_crypto_open_luks,
+    .bdrv_close         = block_crypto_close,
+    .bdrv_create        = block_crypto_create_luks,
+    .create_opts        = &block_crypto_create_opts_luks,
+
+    .bdrv_co_readv      = block_crypto_co_readv,
+    .bdrv_co_writev     = block_crypto_co_writev,
+    .bdrv_getlength     = block_crypto_getlength,
+};

Rather minimalistic, but we can always add the missing functions later.

Do you have any recommendations on which are top priority / important callbacks to add support for so I can prioritize future effort.

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#10 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

Am 18.03.2016 um 15:45 hat Daniel P. Berrange geschrieben:

Quoted 67 lines · Kevin Wolf
Quoted 57 lines

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

Quoted 56 lines

Add a block driver that is capable of supporting any full disk encryption format. This utilizes the previously added block encryption code, and at this time supports the LUKS format.

The driver code is capable of supporting any format supported by the QCryptoBlock module, so it registers one block driver for each format. This patch only registers the "luks" driver since the "qcow" driver is there only for back-compatibility with existing qcow built-in encryption.

New LUKS compatible volumes can be formatted using qemu-img with defaults for all settings.

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0 demo.luks 10G

Alternatively the cryptographic settings can be explicitly set

$ qemu-img create --object secret,data=123456,id=sec0 \
      -f luks -o key-secret=sec0,cipher-alg=aes-256,\
                 cipher-mode=cbc,ivgen-alg=plain64,hash-alg=sha256 \
      demo.luks 10G

And query its size

$ qemu-img info demo.img
image: demo.img
file format: luks
virtual size: 10G (10737418240 bytes)
disk size: 132K
encrypted: yes

Note that it was not necessary to provide the password when querying info for the volume. The password is only required when performing I/O on the volume

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver.

The only algorithms listed in the LUKS spec that are not currently supported by this impl are sha512 and ripemd160 hashes and cast6 cipher.

A new I/O test is added which is used to validate the interoperability of the QEMU implementation of LUKS, with the dm-crypt/cryptsetup implementation. Due to the need to run cryptsetup as root, this test requires that the user have password-less sudo configured.

The test is set to only run against the 'luks' format so needs to be manually invoked with

cd tests/qemu-iotests
./check -luks 149

Quoted 8 lines
Quoted 2 lines

This is a huge patch. I'm not sure if it wouldn't be better to split off the test. I also think that having some test cases that don't require root privileges would be helpful, so maybe the test can be split in two halves as well, one requiring passwordless sudo and the other without special requirements.

Quoted 5 lines

I can certainly split off the test, however, I don't think it can be split into 2 as you describe, as both halves of the two require sudo privileges. So in one half we're creating images with dm-crypt and processing them with qemu, and in the other half we're creating images with qemu-img and processing them with dm-crypt.

Yes, I only read the test case after writing this comment.

Quoted 9 lines

This test was specifically designed to validate dm-crypt interoperability, and my intention was that "pure" QEMU block driver testing of it would be covered by the various pre-existing I/O tests. The problem is that I need to update those existing tests to know how to pass the right args to qemu-img to setup passwords. If I can do that, then we'll have some good testing cover of the luks driver without needing sudo.

So I'll look at converting a couple of key pre-existing tests to get such coverage, and put this test in its own patch.

Okay, that makes sense. Then we don't need a new test case.

Quoted 20 lines
Quoted 11 lines
Quoted 11 lines
block/crypto.c new file +11 -0
+static QCryptoBlockOpenOptions *
+block_crypto_open_opts_init(QCryptoBlockFormat format,
+                            QemuOpts *opts,
+                            Error **errp)
+{
+    OptsVisitor *ov;
+    QCryptoBlockOpenOptions *ret = NULL;
+    Error *local_err = NULL;
+
+    ret = g_new0(QCryptoBlockOpenOptions, 1);
+    ret->format = format;
Quoted 8 lines

block/crypto.c line 206

Quoted 5 lines
block/crypto.c new file +5 -0
+
+    ov = opts_visitor_new(opts);
+
+    visit_start_struct(opts_get_visitor(ov),
+                       "luks", NULL, 0, &local_err);

As this refers to "luks" specifically, shouldn't it be inside the switch below?

Quoted 2 lines

Or probably better if I just change it to "", since this parameter is not actually used in this context IIRC.

NULL then? It would be very obvious then if it were used against our expectations.

Quoted 72 lines
Quoted 20 lines
Quoted 20 lines
block/crypto.c new file +20 -0
+#define BLOCK_CRYPTO_MAX_SECTORS 32
+
+static coroutine_fn int
+block_crypto_co_readv(BlockDriverState *bs, int64_t sector_num,
+                      int remaining_sectors, QEMUIOVector *qiov)
+{
+    BlockCrypto *crypto = bs->opaque;
+    int cur_nr_sectors; /* number of sectors in current iteration */
+    uint64_t bytes_done = 0;
+    uint8_t *cipher_data = NULL;
+    QEMUIOVector hd_qiov;
+    int ret = 0;
+    size_t payload_offset =
+        qcrypto_block_get_payload_offset(crypto->block) / 512;
+
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+
+    qemu_co_mutex_lock(&crypto->lock);
+
+    /* Bounce buffer so we have a linear mem region for
Quoted 8 lines

block/crypto.c line 406

Quoted 5 lines
block/crypto.c new file +5 -0
+     * entire sector. XXX optimize so we avoid bounce
+     * buffer in case that qiov->niov == 1
+     */
+    cipher_data =
+        qemu_try_blockalign(bs->file->bs, BLOCK_CRYPTO_MAX_SECTORS * 512);

As long as we create an individual buffer for each request, shouldn't MIN(BLOCK_CRYPTO_MAX_SECTORS * 512, qiov->size) be enough?

Yes, you're right. I didn't realize there was a pre-calcuated total size field in QEMUIOVector

Quoted 40 lines
Quoted 6 lines
block/crypto.c new file +6 -0
+    if (cipher_data == NULL) {
+        ret = -ENOMEM;
+        goto cleanup;
+    }
+
+    while (remaining_sectors) {

block/crypto.c line 422

Quoted 10 lines
block/crypto.c new file +10 -0
+        cur_nr_sectors = remaining_sectors;
+
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+
+        qemu_iovec_reset(&hd_qiov);
+        qemu_iovec_add(&hd_qiov, cipher_data, cur_nr_sectors * 512);
+
+        qemu_co_mutex_unlock(&crypto->lock);

Between qemu_co_mutex_lock() and here, there is no yield point...

block/crypto.c line 435

Quoted 13 lines
block/crypto.c new file +13 -0
+        ret = bdrv_co_readv(bs->file->bs,
+                            payload_offset + sector_num,
+                            cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        if (qcrypto_block_decrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;

Need a real -errno code here.

Review

Quoted 2 lines
(quoted diff) +2 -0
+            goto cleanup;
+        }

...nor is there one between here and the end of the function.

Quoted 8 lines
Quoted 4 lines

So what does this CoMutex protect? If qcrypto_block_decrypt() needs this for some reason (it doesn't seem to be touching anything that isn't per request, but maybe I'm missing something), would it be clearer to put the locking only around that call?

This just a result of me blindly copying the locking pattern from qcow2.c qcow2_co_readv() method without really understanding what it was protecting.

qcow2 protects a few fields in BDRVQcow2State and metadata that is used and possibly modified by requests. For example, after reading in some metadata, another request could make changes that invalidate it, and we need to protect against that.

I don't see that the crypto driver relies on any global (i.e. not per-request) state either in memory or on disk, except for things that are never changed after open, so the lock might not be needed.

Quoted 2 lines

If it not possible for two calls to bdrv_co_readv() to run in parallel, then I can drop this mutex.

They can. The obvious yield point where a coroutine switch can happen is the bdrv_co_readv() call above (but you already unlock for that one). Unless qcrypto_block_decrypt() does some I/O internally, we can't have any other yield points.

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
block/crypto.c new file +7 -0
+BlockDriver bdrv_crypto_luks = {
+    .format_name        = "luks",
+    .instance_size      = sizeof(BlockCrypto),
+    .bdrv_probe         = block_crypto_probe_luks,
+    .bdrv_open          = block_crypto_open_luks,
+    .bdrv_close         = block_crypto_close,
+    .bdrv_create        = block_crypto_create_luks,
Quoted 8 lines

block/crypto.c line 580

Quoted 6 lines
block/crypto.c new file +6 -0
+    .create_opts        = &block_crypto_create_opts_luks,
+
+    .bdrv_co_readv      = block_crypto_co_readv,
+    .bdrv_co_writev     = block_crypto_co_writev,
+    .bdrv_getlength     = block_crypto_getlength,
+};

Rather minimalistic, but we can always add the missing functions later.

Quoted 2 lines

Do you have any recommendations on which are top priority / important callbacks to add support for so I can prioritize future effort.

Hm... I was thinking of has_zero_init/discard/get_block_status, but I'm not sure how interesting that really is with encryption.

In theory, we could discard with undefined contents as the result, if we don't mind that we would be exposing that information (on the other hand, encrypted qcow2 images will expose it, too). And you have to enable unmap manually anyway.

Efficient zero write is out of question, I'm afraid.

The other thing that would be nice are several functions that provide information about the image, like refresh_limits, bdrv_info, etc.

Kevin

#11 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

Quoted 33 lines · Kevin Wolf

Am 18.03.2016 um 15:45 hat Daniel P. Berrange geschrieben:

Quoted 23 lines · Kevin Wolf
Quoted 22 lines

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

block/crypto.c line 435

Quoted 13 lines
block/crypto.c new file +13 -0
+        ret = bdrv_co_readv(bs->file->bs,
+                            payload_offset + sector_num,
+                            cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        if (qcrypto_block_decrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;

Need a real -errno code here.

Review

Quoted 2 lines
(quoted diff) +2 -0
+            goto cleanup;
+        }

...nor is there one between here and the end of the function.

Quoted 8 lines
Quoted 4 lines

So what does this CoMutex protect? If qcrypto_block_decrypt() needs this for some reason (it doesn't seem to be touching anything that isn't per request, but maybe I'm missing something), would it be clearer to put the locking only around that call?

This just a result of me blindly copying the locking pattern from qcow2.c qcow2_co_readv() method without really understanding what it was protecting.

Quoted 8 lines

qcow2 protects a few fields in BDRVQcow2State and metadata that is used and possibly modified by requests. For example, after reading in some metadata, another request could make changes that invalidate it, and we need to protect against that.

I don't see that the crypto driver relies on any global (i.e. not per-request) state either in memory or on disk, except for things that are never changed after open, so the lock might not be needed.

Actually it does have global state - the QCryptoCipher object that's into the QCryptoBlock object must not be used concurrently by multiple threads, as each thread will need to initialize different IV data.

Quoted 7 lines
Quoted 2 lines

If it not possible for two calls to bdrv_co_readv() to run in parallel, then I can drop this mutex.

They can. The obvious yield point where a coroutine switch can happen is the bdrv_co_readv() call above (but you already unlock for that one). Unless qcrypto_block_decrypt() does some I/O internally, we can't have any other yield points.

Ok, so we do need the mutex then to protect the cipher object state against concurrent use.

Quoted 27 lines
Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
block/crypto.c new file +7 -0
+BlockDriver bdrv_crypto_luks = {
+    .format_name        = "luks",
+    .instance_size      = sizeof(BlockCrypto),
+    .bdrv_probe         = block_crypto_probe_luks,
+    .bdrv_open          = block_crypto_open_luks,
+    .bdrv_close         = block_crypto_close,
+    .bdrv_create        = block_crypto_create_luks,
Quoted 8 lines

block/crypto.c line 580

Quoted 6 lines
block/crypto.c new file +6 -0
+    .create_opts        = &block_crypto_create_opts_luks,
+
+    .bdrv_co_readv      = block_crypto_co_readv,
+    .bdrv_co_writev     = block_crypto_co_writev,
+    .bdrv_getlength     = block_crypto_getlength,
+};

Rather minimalistic, but we can always add the missing functions later.

Quoted 2 lines

Do you have any recommendations on which are top priority / important callbacks to add support for so I can prioritize future effort.

Hm... I was thinking of has_zero_init/discard/get_block_status, but I'm not sure how interesting that really is with encryption.

In theory, we could discard with undefined contents as the result, if we don't mind that we would be exposing that information (on the other hand, encrypted qcow2 images will expose it, too). And you have to enable unmap manually anyway.

Quoted 4 lines

Efficient zero write is out of question, I'm afraid.

The other thing that would be nice are several functions that provide information about the image, like refresh_limits, bdrv_info, etc.

Ok, I'll have a look at these.

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#12 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

Quoted 50 lines · Daniel P. Berrange
Quoted 33 lines · Kevin Wolf

Am 18.03.2016 um 15:45 hat Daniel P. Berrange geschrieben:

Quoted 23 lines · Kevin Wolf
Quoted 22 lines

Am 17.03.2016 um 18:51 hat Daniel P. Berrange geschrieben:

block/crypto.c line 435

Quoted 13 lines
block/crypto.c new file +13 -0
+        ret = bdrv_co_readv(bs->file->bs,
+                            payload_offset + sector_num,
+                            cur_nr_sectors, &hd_qiov);
+        qemu_co_mutex_lock(&crypto->lock);
+        if (ret < 0) {
+            goto cleanup;
+        }
+
+        if (qcrypto_block_decrypt(crypto->block,
+                                  sector_num,
+                                  cipher_data, cur_nr_sectors * 512,
+                                  NULL) < 0) {
+            ret = -1;

Need a real -errno code here.

Review

Quoted 2 lines
(quoted diff) +2 -0
+            goto cleanup;
+        }

...nor is there one between here and the end of the function.

Quoted 8 lines
Quoted 4 lines

So what does this CoMutex protect? If qcrypto_block_decrypt() needs this for some reason (it doesn't seem to be touching anything that isn't per request, but maybe I'm missing something), would it be clearer to put the locking only around that call?

This just a result of me blindly copying the locking pattern from qcow2.c qcow2_co_readv() method without really understanding what it was protecting.

Quoted 8 lines

qcow2 protects a few fields in BDRVQcow2State and metadata that is used and possibly modified by requests. For example, after reading in some metadata, another request could make changes that invalidate it, and we need to protect against that.

I don't see that the crypto driver relies on any global (i.e. not per-request) state either in memory or on disk, except for things that are never changed after open, so the lock might not be needed.

Actually it does have global state - the QCryptoCipher object that's into the QCryptoBlock object must not be used concurrently by multiple threads, as each thread will need to initialize different IV data.

Quoted 3 lines
Quoted 2 lines

If it not possible for two calls to bdrv_co_readv() to run in parallel, then I can drop this mutex.

Quoted 7 lines
Quoted 4 lines

They can. The obvious yield point where a coroutine switch can happen is the bdrv_co_readv() call above (but you already unlock for that one). Unless qcrypto_block_decrypt() does some I/O internally, we can't have any other yield points.

Ok, so we do need the mutex then to protect the cipher object state against concurrent use.

Ignore this comment & the one above. Since we're using coroutines the qcrypto_block_decrypt() calls can't ever be running truely concurrently.

Regards,
Daniel

Signature · 4 lines
|: http://berrange.com      -o-    http://www.flickr.com/photos/dberrange/ :|
|: http://libvirt.org              -o-             http://virt-manager.org :|
|: http://autobuild.org       -o-         http://search.cpan.org/~danberr/ :|
|: http://entangle-photo.org       -o-       http://live.gnome.org/gtk-vnc :|
#13 lore raw

Re: [Qemu-devel] [PATCH v5 6/7] block: add generic full disk encryption driver

In reply to Kevin Wolf
Quoted 5 lines · Kevin Wolf
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines
block/crypto.c new file +4 -0
+    ov = opts_visitor_new(opts);
+
+    visit_start_struct(opts_get_visitor(ov),
+                       "luks", NULL, 0, &local_err);
Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

As this refers to "luks" specifically, shouldn't it be inside the switch below?

Or probably better if I just change it to "", since this parameter is not actually used in this context IIRC.

NULL then? It would be very obvious then if it were used against our expectations.

Yes, please. The QMP input visitor has a bug where passing non-NULL at the top-level visit can cause weird behavior with parsing an extra {}; I have patches to fix it, but in the meantime consistently passing NULL for the top-level visit is safest.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org