Skip to contentSkip to conversation

Support LUKS encryption in block devices

PATCH Superseded Daniel P. Berrange 3 participants 69 messages Jan 20, 2016 – Feb 9, 2016

Subsystems (3)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover Support LUKS encryption in block devices

This is a posting of the previously submitted work in progress code:

https://lists.gnu.org/archive/html/qemu-devel/2015-11/msg04748.html

This series depends on these previously submitted patches to the block tools:

https://lists.gnu.org/archive/html/qemu-devel/2015-12/msg04354.html

As can be guessed from the subject, the primary goal of this patch series is to support LUKS encryption in the QEMU block layer. QEMU has increasingly been adding native clients for network block protocols (RBD, gluster, NFS, iSCSI, etc) and apps like OpenStack are embracing them as it is much easier to deal with this from a management POV than to deal with the kernel block layer & userspace tools. Unfortunately when using QEMU native clients, apps are locked out of using dm-crypt and LUKS which is undesirable.

This series introduces two new features to the block layer. First there is a general purpose 'luks' format driver which can be layered over any other existing block driver. eg it can be layed above RBD, iSCSI, etc. Second the qcow2 file format is extended so that its embedded encryption can be replaced with the LUKS data format. While you could just layer the general purpose luks driver over qcow2, this is slightly less desirable, as it removes the ability to reliably auto-detect that LUKS is used by QEMU, as opposed to used by the guest OS. Having use of LUKS encoded in the qcow2 header addresses this.

The code is designed such that there is a strict separation between the full disk encryption format and the block I/O layer. Thus there is an generic API for dealing with full disk encryption added to the crypto/ subsystem. The block layer merely calls this FDE API when required, which serves to minimize the code present in the already complex block layer.

The first 5 patches add some supporting APIs to the crypto subsystem.

The 6-7 patches introduce the general full disk encryption API to the crypto subsystem and LUKS implementation

Patches 8-14 add the new 'luks' block driver format and convert qcow & qcow2 to the new FDE APIs, enabling LUKS in qcow2 (but not qcow) at the same time.

Patches 15-16 clean up the horrible password handling cruft in the block layer and monitor.

Patch 17 blocks use of the legacy qcow[2] encryption from the system emulators.

Still to do

- Add support for XTS cipher mode for dm-crypt compat

Changes since v1:

- Unit testing coverage of the full disk encryption APIs
- Functional testing of LUKS driver via the qemu-iotests for the block layer
- Use GNUTLS random API for the random byte source
- Use Makefile.objs for conditional compilation of pbkdf files (Fam)
- Use 'key-secret' instead of 'key-id' as property for decryption key (Paolo)
- Rename 'fde' to 'crypto' in block code (Kevin)
- Fix accounting of encryption header clusters when checking refcounts (Kevin)
- Rename format 'qcowaes' to 'qcow' (Eric)
- Fix qapi syntax for marking optional parameters (Eric)
- Add assertions in I/O path for BDRV_O_NO_IO flag
- Cleanup return codes / error reporting (Kevin)
- Other misc fixes identified in testing

Changes since WIP:

- QAPI parameters defined for the encryption key ID
- The qcow2 integration of LUKS is working, using extra allocated clusters to store LUKS header instead of trying to expand the main qcow2 header region to > 1 cluster
- qemu-img info now works without prompting for decryption password
- Unit testing of pbkdf2, afsplit and ivgen APis.

Daniel P. Berrange (17):
crypto: ensure qcrypto_hash_digest_len is always defined
crypto: add cryptographic random byte source
crypto: add support for PBKDF2 algorithm
crypto: add support for generating initialization vectors
crypto: add support for anti-forensic split algorithm
crypto: add block encryption framework
crypto: implement the LUKS block encryption format
block: add flag to indicate that no I/O will be performed qemu-img/qemu-io: don't prompt for passwords if not required
block: add generic full disk encryption driver
qcow2: make qcow2_encrypt_sectors encrypt in place
qcow2: convert QCow2 to use QCryptoBlock for encryption
qcow: make encrypt_sectors encrypt in place
qcow: convert QCow to use QCryptoBlock for encryption
block: rip out all traces of password prompting
block: remove all encryption handling APIs
block: remove support for legecy AES qcow/qcow2 encryption

 Makefile.objs                |    2 +-
 block.c                      |   99 +---
 block/Makefile.objs          |    2 +
 block/crypto.c               |  540 +++++++++++++++++++++
 block/io.c                   |    2 +
 block/qapi.c                 |    2 +-
 block/qcow.c                 |  195 ++++----
 block/qcow2-cluster.c        |   53 +-
 block/qcow2-refcount.c       |   10 +
 block/qcow2.c                |  510 ++++++++++++++++---
 block/qcow2.h                |   24 +-
 blockdev.c                   |   40 +-
 crypto/Makefile.objs         |   16 +
 crypto/afsplit.c             |  162 +++++++
 crypto/block-luks.c          | 1104 ++++++++++++++++++++++++++++++++++++++++++
 crypto/block-luks.h          |   28 ++
 crypto/block-qcow.c          |  167 +++++++
 crypto/block-qcow.h          |   28 ++
 crypto/block.c               |  265 ++++++++++
 crypto/blockpriv.h           |   90 ++++
 crypto/hash.c                |   30 +-
 crypto/ivgen-essiv.c         |  112 +++++
 crypto/ivgen-essiv.h         |   28 ++
 crypto/ivgen-plain.c         |   58 +++
 crypto/ivgen-plain.h         |   28 ++
 crypto/ivgen-plain64.c       |   58 +++
 crypto/ivgen-plain64.h       |   28 ++
 crypto/ivgen.c               |   98 ++++
 crypto/ivgenpriv.h           |   49 ++
 crypto/pbkdf-gcrypt.c        |   65 +++
 crypto/pbkdf-nettle.c        |   64 +++
 crypto/pbkdf-stub.c          |   41 ++
 crypto/pbkdf.c               |   68 +++
 crypto/random-gcrypt.c       |   33 ++
 crypto/random-gnutls.c       |   43 ++
 crypto/random-stub.c         |   31 ++
 docs/specs/qcow2.txt         |   74 +++
 hmp.c                        |   31 --
 hw/usb/dev-storage.c         |   34 --
 include/block/block.h        |    6 +-
 include/block/block_int.h    |    1 -
 include/crypto/afsplit.h     |  135 ++++++
 include/crypto/block.h       |  233 +++++++++
 include/crypto/ivgen.h       |  203 ++++++++
 include/crypto/pbkdf.h       |  152 ++++++
 include/crypto/random.h      |   43 ++
 include/monitor/monitor.h    |    7 -
 include/qemu/osdep.h         |    2 -
 monitor.c                    |   68 ---
 qapi/block-core.json         |   41 +-
 qapi/crypto.json             |  120 +++++
 qemu-img.c                   |   45 +-
 qemu-io.c                    |   21 -
 qmp.c                        |    9 -
 tests/.gitignore             |    4 +
 tests/Makefile               |    8 +
 tests/qemu-iotests/049       |    2 +-
 tests/qemu-iotests/049.out   |   10 +-
 tests/qemu-iotests/082.out   |  189 ++++++++
 tests/qemu-iotests/087       |   30 +-
 tests/qemu-iotests/087.out   |   28 +-
 tests/qemu-iotests/134       |   18 +-
 tests/qemu-iotests/134.out   |   33 +-
 tests/qemu-iotests/common    |    1 +
 tests/qemu-iotests/common.rc |    4 +-
 tests/test-crypto-afsplit.c  |  176 +++++++
 tests/test-crypto-block.c    |  343 +++++++++++++
 tests/test-crypto-ivgen.c    |  168 +++++++
 tests/test-crypto-pbkdf.c    |  378 +++++++++++++++
 util/oslib-posix.c           |   66 ---
 util/oslib-win32.c           |   24 -
 71 files changed, 6128 insertions(+), 752 deletions(-)
 create mode 100644 block/crypto.c
 create mode 100644 crypto/afsplit.c
 create mode 100644 crypto/block-luks.c
 create mode 100644 crypto/block-luks.h
 create mode 100644 crypto/block-qcow.c
 create mode 100644 crypto/block-qcow.h
 create mode 100644 crypto/block.c
 create mode 100644 crypto/blockpriv.h
 create mode 100644 crypto/ivgen-essiv.c
 create mode 100644 crypto/ivgen-essiv.h
 create mode 100644 crypto/ivgen-plain.c
 create mode 100644 crypto/ivgen-plain.h
 create mode 100644 crypto/ivgen-plain64.c
 create mode 100644 crypto/ivgen-plain64.h
 create mode 100644 crypto/ivgen.c
 create mode 100644 crypto/ivgenpriv.h
 create mode 100644 crypto/pbkdf-gcrypt.c
 create mode 100644 crypto/pbkdf-nettle.c
 create mode 100644 crypto/pbkdf-stub.c
 create mode 100644 crypto/pbkdf.c
 create mode 100644 crypto/random-gcrypt.c
 create mode 100644 crypto/random-gnutls.c
 create mode 100644 crypto/random-stub.c
 create mode 100644 include/crypto/afsplit.h
 create mode 100644 include/crypto/block.h
 create mode 100644 include/crypto/ivgen.h
 create mode 100644 include/crypto/pbkdf.h
 create mode 100644 include/crypto/random.h
 create mode 100644 tests/test-crypto-afsplit.c
 create mode 100644 tests/test-crypto-block.c
 create mode 100644 tests/test-crypto-ivgen.c
 create mode 100644 tests/test-crypto-pbkdf.c
Signature · 1 line
2.5.0
#1 lore raw

PATCH v2 1/17 crypto: ensure qcrypto_hash_digest_len is always defined

The qcrypto_hash_digest_len method was accidentally inside a CONFIG_GNUTLS_HASH block, even though it doesn't depend on gnutls. Re-arrange it to be unconditionally defined.

---
 crypto/hash.c | 30 +++++++++++++++++-------------
 1 file changed, 17 insertions(+), 13 deletions(-)
crypto/hash.c +17 -13
index 6e83f43..24cabd5 100644
@@ -23,12 +23,8 @@
 #ifdef CONFIG_GNUTLS_HASH
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
+#endif
 
-static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
-    [QCRYPTO_HASH_ALG_MD5] = GNUTLS_DIG_MD5,
-    [QCRYPTO_HASH_ALG_SHA1] = GNUTLS_DIG_SHA1,
-    [QCRYPTO_HASH_ALG_SHA256] = GNUTLS_DIG_SHA256,
-};
 
 static size_t qcrypto_hash_alg_size[QCRYPTO_HASH_ALG__MAX] = {
     [QCRYPTO_HASH_ALG_MD5] = 16,
@@ -36,14 +32,6 @@ static size_t qcrypto_hash_alg_size[QCRYPTO_HASH_ALG__MAX] = {
     [QCRYPTO_HASH_ALG_SHA256] = 32,
 };
 
-gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)
-{
-    if (alg < G_N_ELEMENTS(qcrypto_hash_alg_map)) {
-        return true;
-    }
-    return false;
-}
-
 size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg)
 {
     if (alg >= G_N_ELEMENTS(qcrypto_hash_alg_size)) {
@@ -53,6 +41,22 @@ size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg)
 }
 
 
+#ifdef CONFIG_GNUTLS_HASH
+static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
+    [QCRYPTO_HASH_ALG_MD5] = GNUTLS_DIG_MD5,
+    [QCRYPTO_HASH_ALG_SHA1] = GNUTLS_DIG_SHA1,
+    [QCRYPTO_HASH_ALG_SHA256] = GNUTLS_DIG_SHA256,
+};
+
+gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)
+{
+    if (alg < G_N_ELEMENTS(qcrypto_hash_alg_map)) {
+        return true;
+    }
+    return false;
+}
+
+
 int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
                         const struct iovec *iov,
                         size_t niov,
Signature · 1 line
2.5.0
Reviewed-by on v2 1/17
#2 lore raw

Re: [Qemu-devel] [PATCH v2 01/17] crypto: ensure qcrypto_hash_digest_len is always defined

Quoted 5 lines · Daniel P. Berrange

The qcrypto_hash_digest_len method was accidentally inside a CONFIG_GNUTLS_HASH block, even though it doesn't depend on gnutls. Re-arrange it to be unconditionally defined.

#3 lore raw

PATCH v2 2/17 crypto: add cryptographic random byte source

In reply to Daniel P. Berrange

There are three backend impls provided. The preferred is gnutls, which is backed by nettle in modern distros. The gcrypt impl is provided for cases where QEMU build against gnutls is disabled, but crypto is still desired. No nettle impl is provided, since it is non-trivial to use the nettle APIs for random numbers. Users of nettle should ensure gnutls is enabled for QEMU.

---
 Makefile.objs           |  2 +-
 crypto/Makefile.objs    |  4 ++++
 crypto/random-gcrypt.c  | 33 +++++++++++++++++++++++++++++++++
 crypto/random-gnutls.c  | 43 +++++++++++++++++++++++++++++++++++++++++++
 crypto/random-stub.c    | 31 +++++++++++++++++++++++++++++++
 include/crypto/random.h | 43 +++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 155 insertions(+), 1 deletion(-)
 create mode 100644 crypto/random-gcrypt.c
 create mode 100644 crypto/random-gnutls.c
 create mode 100644 crypto/random-stub.c
 create mode 100644 include/crypto/random.h
Makefile.objs +1 -1
index 06b95c7..8b52f33 100644
@@ -1,6 +1,6 @@
 #######################################################################
 # Common libraries for tools and emulators
-stub-obj-y = stubs/
+stub-obj-y = stubs/ crypto/
 util-obj-y = util/ qobject/ qapi/
 util-obj-y += qmp-introspect.o qapi-types.o qapi-visit.o qapi-event.o
 
crypto/Makefile.objs +4 -0
index a3135f1..1802ff5 100644
@@ -8,6 +8,10 @@ crypto-obj-y += tlscredsanon.o
 crypto-obj-y += tlscredsx509.o
 crypto-obj-y += tlssession.o
 crypto-obj-y += secret.o
+crypto-obj-$(if $(CONFIG_GNUTLS),n,$(CONFIG_GCRYPT)) += random-gcrypt.o
+crypto-obj-$(CONFIG_GNUTLS) += random-gnutls.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
+
+stub-obj-y += random-stub.o
\ No newline at end of file
crypto/random-gcrypt.c new file +33 -0
new file mode 100644
index 0000000..a2d77db
@@ -0,0 +1,33 @@
+/*
+ * QEMU Crypto random number provider
+ *
+ * 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 <config-host.h>
+
+#include "crypto/random.h"
+
+#include <gcrypt.h>
+
+int qcrypto_random_bytes(uint8_t *buf,
+                         size_t buflen,
+                         Error **errp G_GNUC_UNUSED)
+{
+    gcry_randomize(buf, buflen, GCRY_STRONG_RANDOM);
+    return 0;
+}
crypto/random-gnutls.c new file +43 -0

43 lines not on this page · raw message

crypto/random-stub.c new file +31 -0
new file mode 100644
index 0000000..5c2a4e1
@@ -0,0 +1,31 @@
+/*
+ * QEMU Crypto random number provider
+ *
+ * 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 <config-host.h>
+
+#include "crypto/random.h"
+
+int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
+                         size_t buflen G_GNUC_UNUSED,
+                         Error **errp)
+{
+    error_setg(errp, "No random byte source provided in this build");
+    return -1;
+}
include/crypto/random.h new file +43 -0

43 lines not on this page · raw message

Signature · 1 line
2.5.0
Reviewed-by on v2 2/17
#4 lore raw

Re: [Qemu-devel] [PATCH v2 02/17] crypto: add cryptographic random byte source

crypto/random-stub.c line 30

Quoted 6 lines · Daniel P. Berrange
crypto/random-stub.c new file +6 -0
+int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
+                         size_t buflen G_GNUC_UNUSED,
+                         Error **errp)
+{
+    error_setg(errp, "No random byte source provided in this build");
+    return -1;

Curious, why does a random(3) or /dev/random implementation fall short to error?

Regardlessly,

#5 lore raw

Re: [Qemu-devel] [PATCH v2 02/17] crypto: add cryptographic random byte source

Quoted 10 lines · Fam Zheng

crypto/random-stub.c line 30

Quoted 6 lines · Daniel P. Berrange
crypto/random-stub.c new file +6 -0
+int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
+                         size_t buflen G_GNUC_UNUSED,
+                         Error **errp)
+{
+    error_setg(errp, "No random byte source provided in this build");
+    return -1;

Curious, why does a random(3) or /dev/random implementation fall short to error?

random(3) does not provide crytographically strong random numbers.

/dev/random would be suitable, but if we read that directly we would deplete entropy very quickly.

The gnutls backends will use /dev/random in combination with a cryptographically secure generator to provide high entropy numbers, at a high data rate.

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 :|
Reviewed-by on v2 2/17
#6 lore raw

Re: [Qemu-devel] [PATCH v2 02/17] crypto: add cryptographic random byte source

In reply to Daniel P. Berrange
Quoted 14 lines · Daniel P. Berrange

There are three backend impls provided. The preferred is gnutls, which is backed by nettle in modern distros. The gcrypt impl is provided for cases where QEMU build against gnutls is disabled, but crypto is still desired. No nettle impl is provided, since it is non-trivial to use the nettle APIs for random numbers. Users of nettle should ensure gnutls is enabled for QEMU.

---

+++ b/crypto/Makefile.objs

crypto/Makefile.objs +0 -0
@@ -8,6 +8,10 @@ crypto-obj-y += tlscredsanon.o
 crypto-obj-y += tlscredsx509.o

crypto/Makefile.objs crypto-obj-y += tlscredsanon.o · line 17

Quoted 10 lines
crypto/Makefile.objs +4 -0
 crypto-obj-y += tlssession.o
 crypto-obj-y += secret.o
+crypto-obj-$(if $(CONFIG_GNUTLS),n,$(CONFIG_GCRYPT)) += random-gcrypt.o
+crypto-obj-$(CONFIG_GNUTLS) += random-gnutls.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
+
+stub-obj-y += random-stub.o
\ No newline at end of file

You'll want to fix that newline.

Review

Quoted 4 lines

+++ b/crypto/random-gcrypt.c

(quoted diff) +2 -0
+
+#include <config-host.h>

Now that we are starting to include "qemu/osdep.h" first everywhere, you'll want to pick that up on rebase.

include/crypto/random.h line 34

Quoted 10 lines

+++ b/include/crypto/random.h

include/crypto/random.h new file +8 -0
+
+/**
+ * qcrypto_random_bytes:
+ * @buf: the buffer to fill
+ * @buflen: length of @buf in bytes
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Fill @buf with @buflen bytes of random data

s/of/of cryptographically strong/

include/crypto/random.h line 41

Quoted 7 lines

+ *
+ * Returns 0 on sucess, -1 on error
+ */

include/crypto/random.h new file +4 -0
+int qcrypto_random_bytes(uint8_t *buf,
+                         size_t buflen,
+                         Error **errp);
+

With those tweaks,

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

PATCH v2 3/17 crypto: add support for PBKDF2 algorithm

In reply to Daniel P. Berrange

The LUKS data format includes use of PBKDF2 (Password-Based Key Derivation Function). The Nettle library can provide an implementation of this, but we don't want code directly depending on a specific crypto library backend. Introduce a include/crypto/pbkdf.h header which defines a QEMU API for invoking PBKDK2. The initial implementations are backed by nettle & gcrypt, which are commonly available with distros shipping GNUTLS.

The test suite data is taken from the cryptsetup codebase under the LGPLv2.1+ license. This merely aims to verify that whatever backend we provide for this function in QEMU will comply with the spec.

---
 crypto/Makefile.objs      |   6 +-
 crypto/pbkdf-gcrypt.c     |  65 ++++++++
 crypto/pbkdf-nettle.c     |  64 ++++++++
 crypto/pbkdf-stub.c       |  41 +++++
 crypto/pbkdf.c            |  68 +++++++++
 include/crypto/pbkdf.h    | 152 +++++++++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-pbkdf.c | 378 ++++++++++++++++++++++++++++++++++++++++++++++
 9 files changed, 776 insertions(+), 1 deletion(-)
 create mode 100644 crypto/pbkdf-gcrypt.c
 create mode 100644 crypto/pbkdf-nettle.c
 create mode 100644 crypto/pbkdf-stub.c
 create mode 100644 crypto/pbkdf.c
 create mode 100644 include/crypto/pbkdf.h
 create mode 100644 tests/test-crypto-pbkdf.c
crypto/Makefile.objs +5 -1
index 1802ff5..4d2cd3e 100644
@@ -10,8 +10,12 @@ crypto-obj-y += tlssession.o
 crypto-obj-y += secret.o
 crypto-obj-$(if $(CONFIG_GNUTLS),n,$(CONFIG_GCRYPT)) += random-gcrypt.o
 crypto-obj-$(CONFIG_GNUTLS) += random-gnutls.o
+crypto-obj-y += pbkdf.o
+crypto-obj-$(CONFIG_NETTLE) += pbkdf-nettle.o
+crypto-obj-$(if $(CONFIG_NETTLE),n,$(CONFIG_GCRYPT)) += pbkdf-gcrypt.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
 
-stub-obj-y += random-stub.o
\ No newline at end of file
+stub-obj-y += random-stub.o
+stub-obj-y += pbkdf-stub.o
crypto/pbkdf-gcrypt.c new file +65 -0

65 lines not on this page · raw message

crypto/pbkdf-nettle.c new file +64 -0

64 lines not on this page · raw message

crypto/pbkdf-stub.c new file +41 -0

41 lines not on this page · raw message

crypto/pbkdf.c new file +68 -0

68 lines not on this page · raw message

include/crypto/pbkdf.h new file +152 -0

152 lines not on this page · raw message

tests/.gitignore +1 -0
index 787c95c..db6b9be 100644
@@ -14,6 +14,7 @@ test-blockjob-txn
 test-coroutine
 test-crypto-cipher
 test-crypto-hash
+test-crypto-pbkdf
 test-crypto-secret
 test-crypto-tlscredsx509
 test-crypto-tlscredsx509-work/
tests/Makefile +2 -0
index b7352f1..833a290 100644
@@ -92,6 +92,7 @@ check-unit-$(CONFIG_GNUTLS) += tests/test-io-channel-tls$(EXESUF)
 check-unit-y += tests/test-io-channel-command$(EXESUF)
 check-unit-y += tests/test-io-channel-buffer$(EXESUF)
 check-unit-y += tests/test-base64$(EXESUF)
+check-unit-y += tests/test-crypto-pbkdf$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -495,6 +496,7 @@ tests/test-io-channel-command$(EXESUF): tests/test-io-channel-command.o \
         tests/io-channel-helpers.o $(test-io-obj-y)
 tests/test-io-channel-buffer$(EXESUF): tests/test-io-channel-buffer.o \
         tests/io-channel-helpers.o $(test-io-obj-y)
+tests/test-crypto-pbkdf$(EXESUF): tests/test-crypto-pbkdf.o $(test-crypto-obj-y)
 
 libqos-obj-y = tests/libqos/pci.o tests/libqos/fw_cfg.o tests/libqos/malloc.o
 libqos-obj-y += tests/libqos/i2c.o tests/libqos/libqos.o
tests/test-crypto-pbkdf.c new file +378 -0

378 lines not on this page · raw message

Signature · 1 line
2.5.0
#8 lore raw

Re: [Qemu-devel] [PATCH v2 03/17] crypto: add support for PBKDF2 algorithm

Quoted 97 lines · Daniel P. Berrange

The LUKS data format includes use of PBKDF2 (Password-Based Key Derivation Function). The Nettle library can provide an implementation of this, but we don't want code directly depending on a specific crypto library backend. Introduce a include/crypto/pbkdf.h header which defines a QEMU API for invoking PBKDK2. The initial implementations are backed by nettle & gcrypt, which are commonly available with distros shipping GNUTLS.

The test suite data is taken from the cryptsetup codebase under the LGPLv2.1+ license. This merely aims to verify that whatever backend we provide for this function in QEMU will comply with the spec.

---
 crypto/Makefile.objs      |   6 +-
 crypto/pbkdf-gcrypt.c     |  65 ++++++++
 crypto/pbkdf-nettle.c     |  64 ++++++++
 crypto/pbkdf-stub.c       |  41 +++++
 crypto/pbkdf.c            |  68 +++++++++
 include/crypto/pbkdf.h    | 152 +++++++++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-pbkdf.c | 378 ++++++++++++++++++++++++++++++++++++++++++++++
 9 files changed, 776 insertions(+), 1 deletion(-)
 create mode 100644 crypto/pbkdf-gcrypt.c
 create mode 100644 crypto/pbkdf-nettle.c
 create mode 100644 crypto/pbkdf-stub.c
 create mode 100644 crypto/pbkdf.c
 create mode 100644 include/crypto/pbkdf.h
 create mode 100644 tests/test-crypto-pbkdf.c
crypto/Makefile.objs +5 -1
index 1802ff5..4d2cd3e 100644
@@ -10,8 +10,12 @@ crypto-obj-y += tlssession.o
 crypto-obj-y += secret.o
 crypto-obj-$(if $(CONFIG_GNUTLS),n,$(CONFIG_GCRYPT)) += random-gcrypt.o
 crypto-obj-$(CONFIG_GNUTLS) += random-gnutls.o
+crypto-obj-y += pbkdf.o
+crypto-obj-$(CONFIG_NETTLE) += pbkdf-nettle.o
+crypto-obj-$(if $(CONFIG_NETTLE),n,$(CONFIG_GCRYPT)) += pbkdf-gcrypt.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
 
-stub-obj-y += random-stub.o
\ No newline at end of file
+stub-obj-y += random-stub.o
+stub-obj-y += pbkdf-stub.o
crypto/pbkdf-gcrypt.c new file +39 -0
new file mode 100644
index 0000000..94abcf8
@@ -0,0 +1,65 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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 "crypto/pbkdf.h"
+#include "gcrypt.h"
+
+bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
+{
+    switch (hash) {
+    case QCRYPTO_HASH_ALG_SHA1:
+    case QCRYPTO_HASH_ALG_SHA256:
+        return true;
+    default:
+        return false;
+    }
+}
+
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,

crypto/pbkdf-gcrypt.c line 49

Quoted 10 lines
crypto/pbkdf-gcrypt.c new file +10 -0
+                   Error **errp)
+{
+    static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
+        [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
+        [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
+        [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
+    };
+    int ret;
+
+    if (hash > G_N_ELEMENTS(hash_map)) {

Do you want ">="?

crypto/pbkdf-gcrypt.c line 57

Quoted 8 lines
crypto/pbkdf-gcrypt.c new file +8 -0
+        error_setg(errp, "Unexpected hash algorithm %d", hash);
+        return -1;
+    }
+
+    ret = gcry_kdf_derive(key, nkey, GCRY_KDF_PBKDF2,
+                          hash_map[hash],
+                          salt, nsalt, iterations,
+                          nout, out);

We go ahead with QCRYPTO_HASH_ALG_MD5 here, but we didn't accept it in qcrypto_pbkdf2_supports, is that a mistake?

Quoted 97 lines
crypto/pbkdf-gcrypt.c new file +8 -0
+    if (ret != 0) {
+        error_setg(errp, "Cannot derive password: %s",
+                   gcry_strerror(ret));
+        return -1;
+    }
+
+    return 0;
+}
crypto/pbkdf-nettle.c new file +64 -0
new file mode 100644
index 0000000..b0f2d8e
@@ -0,0 +1,64 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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 "crypto/pbkdf.h"
+#include "nettle/pbkdf2.h"
+
+
+bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
+{
+    switch (hash) {
+    case QCRYPTO_HASH_ALG_SHA1:
+    case QCRYPTO_HASH_ALG_SHA256:
+        return true;
+    default:
+        return false;
+    }
+}
+
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp)
+{
+    switch (hash) {
+    case QCRYPTO_HASH_ALG_SHA1:
+        pbkdf2_hmac_sha1(nkey, key,
+                         iterations,
+                         nsalt, salt,
+                         nout, out);
+        break;
+
+    case QCRYPTO_HASH_ALG_SHA256:
+        pbkdf2_hmac_sha256(nkey, key,
+                           iterations,
+                           nsalt, salt,
+                           nout, out);
+        break;
+
+    default:
+        error_setg_errno(errp, ENOSYS,
+                         "PBKDF does not support hash algorithm %d", hash);
+        return -1;
+    }
+    return 0;
+}
crypto/pbkdf-stub.c new file +13 -0
new file mode 100644
index 0000000..73a08c3
@@ -0,0 +1,41 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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

crypto/pbkdf-stub.c line 23

Quoted 10 lines
crypto/pbkdf-stub.c new file +10 -0
+ * 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 "crypto/pbkdf.h"
+
+bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)

Missing G_GNUC_UNUSED to be consistent with the rest of the file, doesn't hurt though.

Quoted 45 lines
crypto/pbkdf-stub.c new file +18 -0
+{
+    return false;
+}
+
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash G_GNUC_UNUSED,
+                   const uint8_t *key G_GNUC_UNUSED,
+                   size_t nkey G_GNUC_UNUSED,
+                   const uint8_t *salt G_GNUC_UNUSED,
+                   size_t nsalt G_GNUC_UNUSED,
+                   unsigned int iterations G_GNUC_UNUSED,
+                   uint8_t *out G_GNUC_UNUSED,
+                   size_t nout G_GNUC_UNUSED,
+                   Error **errp)
+{
+    error_setg_errno(errp, ENOSYS,
+                     "No crypto library supporting PBKDF in this build");
+    return -1;
+}
crypto/pbkdf.c new file +21 -0
new file mode 100644
index 0000000..71f96cd
@@ -0,0 +1,68 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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 "crypto/pbkdf.h"

crypto/pbkdf.c line 31

Quoted 10 lines
crypto/pbkdf.c new file +10 -0
+#include <sys/resource.h>
+
+
+int qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash,
+                               const uint8_t *key, size_t nkey,
+                               const uint8_t *salt, size_t nsalt,
+                               Error **errp)
+{
+    uint8_t out[32];
+    int iterations = (1 << 15);

To be safe from overflow, I'd use at least 64 bits to do the math, just in case that some machine is too good at computing this stuff. :)

Quoted 65 lines
crypto/pbkdf.c new file +37 -0
+    struct rusage start, end;
+    unsigned long long delta;
+
+    while (1) {
+        if (getrusage(RUSAGE_THREAD, &start) < 0) {
+            error_setg_errno(errp, errno, "Unable to get thread CPU usage");
+            return -1;
+        }
+        if (qcrypto_pbkdf2(hash,
+                           key, nkey,
+                           salt, nsalt,
+                           iterations,
+                           out, sizeof(out),
+                           errp) < 0) {
+            return -1;
+        }
+        if (getrusage(RUSAGE_THREAD, &end) < 0) {
+            error_setg_errno(errp, errno, "Unable to get thread CPU usage");
+            return -1;
+        }
+
+        delta = (((end.ru_utime.tv_sec * 1000ll) +
+                  (end.ru_utime.tv_usec / 1000)) -
+                 ((start.ru_utime.tv_sec * 1000ll) +
+                  (start.ru_utime.tv_usec / 1000)));
+
+        if (delta > 500) {
+            break;
+        } else if (delta < 100) {
+            iterations = iterations * 10;
+        } else {
+            iterations = (iterations * 1000 / delta);
+        }
+    }
+
+    return iterations * 1000 / delta;
+}
include/crypto/pbkdf.h new file +22 -0
new file mode 100644
index 0000000..a5e8267
@@ -0,0 +1,152 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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/>.
+ *
+ */
+
+#ifndef QCRYPTO_PBKDF_H__
+#define QCRYPTO_PBKDF_H__

include/crypto/pbkdf.h line 32

Quoted 10 lines
include/crypto/pbkdf.h new file +10 -0
+
+#include "crypto/hash.h"
+
+/**
+ * This module provides an interface to the PBKDF2 algorithm
+ *
+ *   https://en.wikipedia.org/wiki/PBKDF2
+ *
+ * <example>
+ *   <title>Generating a AES encryption key from a user password</title>

s/a AES/an AES/ ?

Quoted 1 line
include/crypto/pbkdf.h new file +1 -0
+ *   <programlisting>
#9 lore raw

Re: [Qemu-devel] [PATCH v2 03/17] crypto: add support for PBKDF2 algorithm

Quoted 43 lines · Fam Zheng
Quoted 42 lines · Daniel P. Berrange

The LUKS data format includes use of PBKDF2 (Password-Based Key Derivation Function). The Nettle library can provide an implementation of this, but we don't want code directly depending on a specific crypto library backend. Introduce a include/crypto/pbkdf.h header which defines a QEMU API for invoking PBKDK2. The initial implementations are backed by nettle & gcrypt, which are commonly available with distros shipping GNUTLS.

The test suite data is taken from the cryptsetup codebase under the LGPLv2.1+ license. This merely aims to verify that whatever backend we provide for this function in QEMU will comply with the spec.

---
 crypto/Makefile.objs      |   6 +-
 crypto/pbkdf-gcrypt.c     |  65 ++++++++
 crypto/pbkdf-nettle.c     |  64 ++++++++
 crypto/pbkdf-stub.c       |  41 +++++
 crypto/pbkdf.c            |  68 +++++++++
 include/crypto/pbkdf.h    | 152 +++++++++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-pbkdf.c | 378 ++++++++++++++++++++++++++++++++++++++++++++++
 9 files changed, 776 insertions(+), 1 deletion(-)
 create mode 100644 crypto/pbkdf-gcrypt.c
 create mode 100644 crypto/pbkdf-nettle.c
 create mode 100644 crypto/pbkdf-stub.c
 create mode 100644 crypto/pbkdf.c
 create mode 100644 include/crypto/pbkdf.h
 create mode 100644 tests/test-crypto-pbkdf.c
crypto/pbkdf-gcrypt.c new file +9 -0
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp)
+{
+    static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
+        [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
Quoted 8 lines

crypto/pbkdf-gcrypt.c line 49

Quoted 6 lines
crypto/pbkdf-gcrypt.c new file +6 -0
+        [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
+        [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
+    };
+    int ret;
+
+    if (hash > G_N_ELEMENTS(hash_map)) {

Do you want ">="?

Yes.

Quoted 10 lines

crypto/pbkdf-gcrypt.c line 57

Quoted 9 lines
crypto/pbkdf-gcrypt.c new file +8 -0
+        error_setg(errp, "Unexpected hash algorithm %d", hash);
+        return -1;
+    }
+
+    ret = gcry_kdf_derive(key, nkey, GCRY_KDF_PBKDF2,
+                          hash_map[hash],
+                          salt, nsalt, iterations,
+                          nout, out);
Quoted 2 lines

We go ahead with QCRYPTO_HASH_ALG_MD5 here, but we didn't accept it in qcrypto_pbkdf2_supports, is that a mistake?

Yes, I should have reported MD5 in the earlier function, since gcrypt allows that.

Quoted 32 lines
Quoted 32 lines
crypto/pbkdf.c new file +26 -0
new file mode 100644
index 0000000..71f96cd
@@ -0,0 +1,68 @@
+/*
+ * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
+ *
+ * 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 "crypto/pbkdf.h"
+#include <sys/resource.h>
+
+
+int qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash,
+                               const uint8_t *key, size_t nkey,
Quoted 8 lines

crypto/pbkdf.c line 31

Quoted 5 lines
crypto/pbkdf.c new file +5 -0
+                               const uint8_t *salt, size_t nsalt,
+                               Error **errp)
+{
+    uint8_t out[32];
+    int iterations = (1 << 15);

To be safe from overflow, I'd use at least 64 bits to do the math, just in case that some machine is too good at computing this stuff. :)

Hmm, probably need to change the return type to be 64 bit too then

Quoted 39 lines
Quoted 39 lines
crypto/pbkdf.c new file +38 -0
+    struct rusage start, end;
+    unsigned long long delta;
+
+    while (1) {
+        if (getrusage(RUSAGE_THREAD, &start) < 0) {
+            error_setg_errno(errp, errno, "Unable to get thread CPU usage");
+            return -1;
+        }
+        if (qcrypto_pbkdf2(hash,
+                           key, nkey,
+                           salt, nsalt,
+                           iterations,
+                           out, sizeof(out),
+                           errp) < 0) {
+            return -1;
+        }
+        if (getrusage(RUSAGE_THREAD, &end) < 0) {
+            error_setg_errno(errp, errno, "Unable to get thread CPU usage");
+            return -1;
+        }
+
+        delta = (((end.ru_utime.tv_sec * 1000ll) +
+                  (end.ru_utime.tv_usec / 1000)) -
+                 ((start.ru_utime.tv_sec * 1000ll) +
+                  (start.ru_utime.tv_usec / 1000)));
+
+        if (delta > 500) {
+            break;
+        } else if (delta < 100) {
+            iterations = iterations * 10;
+        } else {
+            iterations = (iterations * 1000 / delta);
+        }
+    }
+
+    return iterations * 1000 / delta;
+}
+/**
Quoted 8 lines
Quoted 6 lines

+ * This module provides an interface to the PBKDF2 algorithm
+ *
+ * https://en.wikipedia.org/wiki/PBKDF2
+ *
+ * <example>
+ * <title>Generating a AES encryption key from a user password</title>

s/a AES/an AES/ ?

Yes

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 v2 03/17] crypto: add support for PBKDF2 algorithm

In reply to Daniel P. Berrange
Quoted 5 lines · Daniel P. Berrange

The LUKS data format includes use of PBKDF2 (Password-Based Key Derivation Function). The Nettle library can provide an implementation of this, but we don't want code directly depending on a specific crypto library backend. Introduce a include/crypto/pbkdf.h header which defines a QEMU

'an include/...', or maybe 'a new include/...'?

Quoted 11 lines

API for invoking PBKDK2. The initial implementations are backed by nettle & gcrypt, which are commonly available with distros shipping GNUTLS.

The test suite data is taken from the cryptsetup codebase under the LGPLv2.1+ license. This merely aims to verify that whatever backend we provide for this function in QEMU will comply with the spec.

---

In addition to Fam's review,

Quoted 4 lines

+++ b/crypto/pbkdf-gcrypt.c

crypto/pbkdf-gcrypt.c new file +2 -0
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,

crypto/pbkdf-gcrypt.c line 46

Quoted 10 lines
crypto/pbkdf-gcrypt.c new file +10 -0
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp)
+{
+    static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
+        [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
+        [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
+        [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
+    };

If QCRYPTO_HASH_ gains future enum values, those elements of the array will be 0-initialized.

crypto/pbkdf-gcrypt.c line 52

Quoted 6 lines
crypto/pbkdf-gcrypt.c new file +6 -0
+    int ret;
+
+    if (hash > G_N_ELEMENTS(hash_map)) {
+        error_setg(errp, "Unexpected hash algorithm %d", hash);
+        return -1;
+    }

This checks for beyond the bounds of the array, but not for an element that was 0-initialized. Is that a problem we need to worry about?

Quoted 12 lines
include/crypto/pbkdf.h new file +12 -0
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp);
+
+/**
+ * qcrypto_pbkdf2_count_iters:
+ * @hash: the hash algorithm to use
+ * @key: the user password / key
+ * @nkey: the length of @key in bytes

include/crypto/pbkdf.h line 143

Quoted 10 lines
include/crypto/pbkdf.h new file +10 -0
+ * @salt: a random salt
+ * @nsalt: length of @salt in bytes
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Time the PBKDF2 algorithm to determine how many
+ * iterations are required to derive an encryption
+ * key from a user password provided in @key in 1
+ * second of compute time. The result of this can
+ * be used as a the @iterations parameter of a later
+ * call to qcrypto_pbkdf2().

As machines get faster, will 2^31 still be enough, or do we want a 64-bit iterations counter?

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

Re: [Qemu-devel] [PATCH v2 03/17] crypto: add support for PBKDF2 algorithm

Quoted 18 lines · Eric Blake
Quoted 17 lines · Daniel P. Berrange
include/crypto/pbkdf.h new file +17 -0
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp);
+
+/**
+ * qcrypto_pbkdf2_count_iters:
+ * @hash: the hash algorithm to use
+ * @key: the user password / key
+ * @nkey: the length of @key in bytes
+ * @salt: a random salt
+ * @nsalt: length of @salt in bytes
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Time the PBKDF2 algorithm to determine how many
Quoted 8 lines
Quoted 5 lines

+ * iterations are required to derive an encryption
+ * key from a user password provided in @key in 1
+ * second of compute time. The result of this can
+ * be used as a the @iterations parameter of a later
+ * call to qcrypto_pbkdf2().

As machines get faster, will 2^31 still be enough, or do we want a 64-bit iterations counter?

The luks format only has space to store a 32-bit int for interations, so 64-bit would require an on disk format change. On my current modern laptop we're getting iteration counts in the 400,000 range, so it will be a decent while before we hit 2^31, by which time LUKS maintainers will have to do a format change.

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 v2 03/17] crypto: add support for PBKDF2 algorithm

In reply to Eric Blake
Quoted 48 lines · Eric Blake
Quoted 5 lines · Daniel P. Berrange

The LUKS data format includes use of PBKDF2 (Password-Based Key Derivation Function). The Nettle library can provide an implementation of this, but we don't want code directly depending on a specific crypto library backend. Introduce a include/crypto/pbkdf.h header which defines a QEMU

'an include/...', or maybe 'a new include/...'?

Quoted 11 lines

API for invoking PBKDK2. The initial implementations are backed by nettle & gcrypt, which are commonly available with distros shipping GNUTLS.

The test suite data is taken from the cryptsetup codebase under the LGPLv2.1+ license. This merely aims to verify that whatever backend we provide for this function in QEMU will comply with the spec.

---

In addition to Fam's review,

Quoted 4 lines

+++ b/crypto/pbkdf-gcrypt.c

crypto/pbkdf-gcrypt.c new file +2 -0
+int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
+                   const uint8_t *key, size_t nkey,

crypto/pbkdf-gcrypt.c line 46

Quoted 10 lines
crypto/pbkdf-gcrypt.c new file +10 -0
+                   const uint8_t *salt, size_t nsalt,
+                   unsigned int iterations,
+                   uint8_t *out, size_t nout,
+                   Error **errp)
+{
+    static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
+        [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
+        [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
+        [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
+    };

If QCRYPTO_HASH_ gains future enum values, those elements of the array will be 0-initialized.

crypto/pbkdf-gcrypt.c line 52

Quoted 6 lines
crypto/pbkdf-gcrypt.c new file +6 -0
+    int ret;
+
+    if (hash > G_N_ELEMENTS(hash_map)) {
+        error_setg(errp, "Unexpected hash algorithm %d", hash);
+        return -1;
+    }
Quoted 2 lines

This checks for beyond the bounds of the array, but not for an element that was 0-initialized. Is that a problem we need to worry about?

I'll add '|| hash_map[hash] == GCRY_MD_NONE' to this condition

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

PATCH v2 4/17 crypto: add support for generating initialization vectors

In reply to Daniel P. Berrange

There are a number of different algorithms that can be used to generate initialization vectors for disk encryption. This introduces a simple internal QCryptoBlockIV object to provide a consistent internal API to the different algorithms. The initially implemented algorithms are 'plain', 'plain64' and 'essiv', each matching the same named algorithm provided by the Linux kernel dm-crypt driver.

---
 crypto/Makefile.objs      |   4 +
 crypto/ivgen-essiv.c      | 112 +++++++++++++++++++++++++
 crypto/ivgen-essiv.h      |  28 +++++++
 crypto/ivgen-plain.c      |  58 +++++++++++++
 crypto/ivgen-plain.h      |  28 +++++++
 crypto/ivgen-plain64.c    |  58 +++++++++++++
 crypto/ivgen-plain64.h    |  28 +++++++
 crypto/ivgen.c            |  98 ++++++++++++++++++++++
 crypto/ivgenpriv.h        |  49 +++++++++++
 include/crypto/ivgen.h    | 203 ++++++++++++++++++++++++++++++++++++++++++++++
 qapi/crypto.json          |  16 ++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-ivgen.c | 168 ++++++++++++++++++++++++++++++++++++++
 14 files changed, 853 insertions(+)
 create mode 100644 crypto/ivgen-essiv.c
 create mode 100644 crypto/ivgen-essiv.h
 create mode 100644 crypto/ivgen-plain.c
 create mode 100644 crypto/ivgen-plain.h
 create mode 100644 crypto/ivgen-plain64.c
 create mode 100644 crypto/ivgen-plain64.h
 create mode 100644 crypto/ivgen.c
 create mode 100644 crypto/ivgenpriv.h
 create mode 100644 include/crypto/ivgen.h
 create mode 100644 tests/test-crypto-ivgen.c
crypto/Makefile.objs +4 -0
index 4d2cd3e..3040989 100644
@@ -13,6 +13,10 @@ crypto-obj-$(CONFIG_GNUTLS) += random-gnutls.o
 crypto-obj-y += pbkdf.o
 crypto-obj-$(CONFIG_NETTLE) += pbkdf-nettle.o
 crypto-obj-$(if $(CONFIG_NETTLE),n,$(CONFIG_GCRYPT)) += pbkdf-gcrypt.o
+crypto-obj-y += ivgen.o
+crypto-obj-y += ivgen-essiv.o
+crypto-obj-y += ivgen-plain.o
+crypto-obj-y += ivgen-plain64.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
crypto/ivgen-essiv.c new file +112 -0

112 lines not on this page · raw message

crypto/ivgen-essiv.h new file +28 -0
new file mode 100644
index 0000000..4a00af8
@@ -0,0 +1,28 @@
+/*
+ * QEMU Crypto block IV generator - essiv
+ *
+ * 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 "crypto/ivgenpriv.h"
+
+#ifndef QCRYPTO_IVGEN_ESSIV_H__
+#define QCRYPTO_IVGEN_ESSIV_H__
+
+extern struct QCryptoIVGenDriver qcrypto_ivgen_essiv;
+
+#endif /* QCRYPTO_IVGEN_ESSIV_H__ */
crypto/ivgen-plain.c new file +58 -0

58 lines not on this page · raw message

crypto/ivgen-plain.h new file +28 -0
new file mode 100644
index 0000000..0fe8835
@@ -0,0 +1,28 @@
+/*
+ * QEMU Crypto block IV generator - plain
+ *
+ * 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 "crypto/ivgenpriv.h"
+
+#ifndef QCRYPTO_IVGEN_PLAIN_H__
+#define QCRYPTO_IVGEN_PLAIN_H__
+
+extern struct QCryptoIVGenDriver qcrypto_ivgen_plain;
+
+#endif /* QCRYPTO_IVGEN_PLAIN_H__ */
crypto/ivgen-plain64.c new file +58 -0

58 lines not on this page · raw message

crypto/ivgen-plain64.h new file +28 -0
new file mode 100644
index 0000000..c410445
@@ -0,0 +1,28 @@
+/*
+ * QEMU Crypto block IV generator - plain64
+ *
+ * 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 "crypto/ivgenpriv.h"
+
+#ifndef QCRYPTO_IVGEN_PLAIN64_H__
+#define QCRYPTO_IVGEN_PLAIN64_H__
+
+extern struct QCryptoIVGenDriver qcrypto_ivgen_plain64;
+
+#endif /* QCRYPTO_IVGEN_PLAIN64_H__ */
crypto/ivgen.c new file +98 -0

98 lines not on this page · raw message

crypto/ivgenpriv.h new file +49 -0

49 lines not on this page · raw message

include/crypto/ivgen.h new file +203 -0

203 lines not on this page · raw message

qapi/crypto.json +16 -0
index 4bd690f..48946b0 100644
@@ -78,3 +78,19 @@
 { 'enum': 'QCryptoCipherMode',
   'prefix': 'QCRYPTO_CIPHER_MODE',
   'data': ['ecb', 'cbc']}
+
+
+##
+# QCryptoIVGenAlgorithm:
+#
+# The supported algorithms for generating initialization
+# vectors for full disk encryption
+#
+# @plain: 64-bit sector number truncated to 32-bits
+# @plain64: 64-bit sector number
+# @essiv: 64-bit sector number encrypted with a hash of the encryption key
+# Since: 2.6
+##
+{ 'enum': 'QCryptoIVGenAlgorithm',
+  'prefix': 'QCRYPTO_IVGEN_ALG',
+  'data': ['plain', 'plain64', 'essiv']}
tests/.gitignore +1 -0
index db6b9be..369f848 100644
@@ -14,6 +14,7 @@ test-blockjob-txn
 test-coroutine
 test-crypto-cipher
 test-crypto-hash
+test-crypto-ivgen
 test-crypto-pbkdf
 test-crypto-secret
 test-crypto-tlscredsx509
tests/Makefile +2 -0
index 833a290..5fdbaf0 100644
@@ -93,6 +93,7 @@ check-unit-y += tests/test-io-channel-command$(EXESUF)
 check-unit-y += tests/test-io-channel-buffer$(EXESUF)
 check-unit-y += tests/test-base64$(EXESUF)
 check-unit-y += tests/test-crypto-pbkdf$(EXESUF)
+check-unit-y += tests/test-crypto-ivgen$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -497,6 +498,7 @@ tests/test-io-channel-command$(EXESUF): tests/test-io-channel-command.o \
 tests/test-io-channel-buffer$(EXESUF): tests/test-io-channel-buffer.o \
         tests/io-channel-helpers.o $(test-io-obj-y)
 tests/test-crypto-pbkdf$(EXESUF): tests/test-crypto-pbkdf.o $(test-crypto-obj-y)
+tests/test-crypto-ivgen$(EXESUF): tests/test-crypto-ivgen.o $(test-crypto-obj-y)
 
 libqos-obj-y = tests/libqos/pci.o tests/libqos/fw_cfg.o tests/libqos/malloc.o
 libqos-obj-y += tests/libqos/i2c.o tests/libqos/libqos.o
tests/test-crypto-ivgen.c new file +168 -0

168 lines not on this page · raw message

Signature · 1 line
2.5.0
#14 lore raw

Re: [Qemu-devel] [PATCH v2 04/17] crypto: add support for generating initialization vectors

Quoted 35 lines · Daniel P. Berrange
crypto/ivgen-essiv.c new file +35 -0
+static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,
+                                    const uint8_t *key, size_t nkey,
+                                    Error **errp)
+{
+    uint8_t *salt;
+    size_t nhash;
+    QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);
+
+    nhash = qcrypto_hash_digest_len(ivgen->hash);
+    /* Salt must be larger of hash size or key size */
+    salt = g_new0(uint8_t, nhash > nkey ? nhash : nkey);
+
+    if (qcrypto_hash_bytes(ivgen->hash, (const gchar *)key, nkey,
+                           &salt, &nhash,
+                           errp) < 0) {
+        g_free(essiv);
+        return -1;
+    }
+
+    essiv->cipher = qcrypto_cipher_new(ivgen->cipher,
+                                       QCRYPTO_CIPHER_MODE_ECB,
+                                       salt, nkey,
+                                       errp);
+    if (!essiv->cipher) {
+        g_free(essiv);
+        g_free(salt);
+        return -1;
+    }
+
+    g_free(salt);
+    ivgen->private = essiv;
+
+    return 0;
+}
+

crypto/ivgen-essiv.c line 72

Quoted 10 lines
crypto/ivgen-essiv.c new file +10 -0
+static int qcrypto_ivgen_essiv_calculate(QCryptoIVGen *ivgen,
+                                         uint64_t sector,
+                                         uint8_t *iv, size_t niv,
+                                         Error **errp)
+{
+    QCryptoIVGenESSIV *essiv = ivgen->private;
+    size_t ndata = qcrypto_cipher_get_block_len(ivgen->cipher);
+    uint8_t *data = g_new(uint8_t, ndata);
+
+    sector = cpu_to_le64((uint32_t)sector);

Why casting to 32 bit?

Quoted 26 lines
crypto/ivgen-essiv.c new file +26 -0
+    memcpy(data, (uint8_t *)&sector, ndata);
+    if (sizeof(sector) < ndata) {
+        memset(data + sizeof(sector), 0, ndata - sizeof(sector));
+    }
+
+    if (qcrypto_cipher_encrypt(essiv->cipher,
+                               data,
+                               data,
+                               ndata,
+                               errp) < 0) {
+        g_free(data);
+        return -1;
+    }
+
+    if (ndata > niv) {
+        ndata = niv;
+    }
+    memcpy(iv, data, ndata);
+    if (ndata < niv) {
+        memset(iv + ndata, 0, niv - ndata);
+    }
+    g_free(data);
+    return 0;
+}
+
+static void qcrypto_ivgen_essiv_cleanup(QCryptoIVGen *ivgen)

crypto/ivgen-essiv.c line 108

Quoted 10 lines
crypto/ivgen-essiv.c new file +10 -0
+{
+    QCryptoIVGenESSIV *essiv = ivgen->private;
+
+    qcrypto_cipher_free(essiv->cipher);
+    g_free(essiv);
+}
+
+
+struct QCryptoIVGenDriver qcrypto_ivgen_essiv = {
+    qcrypto_ivgen_essiv_init,

It'd be more readable to explicitly write

    .init = qcrypto_ivgen_essiv_init,
    .calculate = ...,
    .cleanup = ...

but it is fine since there are only three operations now.

Quoted 4 lines
crypto/ivgen-essiv.c new file +4 -0
+    qcrypto_ivgen_essiv_calculate,
+    qcrypto_ivgen_essiv_cleanup,
+};
+
#15 lore raw

Re: [Qemu-devel] [PATCH v2 04/17] crypto: add support for generating initialization vectors

Quoted 40 lines · Fam Zheng
Quoted 39 lines · Daniel P. Berrange
crypto/ivgen-essiv.c new file +39 -0
+static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,
+                                    const uint8_t *key, size_t nkey,
+                                    Error **errp)
+{
+    uint8_t *salt;
+    size_t nhash;
+    QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);
+
+    nhash = qcrypto_hash_digest_len(ivgen->hash);
+    /* Salt must be larger of hash size or key size */
+    salt = g_new0(uint8_t, nhash > nkey ? nhash : nkey);
+
+    if (qcrypto_hash_bytes(ivgen->hash, (const gchar *)key, nkey,
+                           &salt, &nhash,
+                           errp) < 0) {
+        g_free(essiv);
+        return -1;
+    }
+
+    essiv->cipher = qcrypto_cipher_new(ivgen->cipher,
+                                       QCRYPTO_CIPHER_MODE_ECB,
+                                       salt, nkey,
+                                       errp);
+    if (!essiv->cipher) {
+        g_free(essiv);
+        g_free(salt);
+        return -1;
+    }
+
+    g_free(salt);
+    ivgen->private = essiv;
+
+    return 0;
+}
+
+static int qcrypto_ivgen_essiv_calculate(QCryptoIVGen *ivgen,
+                                         uint64_t sector,
+                                         uint8_t *iv, size_t niv,
+                                         Error **errp)
Quoted 8 lines

crypto/ivgen-essiv.c line 72

Quoted 6 lines
crypto/ivgen-essiv.c new file +6 -0
+{
+    QCryptoIVGenESSIV *essiv = ivgen->private;
+    size_t ndata = qcrypto_cipher_get_block_len(ivgen->cipher);
+    uint8_t *data = g_new(uint8_t, ndata);
+
+    sector = cpu_to_le64((uint32_t)sector);

Why casting to 32 bit?

Bugtastic.

Quoted 39 lines
Quoted 26 lines
crypto/ivgen-essiv.c new file +26 -0
+    memcpy(data, (uint8_t *)&sector, ndata);
+    if (sizeof(sector) < ndata) {
+        memset(data + sizeof(sector), 0, ndata - sizeof(sector));
+    }
+
+    if (qcrypto_cipher_encrypt(essiv->cipher,
+                               data,
+                               data,
+                               ndata,
+                               errp) < 0) {
+        g_free(data);
+        return -1;
+    }
+
+    if (ndata > niv) {
+        ndata = niv;
+    }
+    memcpy(iv, data, ndata);
+    if (ndata < niv) {
+        memset(iv + ndata, 0, niv - ndata);
+    }
+    g_free(data);
+    return 0;
+}
+
+static void qcrypto_ivgen_essiv_cleanup(QCryptoIVGen *ivgen)

crypto/ivgen-essiv.c line 108

Quoted 10 lines
crypto/ivgen-essiv.c new file +10 -0
+{
+    QCryptoIVGenESSIV *essiv = ivgen->private;
+
+    qcrypto_cipher_free(essiv->cipher);
+    g_free(essiv);
+}
+
+
+struct QCryptoIVGenDriver qcrypto_ivgen_essiv = {
+    qcrypto_ivgen_essiv_init,

It'd be more readable to explicitly write

Quoted 5 lines
    .init = qcrypto_ivgen_essiv_init,
    .calculate = ...,
    .cleanup = ...

but it is fine since there are only three operations now.

Yeah, I normally do it that way anyway, so will change it.

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 :|
#16 lore raw

Re: [Qemu-devel] [PATCH v2 04/17] crypto: add support for generating initialization vectors

In reply to Daniel P. Berrange
Quoted 14 lines · Daniel P. Berrange

There are a number of different algorithms that can be used to generate initialization vectors for disk encryption. This introduces a simple internal QCryptoBlockIV object to provide a consistent internal API to the different algorithms. The initially implemented algorithms are 'plain', 'plain64' and 'essiv', each matching the same named algorithm provided by the Linux kernel dm-crypt driver.

---

+++ b/crypto/ivgen-essiv.c

crypto/ivgen-essiv.c new file +1 -0
+static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,

crypto/ivgen-essiv.c line 38

Quoted 10 lines
crypto/ivgen-essiv.c new file +10 -0
+                                    const uint8_t *key, size_t nkey,
+                                    Error **errp)
+{
+    uint8_t *salt;
+    size_t nhash;
+    QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);
+
+    nhash = qcrypto_hash_digest_len(ivgen->hash);
+    /* Salt must be larger of hash size or key size */
+    salt = g_new0(uint8_t, nhash > nkey ? nhash : nkey);

Don't we have a handy MAX() macro for that?

crypto/ivgen-plain.c line 36

Quoted 8 lines

+++ b/crypto/ivgen-plain.c

crypto/ivgen-plain.c new file +7 -0
+static int qcrypto_ivgen_plain_calculate(QCryptoIVGen *ivgen,
+                                         uint64_t sector,
+                                         uint8_t *iv, size_t niv,
+                                         Error **errp)
+{
+    size_t ivprefix;
+    uint32_t shortsector = cpu_to_le32((uint32_t)(sector & 0xffffffff));

Why do you need both the cast and the mask to 32 bits?

crypto/ivgenpriv.h line 29

Quoted 5 lines

+++ b/crypto/ivgenpriv.h

crypto/ivgenpriv.h new file +2 -0
@@ -0,0 +1,49 @@
 
+struct QCryptoIVGenDriver {
+    int (*init)(QCryptoIVGen *biv,

Where'd the name 'biv' come from? But it doesn't affect correctness.

Quoted 24 lines

+++ b/include/crypto/ivgen.h

include/crypto/ivgen.h new file +20 -0
@@ -0,0 +1,203 @@
 
+
+/**
+ * This module provides a framework for generating initialization
+ * vectors for block encryption schemes using chained cipher modes
+ * CBC. The principle is that each disk sector is assigned a unique
+ * initialization vector for use for encryption of data in that
+ * sector.
+ *
+ * <example>
+ *   <title>Encrypting block data with initialiation vectors</title>
+ *   <programlisting>
 
+ * niv =  qcrypto_cipher_get_iv_len(QCRYPTO_CIPHER_ALG_AES_128,
+ *                                  QCRYPTO_CIPHER_MODE_CBC);
+ * iv = g_new0(uint8_t, niv);
+ *
+ *
+ * while (ndata) {
+ *     if (qcrypto_ivgen_calculate(ivgen, sector, iv, niv, errp) < 0) {
+ *         goto error;
+ *     }

include/crypto/ivgen.h line 80

Quoted 10 lines
include/crypto/ivgen.h new file +10 -0
+ *     if (qcrypto_cipher_setiv(cipher, iv, niv, errp) < 0) {
+ *         goto error;
+ *     }
+ *     if (qcrypto_cipher_encrypt(cipher,
+ *                                data + (sector * 512),
+ *                                data + (sector * 512),
+ *                                512, errp) < 0) {
+ *         goto error;
+ *     }
+ * }

Umm, this loop is infinite except on errors, because ndata is never changed. Are you missing something like 'sector++; ndata -= 512;' ?

include/crypto/ivgen.h line 105

Quoted 6 lines
include/crypto/ivgen.h new file +6 -0
+
+/**
+ * qcrypto_ivgen_new:
+ * @alg: the initialization vector generation algorithm
+ * @cipheralg: the cipher algorithm or 0
+ * @hash: the hash algorithm or 0,

Inconsistent trailing punctuation.

Why 'or 0'? These two fields are defined by QAPI enums, which start numbering at 0. So cipheralg == 0 would by indistinguishable from requesting the 'aes-128' cipher. Is the intent to allow a sentinel for unspecified, when the algorithm can use a default of its choosing?...

Quoted 7 lines

+ * @key: the encryption key or NULL
+ * @nkey: the size of @key in bytes
+ *
+ * Create a new initialization vector generator that uses
+ * the algorithm @alg. Whether the remaining parameters
+ * are required or not depends on the choice of @alg
+ * requested.

...Oh, because 0 is okay if @alg won't use the parameter.

Quoted 6 lines

+ *
+ * - QCRYPTO_IVGEN_ALG_PLAIN
+ *
+ * The IVs are generated by the 32-bit truncated sector
+ * number. This should never be used for block devices
+ * that are larger than 2^32 sectors in size

Should the code assert/set errp if sector is too large, rather than blindly truncating it? I guess it is user-triggerable so assert is probably bad, but it may still be nice to tell the user up front that they can't use this mode based on the size of their block device, if we can figure that out.

include/crypto/ivgen.h line 180

Quoted 10 lines
include/crypto/ivgen.h new file +10 -0
+/**
+ * qcrypto_ivgen_get_cipher:
+ * @ivgen: the IV generator object
+ *
+ * Get the cipher algorithm used by this IV generator (if
+ * applicable)
+ *
+ * Returns: the cipher algorithm
+ */
+QCryptoCipherAlgorithm qcrypto_ivgen_get_cipher(QCryptoIVGen *ivgen);

Should this return a known and obvious sentinel when the ivgen doesn't need a cipher, rather than just playing back the user's input (which was likely 0)?

include/crypto/ivgen.h line 192

Quoted 12 lines
include/crypto/ivgen.h new file +12 -0
+
+
+/**
+ * qcrypto_ivgen_get_algorithm:
+ * @ivgen: the IV generator object
+ *
+ * Get the hash algorithm used by this IV generator (if
+ * applicable)
+ *
+ * Returns: the hash algorithm
+ */
+QCryptoHashAlgorithm qcrypto_ivgen_get_hash(QCryptoIVGen *ivgen);

Copy/paste mismatch in documentation name (this is get_hash, not get_algorithm)

include/crypto/ivgen.h line 199

Quoted 7 lines
include/crypto/ivgen.h new file +7 -0
+
+
+/**
+ * qcrypto_ivgen_free:
+ * @ivgen: the IV generator object
+ *
+ * Release all resources associated with @ivgen

Worth mentioning that it works on NULL?

Quoted 4 lines

+++ b/qapi/crypto.json

qapi/crypto.json +0 -0
@@ -78,3 +78,19 @@
 { 'enum': 'QCryptoCipherMode',
   'prefix': 'QCRYPTO_CIPHER_MODE',

qapi/crypto.json line 89

Quoted 10 lines
qapi/crypto.json +9 -0
   'data': ['ecb', 'cbc']}
+
+
+##
+# QCryptoIVGenAlgorithm:
+#
+# The supported algorithms for generating initialization
+# vectors for full disk encryption
+#
+# @plain: 64-bit sector number truncated to 32-bits

Worth a warning to avoid this for disks larger than 2^32 bytes?

Quoted 7 lines
qapi/crypto.json +7 -0
+# @plain64: 64-bit sector number
+# @essiv: 64-bit sector number encrypted with a hash of the encryption key
+# Since: 2.6
+##
+{ 'enum': 'QCryptoIVGenAlgorithm',
+  'prefix': 'QCRYPTO_IVGEN_ALG',
+  'data': ['plain', 'plain64', 'essiv']}
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#17 lore raw

Re: [Qemu-devel] [PATCH v2 04/17] crypto: add support for generating initialization vectors

Quoted 14 lines · Eric Blake
Quoted 12 lines · Daniel P. Berrange

There are a number of different algorithms that can be used to generate initialization vectors for disk encryption. This introduces a simple internal QCryptoBlockIV object to provide a consistent internal API to the different algorithms. The initially implemented algorithms are 'plain', 'plain64' and 'essiv', each matching the same named algorithm provided by the Linux kernel dm-crypt driver.

---

+++ b/crypto/ivgen-essiv.c

Quoted 13 lines

crypto/ivgen-essiv.c line 38

Quoted 11 lines
crypto/ivgen-essiv.c new file +11 -0
+static int qcrypto_ivgen_essiv_init(QCryptoIVGen *ivgen,
+                                    const uint8_t *key, size_t nkey,
+                                    Error **errp)
+{
+    uint8_t *salt;
+    size_t nhash;
+    QCryptoIVGenESSIV *essiv = g_new0(QCryptoIVGenESSIV, 1);
+
+    nhash = qcrypto_hash_digest_len(ivgen->hash);
+    /* Salt must be larger of hash size or key size */
+    salt = g_new0(uint8_t, nhash > nkey ? nhash : nkey);

Don't we have a handy MAX() macro for that?

Yes

Quoted 10 lines

crypto/ivgen-plain.c line 36

Quoted 8 lines

+++ b/crypto/ivgen-plain.c

crypto/ivgen-plain.c new file +7 -0
+static int qcrypto_ivgen_plain_calculate(QCryptoIVGen *ivgen,
+                                         uint64_t sector,
+                                         uint8_t *iv, size_t niv,
+                                         Error **errp)
+{
+    size_t ivprefix;
+    uint32_t shortsector = cpu_to_le32((uint32_t)(sector & 0xffffffff));

Why do you need both the cast and the mask to 32 bits?

I'll remove the cast. I'll also add in

    if (shortsector != sector) {
        error_setg(errp, "Sector '%llu' is too large for 'plain' "
                   "initialization vector generator",
                   (long long unsigned)sector);
        return -1;
    }
Quoted 8 lines

crypto/ivgenpriv.h line 29

Quoted 6 lines

+++ b/crypto/ivgenpriv.h

crypto/ivgenpriv.h new file +2 -0
@@ -0,0 +1,49 @@
 
+struct QCryptoIVGenDriver {
+    int (*init)(QCryptoIVGen *biv,

Where'd the name 'biv' come from? But it doesn't affect correctness.

An older version of the code called the struct QCryptoBlockIV. I'll change this to 'ivgen' to match elsewhere.

Quoted 15 lines
Quoted 8 lines

+ * while (ndata) {
+ * if (qcrypto_ivgen_calculate(ivgen, sector, iv, niv, errp) < 0) {
+ * goto error;
+ * }
+ * if (qcrypto_cipher_setiv(cipher, iv, niv, errp) < 0) {
+ * goto error;
+ * }
+ * if (qcrypto_cipher_encrypt(cipher,

Quoted 6 lines
+ *                                data + (sector * 512),
+ *                                data + (sector * 512),
+ *                                512, errp) < 0) {

+ * goto error;
+ * }
+ * }

Quoted 2 lines

Umm, this loop is infinite except on errors, because ndata is never changed. Are you missing something like 'sector++; ndata -= 512;' ?

Yes, will add those.

Quoted 7 lines
Quoted 6 lines

+ *
+ * - QCRYPTO_IVGEN_ALG_PLAIN
+ *
+ * The IVs are generated by the 32-bit truncated sector
+ * number. This should never be used for block devices
+ * that are larger than 2^32 sectors in size

Quoted 5 lines

Should the code assert/set errp if sector is too large, rather than blindly truncating it? I guess it is user-triggerable so assert is probably bad, but it may still be nice to tell the user up front that they can't use this mode based on the size of their block device, if we can figure that out.

I put an error check in as mentioned above.

Quoted 6 lines
Quoted 6 lines

+/**
+ * qcrypto_ivgen_get_cipher:
+ * @ivgen: the IV generator object
+ *
+ * Get the cipher algorithm used by this IV generator (if
+ * applicable)

Quoted 8 lines
Quoted 4 lines

+ *
+ * Returns: the cipher algorithm
+ */
+QCryptoCipherAlgorithm qcrypto_ivgen_get_cipher(QCryptoIVGen *ivgen);

Should this return a known and obvious sentinel when the ivgen doesn't need a cipher, rather than just playing back the user's input (which was likely 0)?

I feel it is nicer to just be consistent with the user's input.

Quoted 7 lines
Quoted 5 lines

+/**
+ * qcrypto_ivgen_free:
+ * @ivgen: the IV generator object
+ *
+ * Release all resources associated with @ivgen

Worth mentioning that it works on NULL?

Yep.

Quoted 8 lines

qapi/crypto.json line 89

Quoted 6 lines
qapi/crypto.json +6 -0
+# QCryptoIVGenAlgorithm:
+#
+# The supported algorithms for generating initialization
+# vectors for full disk encryption
+#
+# @plain: 64-bit sector number truncated to 32-bits

Worth a warning to avoid this for disks larger than 2^32 bytes?

Yes, will do.

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 :|
#18 lore raw

Re: [Qemu-devel] [PATCH v2 04/17] crypto: add support for generating initialization vectors

Quoted 34 lines · Daniel P. Berrange
Quoted 14 lines · Eric Blake
Quoted 12 lines · Daniel P. Berrange

There are a number of different algorithms that can be used to generate initialization vectors for disk encryption. This introduces a simple internal QCryptoBlockIV object to provide a consistent internal API to the different algorithms. The initially implemented algorithms are 'plain', 'plain64' and 'essiv', each matching the same named algorithm provided by the Linux kernel dm-crypt driver.

---

+++ b/crypto/ivgen-essiv.c

Quoted 10 lines

crypto/ivgen-plain.c line 36

Quoted 8 lines

+++ b/crypto/ivgen-plain.c

crypto/ivgen-plain.c new file +7 -0
+static int qcrypto_ivgen_plain_calculate(QCryptoIVGen *ivgen,
+                                         uint64_t sector,
+                                         uint8_t *iv, size_t niv,
+                                         Error **errp)
+{
+    size_t ivprefix;
+    uint32_t shortsector = cpu_to_le32((uint32_t)(sector & 0xffffffff));

Why do you need both the cast and the mask to 32 bits?

I'll remove the cast. I'll also add in

    if (shortsector != sector) {
        error_setg(errp, "Sector '%llu' is too large for 'plain' "
                   "initialization vector generator",
                   (long long unsigned)sector);
        return -1;
    }

[snip]

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

+ *
+ * - QCRYPTO_IVGEN_ALG_PLAIN
+ *
+ * The IVs are generated by the 32-bit truncated sector
+ * number. This should never be used for block devices
+ * that are larger than 2^32 sectors in size

Quoted 7 lines
Quoted 5 lines

Should the code assert/set errp if sector is too large, rather than blindly truncating it? I guess it is user-triggerable so assert is probably bad, but it may still be nice to tell the user up front that they can't use this mode based on the size of their block device, if we can figure that out.

I put an error check in as mentioned above.

Actually we must not treat this is an error - we must silently truncate to 32-bits, in order to retain compatibility with Linux dm-crypt formatted volumes.

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 :|
#19 lore raw

PATCH v2 5/17 crypto: add support for anti-forensic split algorithm

In reply to Daniel P. Berrange

The LUKS format specifies an anti-forensic split algorithm which is used to artificially expand the size of the key material on disk. This is an implementation of that algorithm.

---
 crypto/Makefile.objs        |   1 +
 crypto/afsplit.c            | 162 ++++++++++++++++++++++++++++++++++++++++
 include/crypto/afsplit.h    | 135 +++++++++++++++++++++++++++++++++
 tests/.gitignore            |   1 +
 tests/Makefile              |   2 +
 tests/test-crypto-afsplit.c | 176 ++++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 477 insertions(+)
 create mode 100644 crypto/afsplit.c
 create mode 100644 include/crypto/afsplit.h
 create mode 100644 tests/test-crypto-afsplit.c
crypto/Makefile.objs +1 -0
index 3040989..5136737 100644
@@ -17,6 +17,7 @@ crypto-obj-y += ivgen.o
 crypto-obj-y += ivgen-essiv.o
 crypto-obj-y += ivgen-plain.o
 crypto-obj-y += ivgen-plain64.o
+crypto-obj-y += afsplit.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
crypto/afsplit.c new file +162 -0

162 lines not on this page · raw message

include/crypto/afsplit.h new file +135 -0

135 lines not on this page · raw message

tests/.gitignore +1 -0
index 369f848..5b97e8c 100644
@@ -12,6 +12,7 @@ test-base64
 test-bitops
 test-blockjob-txn
 test-coroutine
+test-crypto-afsplit
 test-crypto-cipher
 test-crypto-hash
 test-crypto-ivgen
tests/Makefile +2 -0
index 5fdbaf0..80847b9 100644
@@ -94,6 +94,7 @@ check-unit-y += tests/test-io-channel-buffer$(EXESUF)
 check-unit-y += tests/test-base64$(EXESUF)
 check-unit-y += tests/test-crypto-pbkdf$(EXESUF)
 check-unit-y += tests/test-crypto-ivgen$(EXESUF)
+check-unit-y += tests/test-crypto-afsplit$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -499,6 +500,7 @@ tests/test-io-channel-buffer$(EXESUF): tests/test-io-channel-buffer.o \
         tests/io-channel-helpers.o $(test-io-obj-y)
 tests/test-crypto-pbkdf$(EXESUF): tests/test-crypto-pbkdf.o $(test-crypto-obj-y)
 tests/test-crypto-ivgen$(EXESUF): tests/test-crypto-ivgen.o $(test-crypto-obj-y)
+tests/test-crypto-afsplit$(EXESUF): tests/test-crypto-afsplit.o $(test-crypto-obj-y)
 
 libqos-obj-y = tests/libqos/pci.o tests/libqos/fw_cfg.o tests/libqos/malloc.o
 libqos-obj-y += tests/libqos/i2c.o tests/libqos/libqos.o
tests/test-crypto-afsplit.c new file +176 -0

176 lines not on this page · raw message

Signature · 1 line
2.5.0
#20 lore raw

Re: [Qemu-devel] [PATCH v2 05/17] crypto: add support for anti-forensic split algorithm

crypto/afsplit.c line 6

Quoted 12 lines · Daniel P. Berrange
crypto/afsplit.c new file +6 -0
new file mode 100644
index 0000000..42529e7
@@ -0,0 +1,162 @@
+/*
+ * QEMU Crypto anti forensic information splitter
+ *
+ * Copyright (c) 2015-2016 Red Hat, Inc.
+ *
+ * Derived from cryptsetup package lib/lusk1/af.c

s/lusk1/luks1/

Quoted 19 lines
crypto/afsplit.c new file +19 -0
+ *
+ * Copyright (C) 2004, Clemens Fruhwirth <[email protected]>
+ * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU 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/>.
+ *
+ */
+

<snip>

Quoted 20 lines
crypto/afsplit.c new file +20 -0
+
+/**
+ * qcrypto_afsplit_encode:
+ * @hash: the hash algorithm to use for data expansion
+ * @blocklen: the size of @in in bytes
+ * @stripes: the number of times to expand @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Split the data in @in, which is @blocklen bytes in
+ * size, to form a larger piece of data @out, which is
+ * @blocklen * @stripes bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */
+int qcrypto_afsplit_encode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,

crypto/afsplit.c

Quoted 10 lines
crypto/afsplit.c new file +10 -0
+                           uint8_t *out,
+                           Error **errp);
+
+/**
+ * qcrypto_afsplit_decode:
+ * @hash: the hash algorithm to use for data compression
+ * @blocklen: the size of @out in bytes
+ * @stripes: the number of times to decrease @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key

I think the descriptions for @in and @out are wrong.

Quoted 4 lines

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Join the data in @in, which is @blocklen * @stripes
+ * bytes in size, to form the original small piece o

piece of

crypto/afsplit.c

Quoted 12 lines

+ * data @out, which is @blocklen bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */

crypto/afsplit.c new file +8 -0
+int qcrypto_afsplit_decode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp);
+
+#endif /* QCRYPTO_AFSPLIT_H__ */

Fam

#21 lore raw

Re: [Qemu-devel] [PATCH v2 05/17] crypto: add support for anti-forensic split algorithm

Quoted 25 lines · Fam Zheng
Quoted 25 lines
include/crypto/afsplit.h new file +24 -0
+
+/**
+ * qcrypto_afsplit_encode:
+ * @hash: the hash algorithm to use for data expansion
+ * @blocklen: the size of @in in bytes
+ * @stripes: the number of times to expand @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Split the data in @in, which is @blocklen bytes in
+ * size, to form a larger piece of data @out, which is
+ * @blocklen * @stripes bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */
+int qcrypto_afsplit_encode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp);
+
+/**
Quoted 8 lines
Quoted 6 lines

+ * qcrypto_afsplit_decode:
+ * @hash: the hash algorithm to use for data compression
+ * @blocklen: the size of @out in bytes
+ * @stripes: the number of times to decrease @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key

I think the descriptions for @in and @out are wrong.

Yeah, got them the wrong way around

Quoted 8 lines
Quoted 5 lines

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Join the data in @in, which is @blocklen * @stripes
+ * bytes in size, to form the original small piece o

piece of

Quoted 14 lines

include/crypto/afsplit.h line 135

Quoted 12 lines

+ * data @out, which is @blocklen bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */

include/crypto/afsplit.h new file +8 -0
+int qcrypto_afsplit_decode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp);
+
+#endif /* QCRYPTO_AFSPLIT_H__ */

Fam

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 :|
#22 lore raw

Re: [Qemu-devel] [PATCH v2 05/17] crypto: add support for anti-forensic split algorithm

In reply to Daniel P. Berrange
Quoted 5 lines · Daniel P. Berrange

The LUKS format specifies an anti-forensic split algorithm which is used to artificially expand the size of the key material on disk. This is an implementation of that algorithm.

Quoted 12 lines
---
 crypto/Makefile.objs        |   1 +
 crypto/afsplit.c            | 162 ++++++++++++++++++++++++++++++++++++++++
 include/crypto/afsplit.h    | 135 +++++++++++++++++++++++++++++++++
 tests/.gitignore            |   1 +
 tests/Makefile              |   2 +
 tests/test-crypto-afsplit.c | 176 ++++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 477 insertions(+)
 create mode 100644 crypto/afsplit.c
 create mode 100644 include/crypto/afsplit.h
 create mode 100644 tests/test-crypto-afsplit.c

In addition to Fam's findings,

Quoted 13 lines

+++ b/crypto/afsplit.c

crypto/afsplit.c new file +10 -0
@@ -0,0 +1,162 @@
+/*
+ * QEMU Crypto anti forensic information splitter
+ *
+ * Copyright (c) 2015-2016 Red Hat, Inc.
+ *
+ * Derived from cryptsetup package lib/lusk1/af.c
+ *
+ * Copyright (C) 2004, Clemens Fruhwirth <[email protected]>
+ * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
+ *
 

crypto/afsplit.c line 38

Quoted 10 lines
crypto/afsplit.c new file +10 -0
+
+static void qcrypto_afsplit_xor(size_t blocklen,
+                                const uint8_t *in1,
+                                const uint8_t *in2,
+                                uint8_t *out)
+{
+    size_t i;
+    for (i = 0; i < blocklen; i++) {
+        out[i] = in1[i] ^ in2[i];
+    }

Could be made faster using larger data types, if we know that things are properly aligned. I'm not sure if the compiler can automatically optimize this. I'm also not sure if this is ever on a hot path where it matters.

Quoted 33 lines
crypto/afsplit.c new file +33 -0
+}
+
+
+static int qcrypto_afsplit_hash(QCryptoHashAlgorithm hash,
+                                size_t blocklen,
+                                uint8_t *block,
+                                Error **errp)
+{
+    size_t digestlen = qcrypto_hash_digest_len(hash);
+
+    size_t hashcount = blocklen / digestlen;
+    size_t finallen = blocklen % digestlen;
+    uint32_t i;
+
+    if (finallen) {
+        hashcount++;
+    } else {
+        finallen = blocklen;
+    }
+
+    for (i = 0; i < hashcount; i++) {
+        uint8_t *out = NULL;
+        size_t outlen = 0;
+        uint32_t iv = cpu_to_be32(i);
+        struct iovec in[] = {
+            { .iov_base = &iv,
+              .iov_len = sizeof(iv) },
+            { .iov_base = block + (i * digestlen),
+              .iov_len = (i == (hashcount - 1)) ? finallen : digestlen },
+        };
+
+        if (qcrypto_hash_bytesv(hash,
+                                in,

crypto/afsplit.c line 81

Quoted 10 lines
crypto/afsplit.c new file +10 -0
+                                G_N_ELEMENTS(in),
+                                &out, &outlen,
+                                errp) < 0) {
+            return -1;
+        }
+
+        if (outlen != digestlen) {
+            error_setg(errp, "Hash output %zu not %zu",
+                       outlen, digestlen);
+            g_free(out);

Is this error even possible, or can it be an assert?

Quoted 20 lines
crypto/afsplit.c new file +17 -0
+            return -1;
+        }
+        memcpy(block + (i * digestlen), out,
+               (i == (hashcount - 1)) ? finallen : digestlen);
+        g_free(out);
+    }
+
+    return 0;
+}
+
+
 
 
 
+int qcrypto_afsplit_encode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp)

crypto/afsplit.c line 112

Quoted 10 lines
crypto/afsplit.c new file +8 -0
+{
+    uint8_t *block = g_new0(uint8_t, blocklen);
+    size_t i;
 
 
+
+        qcrypto_afsplit_xor(blocklen,
+                            out + (i * blocklen),
+                            block,
+                            block);

Should we ensure no overflow in the multiplication here (or rather, that the input blocklen * stripes is reasonable on input)?

include/crypto/afsplit.h line 35

Quoted 13 lines

+++ b/include/crypto/afsplit.h

include/crypto/afsplit.h new file +11 -0
+
+/**
+ * This module implements the anti-forensic splitter that is specified
+ * as part of the LUKS format:
+ *
+ *   http://clemens.endorphin.org/cryptography
+ *   http://clemens.endorphin.org/TKS1-draft.pdf
+ *
+ * The core idea is to take a short piece of data (key material)
+ * and process it to expand it to a much larger piece of data.
+ * The expansion process is reversable, to obtain the original

s/reversable/reversible/

include/crypto/afsplit.h line 97

Quoted 13 lines

+ * short data. The key property of the expansion is that if any
+ * byte in the larger data set is changed / missing, it should be
+ * impossible to recreate the original short data.
+ *

include/crypto/afsplit.h new file +8 -0
+
+/**
+ * qcrypto_afsplit_encode:
+ * @hash: the hash algorithm to use for data expansion
+ * @blocklen: the size of @in in bytes
+ * @stripes: the number of times to expand @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key

s/preallocted/preallocated/

Quoted 12 lines

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Split the data in @in, which is @blocklen bytes in
+ * size, to form a larger piece of data @out, which is
+ * @blocklen * @stripes bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */

include/crypto/afsplit.h new file +4 -0
+int qcrypto_afsplit_encode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,

include/crypto/afsplit.h line 119

Quoted 10 lines
include/crypto/afsplit.h new file +10 -0
+                           uint8_t *out,
+                           Error **errp);
+
+/**
+ * qcrypto_afsplit_decode:
+ * @hash: the hash algorithm to use for data compression
+ * @blocklen: the size of @out in bytes
+ * @stripes: the number of times to decrease @in in size
+ * @in: the master key to be expanded in size
+ * @out: preallocted buffer to hold the split key

and again

Quoted 8 lines

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Join the data in @in, which is @blocklen * @stripes
+ * bytes in size, to form the original small piece o
+ * data @out, which is @blocklen bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */

include/crypto/afsplit.h line 133

Quoted 6 lines
include/crypto/afsplit.h new file +6 -0
+int qcrypto_afsplit_decode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp);

Markus may have an opinion on whether these functions could return void and just use the errp pointer to report errors; but I'm fine with how you've done it.

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

Re: [Qemu-devel] [PATCH v2 05/17] crypto: add support for anti-forensic split algorithm

Quoted 14 lines · Eric Blake
Quoted 12 lines · Daniel P. Berrange

+++ b/crypto/afsplit.c

crypto/afsplit.c new file +10 -0
@@ -0,0 +1,162 @@
+/*
+ * QEMU Crypto anti forensic information splitter
+ *
+ * Copyright (c) 2015-2016 Red Hat, Inc.
+ *
+ * Derived from cryptsetup package lib/lusk1/af.c
+ *
+ * Copyright (C) 2004, Clemens Fruhwirth <[email protected]>
+ * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
+ *
Quoted 15 lines

crypto/afsplit.c line 38

Quoted 10 lines
crypto/afsplit.c new file +10 -0
+
+static void qcrypto_afsplit_xor(size_t blocklen,
+                                const uint8_t *in1,
+                                const uint8_t *in2,
+                                uint8_t *out)
+{
+    size_t i;
+    for (i = 0; i < blocklen; i++) {
+        out[i] = in1[i] ^ in2[i];
+    }

Could be made faster using larger data types, if we know that things are properly aligned. I'm not sure if the compiler can automatically optimize this. I'm also not sure if this is ever on a hot path where it matters.

It is used when opening an encrypted volume, or when formatting an encrypted volume. Both those codepaths are made intentionally very slow by the pbkdf algorithm, so slowness in the afsplit code is not going to be noticable overall.

Quoted 6 lines
Quoted 6 lines
crypto/afsplit.c new file +6 -0
+static int qcrypto_afsplit_hash(QCryptoHashAlgorithm hash,
+                                size_t blocklen,
+                                uint8_t *block,
+                                Error **errp)
+{
+    size_t digestlen = qcrypto_hash_digest_len(hash);

[snip]

Quoted 13 lines

crypto/afsplit.c line 81

Quoted 12 lines
crypto/afsplit.c new file +12 -0
+        if (qcrypto_hash_bytesv(hash,
+                                in,
+                                G_N_ELEMENTS(in),
+                                &out, &outlen,
+                                errp) < 0) {
+            return -1;
+        }
+
+        if (outlen != digestlen) {
+            error_setg(errp, "Hash output %zu not %zu",
+                       outlen, digestlen);
+            g_free(out);
Quoted 1 line

Is this error even possible, or can it be an assert?

Yes it can assert, since it should be impossible.

Quoted 11 lines
Quoted 11 lines
crypto/afsplit.c new file +9 -0
+int qcrypto_afsplit_encode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp)
+{
+    uint8_t *block = g_new0(uint8_t, blocklen);
+    size_t i;
Quoted 8 lines

crypto/afsplit.c line 112

Quoted 5 lines
crypto/afsplit.c new file +5 -0
+
+        qcrypto_afsplit_xor(blocklen,
+                            out + (i * blocklen),
+                            block,
+                            block);

Should we ensure no overflow in the multiplication here (or rather, that the input blocklen * stripes is reasonable on input)?

The use case for this code is splitting an encryption key. So we're talking blocklen in the 100's and stripes i the 1000's. So we're not going to be anywhere near possible overflow.

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 :|
#24 lore raw

Re: [Qemu-devel] [PATCH v2 05/17] crypto: add support for anti-forensic split algorithm

In reply to Eric Blake
Quoted 33 lines · Eric Blake
Quoted 25 lines · Daniel P. Berrange

The LUKS format specifies an anti-forensic split algorithm which is used to artificially expand the size of the key material on disk. This is an implementation of that algorithm.

---
 crypto/Makefile.objs        |   1 +
 crypto/afsplit.c            | 162 ++++++++++++++++++++++++++++++++++++++++
 include/crypto/afsplit.h    | 135 +++++++++++++++++++++++++++++++++
 tests/.gitignore            |   1 +
 tests/Makefile              |   2 +
 tests/test-crypto-afsplit.c | 176 ++++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 477 insertions(+)
 create mode 100644 crypto/afsplit.c
 create mode 100644 include/crypto/afsplit.h
 create mode 100644 tests/test-crypto-afsplit.c

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Join the data in @in, which is @blocklen * @stripes
+ * bytes in size, to form the original small piece o
+ * data @out, which is @blocklen bytes in size.
+ *
+ * Returns: 0 on success, -1 on error;
+ */

include/crypto/afsplit.h line 133

Quoted 6 lines
include/crypto/afsplit.h new file +6 -0
+int qcrypto_afsplit_decode(QCryptoHashAlgorithm hash,
+                           size_t blocklen,
+                           uint32_t stripes,
+                           const uint8_t *in,
+                           uint8_t *out,
+                           Error **errp);
Quoted 3 lines

Markus may have an opinion on whether these functions could return void and just use the errp pointer to report errors; but I'm fine with how you've done it.

I have a preference to be non-void, as it avoids constantly having to use a 'Error local_err' and error_propagate to check for failure, so results in smaller & simpler code.

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 :|
#25 lore raw

PATCH v2 6/17 crypto: add block encryption framework

In reply to Daniel P. Berrange

Add a generic framework for support different block encryption formats. Upon instantiating a QCryptoBlock object, it will read the encryption header and extract the encryption keys. It is then possible to call methods to encrypt/decrypt data buffers.

There is also a mode whereby it will create/initialize a new encryption header on a previously unformatted volume.

The initial framework comes with support for the legacy QCow AES based encryption. This enables code in the QCow driver to be consolidated later.

---
 crypto/Makefile.objs      |   2 +
 crypto/block-qcow.c       | 167 +++++++++++++++++++++++++++++
 crypto/block-qcow.h       |  28 +++++
 crypto/block.c            | 263 ++++++++++++++++++++++++++++++++++++++++++++++
 crypto/blockpriv.h        |  90 ++++++++++++++++
 include/crypto/block.h    | 233 ++++++++++++++++++++++++++++++++++++++++
 qapi/crypto.json          |  67 ++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-block.c | 239 +++++++++++++++++++++++++++++++++++++++++
 10 files changed, 1092 insertions(+)
 create mode 100644 crypto/block-qcow.c
 create mode 100644 crypto/block-qcow.h
 create mode 100644 crypto/block.c
 create mode 100644 crypto/blockpriv.h
 create mode 100644 include/crypto/block.h
 create mode 100644 tests/test-crypto-block.c
crypto/Makefile.objs +2 -0
index 5136737..25ca0c7 100644
@@ -18,6 +18,8 @@ crypto-obj-y += ivgen-essiv.o
 crypto-obj-y += ivgen-plain.o
 crypto-obj-y += ivgen-plain64.o
 crypto-obj-y += afsplit.o
+crypto-obj-y += block.o
+crypto-obj-y += block-qcow.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
crypto/block-qcow.c new file +167 -0

167 lines not on this page · raw message

crypto/block-qcow.h new file +28 -0
new file mode 100644
index 0000000..569f836
@@ -0,0 +1,28 @@
+/*
+ * QEMU Crypto block device encryption QCow/QCow2 AES-CBC format
+ *
+ * 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/>.
+ *
+ */
+
+#ifndef QCRYPTO_BLOCK_QCOW_H__
+#define QCRYPTO_BLOCK_QCOW_H__
+
+#include "crypto/blockpriv.h"
+
+extern const QCryptoBlockDriver qcrypto_block_driver_qcow;
+
+#endif /* QCRYPTO_BLOCK_QCOW_H__ */
crypto/block.c new file +263 -0

263 lines not on this page · raw message

crypto/blockpriv.h new file +90 -0

90 lines not on this page · raw message

include/crypto/block.h new file +233 -0

233 lines not on this page · raw message

qapi/crypto.json +67 -0

70 lines not on this page · raw message

tests/.gitignore +1 -0
index 5b97e8c..179c6ba 100644
@@ -13,6 +13,7 @@ test-bitops
 test-blockjob-txn
 test-coroutine
 test-crypto-afsplit
+test-crypto-block
 test-crypto-cipher
 test-crypto-hash
 test-crypto-ivgen
tests/Makefile +2 -0
index 80847b9..20de4e4 100644
@@ -95,6 +95,7 @@ check-unit-y += tests/test-base64$(EXESUF)
 check-unit-y += tests/test-crypto-pbkdf$(EXESUF)
 check-unit-y += tests/test-crypto-ivgen$(EXESUF)
 check-unit-y += tests/test-crypto-afsplit$(EXESUF)
+check-unit-y += tests/test-crypto-block$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -501,6 +502,7 @@ tests/test-io-channel-buffer$(EXESUF): tests/test-io-channel-buffer.o \
 tests/test-crypto-pbkdf$(EXESUF): tests/test-crypto-pbkdf.o $(test-crypto-obj-y)
 tests/test-crypto-ivgen$(EXESUF): tests/test-crypto-ivgen.o $(test-crypto-obj-y)
 tests/test-crypto-afsplit$(EXESUF): tests/test-crypto-afsplit.o $(test-crypto-obj-y)
+tests/test-crypto-block$(EXESUF): tests/test-crypto-block.o $(test-crypto-obj-y)
 
 libqos-obj-y = tests/libqos/pci.o tests/libqos/fw_cfg.o tests/libqos/malloc.o
 libqos-obj-y += tests/libqos/i2c.o tests/libqos/libqos.o
tests/test-crypto-block.c new file +239 -0

239 lines not on this page · raw message

Signature · 1 line
2.5.0
#26 lore raw

Re: [Qemu-devel] [PATCH v2 06/17] crypto: add block encryption framework

Quoted 44 lines · Daniel P. Berrange

Add a generic framework for support different block encryption formats. Upon instantiating a QCryptoBlock object, it will read the encryption header and extract the encryption keys. It is then possible to call methods to encrypt/decrypt data buffers.

There is also a mode whereby it will create/initialize a new encryption header on a previously unformatted volume.

The initial framework comes with support for the legacy QCow AES based encryption. This enables code in the QCow driver to be consolidated later.

---
 crypto/Makefile.objs      |   2 +
 crypto/block-qcow.c       | 167 +++++++++++++++++++++++++++++
 crypto/block-qcow.h       |  28 +++++
 crypto/block.c            | 263 ++++++++++++++++++++++++++++++++++++++++++++++
 crypto/blockpriv.h        |  90 ++++++++++++++++
 include/crypto/block.h    | 233 ++++++++++++++++++++++++++++++++++++++++
 qapi/crypto.json          |  67 ++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-block.c | 239 +++++++++++++++++++++++++++++++++++++++++
 10 files changed, 1092 insertions(+)
 create mode 100644 crypto/block-qcow.c
 create mode 100644 crypto/block-qcow.h
 create mode 100644 crypto/block.c
 create mode 100644 crypto/blockpriv.h
 create mode 100644 include/crypto/block.h
 create mode 100644 tests/test-crypto-block.c

+++ b/crypto/block-qcow.c

crypto/block-qcow.c new file +9 -0
@@ -0,0 +1,167 @@
+/*
+ * QEMU Crypto block device encryption QCow/QCow2 AES-CBC format
+ *
+ * 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.

crypto/block-qcow.c line 19

Quoted 10 lines
crypto/block-qcow.c new file +10 -0
+ *
+ * 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/>.
+ *
+ */

Maybe worth a big comment stating that this file exists for backwards compatibility, and no one in their right mind should copy the code and/or encrypt new files with it.

crypto/block-qcow.c line 31

Quoted 7 lines
crypto/block-qcow.c new file +6 -0
+static gboolean
+qcrypto_block_qcow_has_format(const uint8_t *buf G_GNUC_UNUSED,
+                              size_t buf_size G_GNUC_UNUSED)
+{
+    return false;
+}

When I see gboolean, I think TRUE/FALSE. Yes, C99 'false' happens to promote to the correct value for whatever integer type gboolean is, but this would read nicer if it returned 'bool'.

Quoted 15 lines
crypto/block-qcow.c new file +15 -0
+
+static int
+qcrypto_block_qcow_init(QCryptoBlock *block,
+                        const char *keysecret,
+                        Error **errp)
+{
+    char *password;
+    int ret;
+    uint8_t keybuf[16];
+    int len, i;
+
+    memset(keybuf, 0, 16);
+
+    password = qcrypto_secret_lookup_as_utf8(keysecret, errp);
+    if (!password) {

crypto/block-qcow.c line 57

Quoted 10 lines
crypto/block-qcow.c new file +10 -0
+        return -1;
+    }
+
+    len = strlen(password);
+    if (len > 16) {
+        len = 16;
+    }
+    for (i = 0; i < len; i++) {
+        keybuf[i] = password[i];
+    }

What - we really throw away anything longer than 16 bytes?

Would a memcpy() be any nicer than an open-coded loop?

Quoted 12 lines
crypto/block-qcow.c new file +12 -0
+
+static int
+qcrypto_block_qcow_create(QCryptoBlock *block,
+                          QCryptoBlockCreateOptions *options,
+                          QCryptoBlockInitFunc initfunc G_GNUC_UNUSED,
+                          QCryptoBlockWriteFunc writefunc G_GNUC_UNUSED,
+                          void *opaque G_GNUC_UNUSED,
+                          Error **errp)
+{
+    if (!options->u.qcow->key_secret) {
+        error_setg(errp, "Parameter 'key-secret' is required for cipher");
+        return -1;

crypto/block-qcow.c line 131

Quoted 10 lines
crypto/block-qcow.c new file +10 -0
+    }
+    /* QCow2 has no special header, since everything is hardwired */
+    return qcrypto_block_qcow_init(block, options->u.qcow->key_secret, errp);
+}
+
+
+static void
+qcrypto_block_qcow_cleanup(QCryptoBlock *block)
+{
+}

Nothing to free? qcrypto_block_qcow_init cleaned up block->cipher and block->ivgen on error, so shouldn't this do likewise (and then the init could call this function instead of open-coding the cleanup)?...

Quoted 14 lines
crypto/block.c new file +7 -0
new file mode 100644
index 0000000..757e28a
@@ -0,0 +1,263 @@
 
+uint64_t qcrypto_block_get_payload_offset(QCryptoBlock *block)
+{
+    return block->payload_offset;
+}
+
+
+void qcrypto_block_free(QCryptoBlock *block)

crypto/block.c line 158

Quoted 10 lines
crypto/block.c new file +10 -0
+{
+    if (!block) {
+        return;
+    }
+
+    block->driver->cleanup(block);
+
+    qcrypto_cipher_free(block->cipher);
+    qcrypto_ivgen_free(block->ivgen);
+    g_free(block);

...oh, you centralized that part of the cleanup.

Quoted 6 lines

+++ b/crypto/blockpriv.h

crypto/block.c new file +4 -0
+
+typedef struct QCryptoBlockDriver QCryptoBlockDriver;
+
+struct QCryptoBlock {

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+    QCryptoBlockFormat format;
+
+    const QCryptoBlockDriver *driver;
+    void *opaque;
+
+    QCryptoCipher *cipher;
+    QCryptoIVGen *ivgen;
+    QCryptoHashAlgorithm kdfhash;
+    size_t niv;
+    uint64_t payload_offset; /* In 512 byte sectors */

Someday, we may want to support 4k sectors natively. I don't envy the person making the conversion, but we could at least make their life easier by representing this in bytes instead of units of 512-byte sectors.

crypto/block.c

Quoted 9 lines
crypto/block.c new file +9 -0
+};
+
+struct QCryptoBlockDriver {
+    int (*open)(QCryptoBlock *block,
+                QCryptoBlockOpenOptions *options,
+                QCryptoBlockReadFunc readfunc,
+                void *opaque,
+                unsigned int flags,
+                Error **errp);

No documentation on any of these contracts?

crypto/block.c

Quoted 3 lines
crypto/block.c new file +3 -0
+
+    gboolean (*has_format)(const uint8_t *buf,
+                           size_t buflen);

Why gboolean instead of bool?

Quoted 6 lines

+++ b/include/crypto/block.h

crypto/block.c new file +3 -0
+/**
+ * qcrypto_block_has_format:
+ * @format: the encryption format

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+ * @buf: the data from head of the volume
+ * @len: the length of @buf in bytes
+ *
+ * Given @len bytes of data from the head of a storage volume
+ * in @buf, probe to determine if the volume has the encryption
+ * format specified in @format.
+ *
+ * Returns: true if the data in @buf matches @format
+ */
+gboolean qcrypto_block_has_format(QCryptoBlockFormat format,

Again, this should probably be 'bool', not gboolean.

Quoted 26 lines
crypto/block.c new file +26 -0
+                                  const uint8_t *buf,
+                                  size_t buflen);
+
+typedef enum {
+    QCRYPTO_BLOCK_OPEN_NO_IO = (1 << 0),
+} QCryptoBlockOpenFlags;
+
+/**
+ * qcrypto_block_open:
+ * @options: the encryption options
+ * @readfunc: callback for reading data from the volume
+ * @opaque: data to pass to @readfunc
+ * @flags: bitmask of QCryptoBlockOpenFlags values
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Create a new block encryption object for an existing
+ * storage volume encrypted with format identified by
+ * the parameters in @options.
+ *
+ * This will use @readfunc to initialize the encryption
+ * context based on the volume header(s), extracting the
+ * master key(s) as required.
+ *
+ * If @flags contains QCRYPTO_BLOCK_OPEN_NO_IO then
+ * the open process will be optimized to skip any parts
+ * that are only required to perform I/O. In particular

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+ * this would usually avoid the need to decrypt any
+ * master keys. The only thing that can be done with
+ * the resulting QCryptoBlock object would be to query
+ * metadata such as the payload offset. There will be
+ * no cipher or ivgen objects available.
+ *
+ * If any part of initializing the encryption context
+ * fails an error will be returned. This could be due
+ * to the volume being in the wrong format, an cipher
+ * or IV generator algorithm that is not supoported,

s/supoported/supported/

Quoted 6 lines

+ * or incorrect passphrases.
+ *
+ * Returns: a block encryption format, or NULL on error
+ */

crypto/block.c new file +2 -0
+QCryptoBlock *qcrypto_block_open(QCryptoBlockOpenOptions *options,
+                                 QCryptoBlockReadFunc readfunc,

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+                                 void *opaque,
+                                 unsigned int flags,
+                                 Error **errp);
+
+/**
+ * qcrypto_block_create:
+ * @format: the encryption format
+ * @initfunc: callback for initializing volume header
+ * @writefunc: callback for writing data to the volume header
+ * @opaque: data to pass to @initfunc & @writefunc

I'd spell it out s/&/and/

Quoted 10 lines

+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Create a new block encryption object for initializing
+ * a storage volume to be encrypted with format identified
+ * by the parameters in @options.
+ *
+ * This method will allocate space for a new volume header
+ * using @initfunc and then write header data using @writefunc,
+ * generating new master keys, etc as required. Any existing
+ * data present on the volume will be irrevokably destroyed.

s/irrevokably/irrevocably/

Quoted 5 lines

+ *
+ * If any part of initializing the encryption context
+ * fails an error will be returned. This could be due
+ * to the volume being in the wrong format, an cipher
+ * or IV generator algorithm that is not supoported,

s/supoported/supported/

Quoted 4 lines

+ * or incorrect passphrases.
+ *
+ * Returns: a block encryption format, or NULL on error
+ */

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options,
+                                   QCryptoBlockInitFunc initfunc,
+                                   QCryptoBlockWriteFunc writefunc,
+                                   void *opaque,
+                                   Error **errp);
+
+/**
+ * @qcrypto_block_decrypt:
+ * @block: the block encryption object
+ * @startsector: the sector from which @buf was read

From the guest's point of view, right?

Quoted 9 lines

+ * @buf: the buffer to decrypt
+ * @len: the length of @buf in bytes
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Decrypt @len bytes of cipher text in @buf, writing
+ * plain text back into @buf
+ *
+ * Returns 0 on success, -1 on failure
+ */

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+int qcrypto_block_decrypt(QCryptoBlock *block,
+                          uint64_t startsector,
+                          uint8_t *buf,
+                          size_t len,
+                          Error **errp);
+
+/**
+ * @qcrypto_block_encrypt:
+ * @block: the block encryption object
+ * @startsector: the sector to which @buf will be written

Likewise, from the guest's point of view, right?

Quoted 18 lines

+ * @buf: the buffer to decrypt
+ * @len: the length of @buf in bytes
+ * @errp: pointer to a NULL-initialized error object
+ *
+ * Encrypt @len bytes of plain text in @buf, writing
+ * cipher text back into @buf
+ *
+ * Returns 0 on success, -1 on failure
+ */

crypto/block.c new file +7 -0
+int qcrypto_block_encrypt(QCryptoBlock *block,
+                          uint64_t startsector,
+                          uint8_t *buf,
+                          size_t len,
+                          Error **errp);
+
 
 
+/**

crypto/block.c

Quoted 10 lines
crypto/block.c new file +10 -0
+ * qcrypto_block_get_payload_offset:
+ * @block: the block encryption object
+ *
+ * Get the offset to the payload indicated by the
+ * encryption header. The offset is measured in
+ * 512 byte sectors
+ *
+ * Returns: the payload offset in sectors.
+ */
+uint64_t qcrypto_block_get_payload_offset(QCryptoBlock *block);

Please, let's use bytes here, not sectors.

Quoted 1 line

+++ b/tests/test-crypto-block.c

Nice tests. Overall looks like we are fairly close to having this ready to commit.

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

Re: [Qemu-devel] [PATCH v2 06/17] crypto: add block encryption framework

Quoted 51 lines · Eric Blake
Quoted 50 lines · Daniel P. Berrange

Add a generic framework for support different block encryption formats. Upon instantiating a QCryptoBlock object, it will read the encryption header and extract the encryption keys. It is then possible to call methods to encrypt/decrypt data buffers.

There is also a mode whereby it will create/initialize a new encryption header on a previously unformatted volume.

The initial framework comes with support for the legacy QCow AES based encryption. This enables code in the QCow driver to be consolidated later.

---
 crypto/Makefile.objs      |   2 +
 crypto/block-qcow.c       | 167 +++++++++++++++++++++++++++++
 crypto/block-qcow.h       |  28 +++++
 crypto/block.c            | 263 ++++++++++++++++++++++++++++++++++++++++++++++
 crypto/blockpriv.h        |  90 ++++++++++++++++
 include/crypto/block.h    | 233 ++++++++++++++++++++++++++++++++++++++++
 qapi/crypto.json          |  67 ++++++++++++
 tests/.gitignore          |   1 +
 tests/Makefile            |   2 +
 tests/test-crypto-block.c | 239 +++++++++++++++++++++++++++++++++++++++++
 10 files changed, 1092 insertions(+)
 create mode 100644 crypto/block-qcow.c
 create mode 100644 crypto/block-qcow.h
 create mode 100644 crypto/block.c
 create mode 100644 crypto/blockpriv.h
 create mode 100644 include/crypto/block.h
 create mode 100644 tests/test-crypto-block.c

+++ b/crypto/block-qcow.c

crypto/block-qcow.c new file +15 -0
@@ -0,0 +1,167 @@
+/*
+ * QEMU Crypto block device encryption QCow/QCow2 AES-CBC format
+ *
+ * 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.
+ *
Quoted 8 lines

crypto/block-qcow.c line 19

Quoted 4 lines
crypto/block-qcow.c new file +4 -0
+ * 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/>.
+ *
+ */

Maybe worth a big comment stating that this file exists for backwards compatibility, and no one in their right mind should copy the code and/or encrypt new files with it.

Heh, yeah.

Quoted 10 lines

crypto/block-qcow.c line 31

Quoted 6 lines
crypto/block-qcow.c new file +6 -0
+static gboolean
+qcrypto_block_qcow_has_format(const uint8_t *buf G_GNUC_UNUSED,
+                              size_t buf_size G_GNUC_UNUSED)
+{
+    return false;
+}

When I see gboolean, I think TRUE/FALSE. Yes, C99 'false' happens to promote to the correct value for whatever integer type gboolean is, but this would read nicer if it returned 'bool'.

Yeah, dunno what I was thinking really. I use gboolean in a few places due to the gmainloop callback API contract, but this should not have needed it.

Quoted 18 lines
Quoted 18 lines
crypto/block-qcow.c new file +18 -0
+static int
+qcrypto_block_qcow_init(QCryptoBlock *block,
+                        const char *keysecret,
+                        Error **errp)
+{
+    char *password;
+    int ret;
+    uint8_t keybuf[16];
+    int len, i;
+
+    memset(keybuf, 0, 16);
+
+    password = qcrypto_secret_lookup_as_utf8(keysecret, errp);
+    if (!password) {
+        return -1;
+    }
+
+    len = strlen(password);
Quoted 8 lines

crypto/block-qcow.c line 57

Quoted 6 lines
crypto/block-qcow.c new file +6 -0
+    if (len > 16) {
+        len = 16;
+    }
+    for (i = 0; i < len; i++) {
+        keybuf[i] = password[i];
+    }

What - we really throw away anything longer than 16 bytes?

Yes, that's how awesome legacy qcow2 encryption is :-)

Quoted 1 line

Would a memcpy() be any nicer than an open-coded loop?

Sure.

Quoted 12 lines
Quoted 12 lines
crypto/blockpriv.h new file +11 -0
+++ b/crypto/blockpriv.h
 
+
+typedef struct QCryptoBlockDriver QCryptoBlockDriver;
+
+struct QCryptoBlock {
+    QCryptoBlockFormat format;
+
+    const QCryptoBlockDriver *driver;
+    void *opaque;
+
+    QCryptoCipher *cipher;
Quoted 8 lines

crypto/blockpriv.h line 38

Quoted 4 lines
crypto/blockpriv.h new file +4 -0
+    QCryptoIVGen *ivgen;
+    QCryptoHashAlgorithm kdfhash;
+    size_t niv;
+    uint64_t payload_offset; /* In 512 byte sectors */

Someday, we may want to support 4k sectors natively. I don't envy the person making the conversion, but we could at least make their life easier by representing this in bytes instead of units of 512-byte sectors.

Ok will do.

Quoted 11 lines

crypto/blockpriv.h line 47

Quoted 9 lines
crypto/blockpriv.h new file +9 -0
+};
+
+struct QCryptoBlockDriver {
+    int (*open)(QCryptoBlock *block,
+                QCryptoBlockOpenOptions *options,
+                QCryptoBlockReadFunc readfunc,
+                void *opaque,
+                unsigned int flags,
+                Error **errp);

No documentation on any of these contracts?

They're essentially identical to the public API contracts, so I figured it was redundant to duplicate those docs.

Quoted 7 lines
Quoted 7 lines

+/**
+ * qcrypto_block_has_format:
+ * @format: the encryption format
+ * @buf: the data from head of the volume
+ * @len: the length of @buf in bytes
+ *
+ * Given @len bytes of data from the head of a storage volume

Quoted 8 lines
Quoted 6 lines

+ * in @buf, probe to determine if the volume has the encryption
+ * format specified in @format.
+ *
+ * Returns: true if the data in @buf matches @format
+ */
+gboolean qcrypto_block_has_format(QCryptoBlockFormat format,

Again, this should probably be 'bool', not gboolean.

Yep

Quoted 4 lines
Quoted 4 lines
crypto/block.c new file +4 -0
+QCryptoBlock *qcrypto_block_create(QCryptoBlockCreateOptions *options,
+                                   QCryptoBlockInitFunc initfunc,
+                                   QCryptoBlockWriteFunc writefunc,
+                                   void *opaque,
Quoted 8 lines

include/crypto/block.h line 144

Quoted 6 lines
include/crypto/block.h new file +6 -0
+                                   Error **errp);
+
+/**
+ * @qcrypto_block_decrypt:
+ * @block: the block encryption object
+ * @startsector: the sector from which @buf was read

From the guest's point of view, right?

Yes & no, it is the sector of whatever underlying storage holds the image. If there are other formats beneath the crypto format it might not correspond to the guest OS seen sector.

Quoted 5 lines
Quoted 5 lines

+/**
+ * qcrypto_block_get_payload_offset:
+ * @block: the block encryption object
+ *
+ * Get the offset to the payload indicated by the

Quoted 8 lines
Quoted 6 lines

+ * encryption header. The offset is measured in
+ * 512 byte sectors
+ *
+ * Returns: the payload offset in sectors.
+ */
+uint64_t qcrypto_block_get_payload_offset(QCryptoBlock *block);

Please, let's use bytes here, not sectors.

Ok

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 :|
#28 lore raw

Re: [Qemu-devel] [PATCH v2 06/17] crypto: add block encryption framework

Quoted 27 lines · Daniel P. Berrange
Quoted 15 lines · Eric Blake
Quoted 12 lines · Daniel P. Berrange

Add a generic framework for support different block encryption formats. Upon instantiating a QCryptoBlock object, it will read the encryption header and extract the encryption keys. It is then possible to call methods to encrypt/decrypt data buffers.

There is also a mode whereby it will create/initialize a new encryption header on a previously unformatted volume.

The initial framework comes with support for the legacy QCow AES based encryption. This enables code in the QCow driver to be consolidated later.

Quoted 10 lines

crypto/block-qcow.c line 31

Quoted 6 lines
crypto/block-qcow.c new file +6 -0
+static gboolean
+qcrypto_block_qcow_has_format(const uint8_t *buf G_GNUC_UNUSED,
+                              size_t buf_size G_GNUC_UNUSED)
+{
+    return false;
+}

When I see gboolean, I think TRUE/FALSE. Yes, C99 'false' happens to promote to the correct value for whatever integer type gboolean is, but this would read nicer if it returned 'bool'.

Quoted 3 lines

Yeah, dunno what I was thinking really. I use gboolean in a few places due to the gmainloop callback API contract, but this should not have needed it.

To be honest, when I see 'gboolean', I _really_ think "Eww. Why did glib have to botch it?". Gnulib's <stdbool.h> replacement that gets C99 semantics in all but a few corner cases with a C89 compiler is so much nicer than glib's blatant wrong typing.

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
crypto/block-qcow.c new file +8 -0
+
+    len = strlen(password);
+    if (len > 16) {
+        len = 16;
+    }
+    for (i = 0; i < len; i++) {
+        keybuf[i] = password[i];
+    }
Quoted 3 lines
Quoted 1 line

What - we really throw away anything longer than 16 bytes?

Yes, that's how awesome legacy qcow2 encryption is :-)

I should have mentioned that I saw nothing with this part of your patch, and was just vocalizing my disgust at what code we are maintaining. But it looks like you got my meaning :)

Quoted 11 lines
Quoted 10 lines

crypto/blockpriv.h line 47

Quoted 8 lines
crypto/blockpriv.h new file +8 -0
+
+struct QCryptoBlockDriver {
+    int (*open)(QCryptoBlock *block,
+                QCryptoBlockOpenOptions *options,
+                QCryptoBlockReadFunc readfunc,
+                void *opaque,
+                unsigned int flags,
+                Error **errp);

No documentation on any of these contracts?

Quoted 2 lines

They're essentially identical to the public API contracts, so I figured it was redundant to duplicate those docs.

Fair enough. Although I probably could have been spared some confusion if you had done:

git config diff.orderFile /path/to/foo

the populated foo such that include/* comes before any other file. I recently learned that trick; it's also available as git format-patch -O/path/to/file (with no space after -O), and can make patches a lot easier to read when you focus the reader on interface first.

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

PATCH v2 7/17 crypto: implement the LUKS block encryption format

In reply to Daniel P. Berrange

Provide a block encryption implementation that follows the LUKS/dm-crypt specification.

This supports all combinations of hash, cipher algorithm, cipher mode and iv generator that are implemented by the current crypto layer.

The notable missing feature is support for the 'xts' cipher mode, which is commonly used for disk encryption instead of 'cbc'. This is because it is not provided by either nettle or libgcrypt. A suitable implementation will be identified & integrated later.

There is support for opening existing volumes formatted by dm-crypt, and for formatting new volumes. In the latter case it will only use key slot 0.

---
 crypto/Makefile.objs      |    1 +
 crypto/block-luks.c       | 1105 +++++++++++++++++++++++++++++++++++++++++++++
 crypto/block-luks.h       |   28 ++
 crypto/block.c            |    2 +
 qapi/crypto.json          |   43 +-
 tests/test-crypto-block.c |  104 +++++
 6 files changed, 1280 insertions(+), 3 deletions(-)
 create mode 100644 crypto/block-luks.c
 create mode 100644 crypto/block-luks.h
crypto/Makefile.objs +1 -0
index 25ca0c7..3299923 100644
@@ -20,6 +20,7 @@ crypto-obj-y += ivgen-plain64.o
 crypto-obj-y += afsplit.o
 crypto-obj-y += block.o
 crypto-obj-y += block-qcow.o
+crypto-obj-y += block-luks.o
 
 # Let the userspace emulators avoid linking gnutls/etc
 crypto-aes-obj-y = aes.o
crypto/block-luks.c new file +1105 -0

1,105 lines not on this page · raw message

crypto/block-luks.h new file +28 -0
new file mode 100644
index 0000000..0934138
@@ -0,0 +1,28 @@
+/*
+ * QEMU Crypto block device encryption LUKS format
+ *
+ * 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/>.
+ *
+ */
+
+#ifndef QCRYPTO_BLOCK_LUKS_H__
+#define QCRYPTO_BLOCK_LUKS_H__
+
+#include "crypto/blockpriv.h"
+
+extern const QCryptoBlockDriver qcrypto_block_driver_luks;
+
+#endif /* QCRYPTO_BLOCK_LUKS_H__ */
crypto/block.c +2 -0
index 757e28a..860ecce 100644
@@ -20,9 +20,11 @@
 
 #include "crypto/blockpriv.h"
 #include "crypto/block-qcow.h"
+#include "crypto/block-luks.h"
 
 static const QCryptoBlockDriver *qcrypto_block_drivers[] = {
     [Q_CRYPTO_BLOCK_FORMAT_QCOW] = &qcrypto_block_driver_qcow,
+    [Q_CRYPTO_BLOCK_FORMAT_LUKS] = &qcrypto_block_driver_luks,
 };
 
 
qapi/crypto.json +40 -3

69 lines not on this page · raw message

tests/test-crypto-block.c +104 -0

116 lines not on this page · raw message

Signature · 1 line
2.5.0
#30 lore raw

Re: [Qemu-devel] [PATCH v2 07/17] crypto: implement the LUKS block encryption format

Quoted 24 lines · Daniel P. Berrange

Provide a block encryption implementation that follows the LUKS/dm-crypt specification.

This supports all combinations of hash, cipher algorithm, cipher mode and iv generator that are implemented by the current crypto layer.

The notable missing feature is support for the 'xts' cipher mode, which is commonly used for disk encryption instead of 'cbc'. This is because it is not provided by either nettle or libgcrypt. A suitable implementation will be identified & integrated later.

There is support for opening existing volumes formatted by dm-crypt, and for formatting new volumes. In the latter case it will only use key slot 0.

---

+++ b/crypto/block-luks.c

crypto/block-luks.c new file +2 -0
@@ -0,0 +1,1105 @@
+/*
+ * QEMU Crypto block device encryption LUKS format

crypto/block-luks.c line 43

Quoted 10 lines
crypto/block-luks.c new file +9 -0
+ *
 
+
+/*
+ * Reference for format is
+ *
+ * docs/on-disk-format.pdf
+ *
+ * In 'cryptsetup' package source code
+ *

Worth calling out the document version number? I reviewed based on version 1.2.1, dated Oct 2011.

Quoted 5 lines

+ */

crypto/block-luks.c new file +4 -0
+
+typedef struct QCryptoBlockLUKS QCryptoBlockLUKS;
+typedef struct QCryptoBlockLUKSHeader QCryptoBlockLUKSHeader;
+typedef struct QCryptoBlockLUKSKeySlot QCryptoBlockLUKSKeySlot;

crypto/block-luks.c line 58

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+
+#define QCRYPTO_BLOCK_LUKS_VERSION 1
+
+#define QCRYPTO_BLOCK_LUKS_MAGIC_LEN 6
+#define QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN 32
+#define QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN 32
+#define QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN 32
+#define QCRYPTO_BLOCK_LUKS_DIGEST_LEN 20
+#define QCRYPTO_BLOCK_LUKS_SALT_LEN 32
+#define QCRYPTO_BLOCK_LUKS_UUID_LEN 40

Matches the spec, but seems awfully wasteful. A binary UUID is 16 bytes; the standard ASCII representation is only 36 bytes. But the spec calls it out as char[] (requiring a 37th byte for a NUL terminator, then rounding it up for aligned field access).

crypto/block-luks.c line 66

Quoted 8 lines
crypto/block-luks.c new file +8 -0
+#define QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS 8
+#define QCRYPTO_BLOCK_LUKS_STRIPES 4000
+#define QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS 1000
+#define QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS 1000
+#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET 4096
+
+#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED 0x0000DEAD
+#define QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED 0x00AC71F3

Cute l33t spelling choice by the upstream folks :)

crypto/block-luks.c line 100

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+
+static const QCryptoBlockLUKSCipherSizeMap
+qcrypto_block_luks_cipher_size_map_aes[] = {
+    { 16, QCRYPTO_CIPHER_ALG_AES_128 },
+    { 24, QCRYPTO_CIPHER_ALG_AES_192 },
+    { 32, QCRYPTO_CIPHER_ALG_AES_256 },
+    { 0, 0 },
+};
+
+static const QCryptoBlockLUKSCipherNameMap
+qcrypto_block_luks_cipher_name_map[] = {
+    { "aes", qcrypto_block_luks_cipher_size_map_aes, },

Inconsistent on the use of trailing , within the inner {} between these two arrays.

crypto/block-luks.c line 106

Quoted 6 lines
crypto/block-luks.c new file +6 -0
+};
+
+
+struct QCryptoBlockLUKSKeySlot {
+    /* state of keyslot, enabled/disable */
+    uint32_t active;

May be worth a comment that this struct is written to disk in big-endian, but used in native-endian for most operations for convenience; to make sure future developers remember to put byteswaps in the correct locations. But it looks like you handled endianness correctly.

crypto/block-luks.c line 115

Quoted 9 lines
crypto/block-luks.c new file +9 -0
+    /* iterations for PBKDF2 */
+    uint32_t iterations;
+    /* salt for PBKDF2 */
+    uint8_t salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
+    /* start sector of key material */
+    uint32_t key_offset;
+    /* number of anti-forensic stripes */
+    uint32_t stripes;
+} QEMU_PACKED;

Packed makes sense since we are writing it straight to disk; although it looks like natural alignment prevails and this did not need to be packed. Do we want some sort of BUG_ON() that we have the right size struct?

crypto/block-luks.c line 124

Quoted 9 lines
crypto/block-luks.c new file +9 -0
+
+struct QCryptoBlockLUKSHeader {
+    /* 'L', 'U', 'K', 'S', '0xBA', '0xBE' */
+    char magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN];
+
+    /* LUKS version, currently 1 */
+    uint16_t version;
+
+    /* cipher name specification (aes, etc */

Missing )

crypto/block-luks.c line 127

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+    char cipher_name[QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN];
+
+    /* cipher mode specification () */

text in the ()?

crypto/block-luks.c line 130

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+    char cipher_mode[QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN];
+
+    /* hash specication () */

s/specication/specification/, text in the ()?

crypto/block-luks.c line 134

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+    char hash_spec[QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN];
+
+    /* start offset of the volume data (in sectors) */
+    uint32_t payload_offset;

Should we say "in 512-byte sectors"? I could not see anything in the LUKS specification that said whether SECTOR_SIZE can be larger than 512
- if you have a bare metal 4k sector disk, does a payload_offset of 2 mean 1024 or 8192 bytes into the disk? Eww. Sounds like we should submit a bug against the LUKS spec to have it clarified.

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+
+    /* Number of key bytes */
+    uint32_t key_bytes;
+

crypto/block-luks.c line 148

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+    /* master key checksum after PBKDF2 */
+    uint8_t master_key_digest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
+
+    /* salt for master key PBKDF2 */
+    uint8_t master_key_salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
+
+    /* iterations for master key PBKDF2 */
+    uint32_t master_key_iterations;
+
+    /* UUID of the partition */

Should we say "in standard ASCII representation"?

crypto/block-luks.c line 153

Quoted 5 lines
crypto/block-luks.c new file +5 -0
+    uint8_t uuid[QCRYPTO_BLOCK_LUKS_UUID_LEN];
+
+    /* key slots */
+    QCryptoBlockLUKSKeySlot key_slots[QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS];
+} QEMU_PACKED;

Again, alignment should mean that we could get away without packing; but the packing doesn't hurt; and a BUG_ON may be nice to ensure size.

crypto/block-luks.c line 185

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+}
+
+/* XXX doesn't QEMU already have a string -> enum val convertor ? */
+static int qcrypto_block_luks_name_lookup(const char *name,

Yes, spelled qapi_enum_parse(). Works if the enum was defined in a .json file.

Quoted 8 lines
crypto/block-luks.c new file +8 -0
+
+    error_setg(errp, "%s %s not supported", type, name);
+    return 0;
+}
+
+#define qcrypto_block_luks_cipher_mode_lookup(name, errp)               \
+    qcrypto_block_luks_name_lookup(name,                                \
+                                   QCryptoCipherMode_lookup,            \

crypto/block-luks.c line 214

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+                                   QCRYPTO_CIPHER_MODE__MAX,            \
+                                   "Cipher mode",                       \
+                                   errp)
+
+#define qcrypto_block_luks_hash_name_lookup(name, errp)                 \
+    qcrypto_block_luks_name_lookup(name,                                \
+                                   QCryptoHashAlgorithm_lookup,         \
+                                   QCRYPTO_HASH_ALG__MAX,               \
+                                   "Hash algorithm",                    \
+                                   errp)

That said, your macro wrappers tweak the error message, so that it is perhaps more legible than the standard failure mode of qapi_enum_parse(). So up to you if you want to keep the wrappers.

Quoted 23 lines
crypto/block-luks.c new file +23 -0
+/*
+ * Given a key slot, and user password, this will attempt to unlock
+ * the master encryption key from the key slot
+ */
+static int
+qcrypto_block_luks_load_key(QCryptoBlock *block,
+                            QCryptoBlockLUKSKeySlot *slot,
+                            const char *password,
+                            QCryptoCipherAlgorithm cipheralg,
+                            QCryptoCipherMode ciphermode,
+                            QCryptoHashAlgorithm hash,
+                            QCryptoIVGenAlgorithm ivalg,
+                            QCryptoHashAlgorithm ivhash,
+                            uint8_t *masterkey,
+                            size_t masterkeylen,
+                            QCryptoBlockReadFunc readfunc,
+                            void *opaque,
+                            Error **errp)
+{
+    QCryptoBlockLUKS *luks = block->opaque;
+    uint8_t *splitkey;
+    size_t splitkeylen;
+    uint8_t *possiblekey;

crypto/block-luks.c line 273

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+    int ret = -1;
+    ssize_t rv;
+    QCryptoCipher *cipher = NULL;
+    uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
+    QCryptoIVGen *ivgen = NULL;
+    size_t niv;
+
+    if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
+        return 0;
+    }

Would be worth documenting the convention of '0' (no key found, but no errp set), '1' (successful key), and negative (errp set).

crypto/block-luks.c line 275

Quoted 2 lines
crypto/block-luks.c new file +2 -0
+
+    splitkeylen = masterkeylen * slot->stripes;

Should we do any validation that masterkeylen was in bounds and this doesn't overflow? I don't want a malicious byte stream masquerading as a LUKS header to cause us to misbehave.

For that matter, the spec states that luks->payload_offset is a write-once calculation at creation time, and that it could be recomputed from key layout. Should we validate that the offset listed makes algorithmic sense with what we know about header and key data sizes for the parameters listed in the header?

Side note: I'm a bit surprised the upstream LUKS spec does not include any checksum over the header contents - it does a great job at ensuring the master key is only going to be found by someone knowing a correct password and that a single byte error in a key material section invalidates that entire slot's usefulness, but it is not as careful on what happens with certain single-byte errors in the header.

Quoted 18 lines
crypto/block-luks.c new file +18 -0
+    splitkey = g_new0(uint8_t, splitkeylen);
+    possiblekey = g_new0(uint8_t, masterkeylen);
+
+    /*
+     * The user password is used to generate a (possible)
+     * decryption key. This may or may not successfully
+     * decrypt the master key - we just blindly assume
+     * the key is correct and validate the results of
+     * decryption later.
+     */
+    if (qcrypto_pbkdf2(hash,
+                       (const uint8_t *)password, strlen(password),
+                       slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                       slot->iterations,
+                       possiblekey, masterkeylen,
+                       errp) < 0) {
+        goto cleanup;
+    }

crypto/block-luks.c line 303

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+
+    /*
+     * We need to read the master key material from the
+     * LUKS key material header. What we're reading is
+     * not the raw master key, but rather the data after
+     * it has been passed through AFSplit and the result
+     * then encrypted.
+     */
+    rv = readfunc(block,
+                  slot->key_offset * 512ll,

I tend to write LL rather than ll, to make it obvious I didn't typo '1'.
Looks like we're hard-coding our sector size (not the first time); but
maybe a constant instead of a magic number will make it easier for the poor guy down the road that tries to switch to 4k sectors.

...

crypto/block-luks.c line 351

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+
+    /*
+     * Now we're decrypted the split master key, join

s/we're/that we've/

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+     * it back together to get the actual master key.
+     */
+    if (qcrypto_afsplit_decode(hash,

...

crypto/block-luks.c line 392

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+
+    if (memcmp(keydigest, luks->header.master_key_digest,
+               QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
+        /* Success, we got the right master key */
+        ret = 1;
+        goto cleanup;
+    }
+
+    /* Fail, user's password was not valid for this key slot,
+     * tell caller to try another slot */
+    ret = 0;
+

Matches the spec. Yay!

Side observation: The LUKS spec doesn't say anything about parallelizing the lookup loop across all 8 key slots, nor any randomization on which slot should be attempted first. The whole point of PBKDF2 iteration count is to burn CPU time so that an attacker can't brute force things easily. That means it is VERY easy to tell by timing how many active slots were attempted before a key was found, if slots are tried serially and we immediately break the loop on the first successful decryption. Is there any information leak caused by the timing observations when serially searching among 8 active slots, when the master key is only found in slot 7 vs. slot 0? But I don't see it as your problem to solve, so much as something to ask the upstream LUKS design team.

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+
+
+static int
+qcrypto_block_luks_open(QCryptoBlock *block,

crypto/block-luks.c

Quoted 10 lines
crypto/block-luks.c new file +9 -0
+                        QCryptoBlockOpenOptions *options,
+                        QCryptoBlockReadFunc readfunc,
+                        void *opaque,
+                        unsigned int flags,
+                        Error **errp)
+{
 
+    /*
+     * The cipher_mode header contains a string that we have
+     * to further parse of the format

s/parse/parse,/

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+     *
+     *    <cipher-mode>-<iv-generator>[:<iv-hash>]
+     *
+     * eg  cbc-essiv:sha256, cbc-plain64

crypto/block-luks.c line 553

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+     */
+    ivgen_name = strchr(luks->header.cipher_mode, '-');
+    if (!ivgen_name) {
+        ret = -EINVAL;
+        error_setg(errp, "Unexpected cipher mode string format %s",
+                   luks->header.cipher_mode);
+        goto fail;
+    }
+    *ivgen_name = '\0';
+    ivgen_name++;

We're modifying luks->header in place; we'd better not write it back out to disk in the modified form. I guess you are okay for now - your code only reads existing LUKS disks, and can only create a single key in slot 0 on conversion (that is, I don't see code for key management of an existing image). Probably things we should add later, though, at which point we'll need to be careful that we don't overwrite too much in the header.

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+    block->payload_offset = luks->header.payload_offset;

Earlier, I argued that block->payload_offset should be in bytes. You are constrained that luks->header.payload_offset is in sectors, but we need not propagate that craziness any higher.

Quoted 9 lines
crypto/block-luks.c new file +9 -0
+
+static int
+qcrypto_block_luks_create(QCryptoBlock *block,
+                          QCryptoBlockCreateOptions *options,
+                          QCryptoBlockInitFunc initfunc,
+                          QCryptoBlockWriteFunc writefunc,
+                          void *opaque,
+                          Error **errp)
+{

crypto/block-luks.c line 699

Quoted 10 lines
crypto/block-luks.c new file +9 -0
 
+
+    memcpy(&luks_opts, options->u.luks, sizeof(luks_opts));
+    if (!luks_opts.has_cipher_alg) {
+        luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
+    }
+    if (!luks_opts.has_cipher_mode) {
+        /* XXX switch to XTS */
+        luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_CBC;
+    }

Yeah, my (quick) reading made it seem like XTS is a slightly more secure default than CBC. But as you said, XTS implementation will come later.

crypto/block-luks.c line 726

Quoted 7 lines
crypto/block-luks.c new file +7 -0
+    luks = g_new0(QCryptoBlockLUKS, 1);
+    block->opaque = luks;
+
+    memcpy(luks->header.magic, qcrypto_block_luks_magic,
+           QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
+
+    luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;

Maybe a comment here that endianness will be addressed later, as a lot of code appears between here and the actual write-to-disk.

crypto/block-luks.c line 738

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+    uuid_generate(uuid);
+    uuid_unparse(uuid, (char *)luks->header.uuid);
+
+    switch (luks_opts.cipher_alg) {
+    case QCRYPTO_CIPHER_ALG_AES_128:
+    case QCRYPTO_CIPHER_ALG_AES_192:
+    case QCRYPTO_CIPHER_ALG_AES_256:
+        cipher_alg = "aes";
+        break;
+    default:
+        error_setg(errp, "Cipher algorithm is not supported");
+        goto error;

That is, we aren't supporting "twofish", "serpent", "cast5", or "cast6".
Fine for now.

crypto/block-luks.c line 749

Quoted 11 lines
crypto/block-luks.c new file +11 -0
+    }
+
+    cipher_mode = QCryptoCipherMode_lookup[luks_opts.cipher_mode];
+    ivgen_alg = QCryptoIVGenAlgorithm_lookup[luks_opts.ivgen_alg];
+    if (luks_opts.has_ivgen_hash_alg) {
+        ivgen_hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.ivgen_hash_alg];
+        cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
+                                           ivgen_hash_alg);
+    } else {
+        cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
+    }

Should we validate that the mode spec is among the set documented by the LUKS spec ("ecb", "cbc-plain", "cbc-essiv:hash", "xts-plain64") (well, we don't support xts yet), and reject combinations that aren't supported ("cbc-plain64" comes to mind as something the LUKS spec doesn't allow, even though we have the pieces to logically make it happen)?

Quoted 1 line

+ hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.hash_alg];

Likewise, should we validate that the hash is one of the specified names ("sha1", "sha256", "sha512", "ripemd160")?

crypto/block-luks.c line 774

Quoted 7 lines
crypto/block-luks.c new file +7 -0
+
+    memcpy(luks->header.cipher_name, cipher_alg,
+           strlen(cipher_alg) + 1);
+    memcpy(luks->header.cipher_mode, cipher_mode_spec,
+           strlen(cipher_mode_spec) + 1);
+    memcpy(luks->header.hash_spec, hash_alg,
+           strlen(hash_alg) + 1);

Couldn't these just be strcpy()?

crypto/block-luks.c line 819

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+
+    /* Determine how many iterations we need to hash the master
+     * key with in order to have 1 second of compute time used

s/with //

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+     */
+    luks->header.master_key_iterations =
+        qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,
+                                   masterkey, luks->header.key_bytes,

crypto/block-luks.c line 833

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+                                   luks->header.master_key_salt,
+                                   QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                                   &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        goto error;
+    }
+
+    /* Why /= 8 ?  That matches cryptsetup, but there's no
+     * explanation why they chose /= 8... */

My guess? There's 8 key slots, and if all 8 are active, you'll spend 1 second serially decrypting each of them. Users got ticked waiting that long, so the /=8 reduces it to 125ms per slot, and for the typical use case of slot0 being the user's password, much faster response at opening the device. But that's a guess - you're right that it could be documented better.

Quoted 17 lines
crypto/block-luks.c new file +17 -0
+    luks->header.master_key_iterations /= 8;
+    luks->header.master_key_iterations = MAX(
+        luks->header.master_key_iterations,
+        QCRYPTO_BLOCK_LUKS_MIN_MASTER_KEY_ITERS);
+
+
+    /* Hash the master key, saving the result in the LUKS
+     * header. This hash is used when opening the encrypted
+     * device to verify that the user password unlocked a
+     * valid master key
+     */
+    if (qcrypto_pbkdf2(luks_opts.hash_alg,
+                       masterkey, luks->header.key_bytes,
+                       luks->header.master_key_salt,
+                       QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                       luks->header.master_key_iterations,
+                       luks->header.master_key_digest,

crypto/block-luks.c line 860

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+                       QCRYPTO_BLOCK_LUKS_DIGEST_LEN,
+                       errp) < 0) {
+        goto error;
+    }
+
+
+    /* Although LUKS has multiple key slots, we're just going
+     * to use the first key slot */
+
+    splitkeylen = luks->header.key_bytes * QCRYPTO_BLOCK_LUKS_STRIPES;

The LUKS spec says that it is okay to allow the user to specify stripes.
Should that be one of our options, with a sane default? But it can be
added later as a followup, this patch is already quite big and I'm fine with hardcoding stripes for now.

crypto/block-luks.c line 869

Quoted 9 lines
crypto/block-luks.c new file +9 -0
+    for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
+        luks->header.key_slots[i].active = i == 0 ?
+            QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED :
+            QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
+        luks->header.key_slots[i].stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
+        luks->header.key_slots[i].key_offset =
+            (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512) +
+            (ROUND_UP(((splitkeylen + 511) / 512),
+                      (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512)) * i);

Eww. The spec seems buggy, saying:

Quoted 3 lines

// integer divisions, result rounded down:
baseOffset = (size of phdr)/SECTOR SIZE + 1 keymaterialSectors = (stripes*masterKeyLength)/SECTOR SIZE + 1

First, look at the calculation of baseOffset. Since size of phdr is 592 bytes, and that is NOT a SECTOR SIZE in any disk I know of, that makes sense that baseOffset will be at least 2 (512-byte) sectors into the disk, or, if SECTOR SIZE is 4, that will result in an offset of 1 (4096-byte) sector. However, you've defined QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET as 4096, which means for our 512-byte sector usage, you are setting the first key material at sector 4 no matter what. I guess that matches what cryptsetup does? Maybe worth a comment?

Now, look at the calculation of keymaterial Sectors. The algorithm in the spec mishandles the case where stripes happens to be an exact multiple of sector size (that is, for a keysize of 20 bytes coupled with 512 stripes, it would reserve 21 sectors rather than the 20 actually required). I think your use of ROUND_UP() makes more sense, but it would be nice to file a bug against the LUKS spec to have them fix their math, and/or document that it is okay to use values larger than the absolute minimum.

Quoted 13 lines
crypto/block-luks.c new file +13 -0
+    }
+
+    if (qcrypto_random_bytes(luks->header.key_slots[0].salt,
+                             QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                             errp) < 0) {
+        goto error;
+    }
+
+    /* Again we determine how many iterations are required to
+     * hash the user password while consuming 1 second of compute
+     * time */
+    luks->header.key_slots[0].iterations =
+        qcrypto_pbkdf2_count_iters(luks_opts.hash_alg,

crypto/block-luks.c line 892

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+                                   (uint8_t *)password, strlen(password),
+                                   luks->header.key_slots[0].salt,
+                                   QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                                   &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
+        goto error;
+    }
+    /* Why /= 2 ?  That matches cryptsetup, but there's no
+     * explanation why they chose /= 2... */

Again, guessing that half a second feels nicer than 1 second for responsiveness.

crypto/block-luks.c line 937

Quoted 11 lines
crypto/block-luks.c new file +10 -0
+    luks->header.key_slots[0].iterations /= 2;
+    luks->header.key_slots[0].iterations = MAX(
+        luks->header.key_slots[0].iterations,
+        QCRYPTO_BLOCK_LUKS_MIN_SLOT_KEY_ITERS);
+
 
+
+    /* Before storing the master key, we need to vastly
+     * increase its size, as protection against forensic
+     * disk data recovery */
+    splitkey = g_new0(uint8_t, splitkeylen);

If we later add the ability to do key management on an active disk, this allocation may be large enough that it would warrant the _try variant and reporting ENOMEM, rather than failing.

crypto/block-luks.c line 960

Quoted 5 lines
crypto/block-luks.c new file +5 -0
+    }
+
+
+
+    /* The total size of the LUKS headers is the partition header + key

Three blank lines?

crypto/block-luks.c line 970

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+     * slot headers, rounded up to the nearest sector, combined with
+     * the size of each master key material region, also rounded up
+     * to the nearest sector */
+    luks->header.payload_offset =
+        (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512) +
+        (ROUND_UP(((splitkeylen + 511) / 512),
+                  (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512)) *
+         QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
+
+    block->payload_offset = luks->header.payload_offset;

Again, I argue that block->payload_offset would be saner in bytes.

crypto/block-luks.c line 973

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+
+    /* Reserve header space to match payload offset */
+    initfunc(block, block->payload_offset * 512, &local_err, opaque);

Especially since initfunc() takes bytes.

Quoted 11 lines
crypto/block-luks.c new file +10 -0
+    if (local_err) {
+        error_propagate(errp, local_err);
+        goto error;
+    }
+
+    /* Everything on disk uses Big Endian, so flip header fields
+     * before writing them */
 
+
+    /* Write out the master key material, starting at the
+     * sector immediately following the partition header. */

crypto/block-luks.c line 1033

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+    if (writefunc(block,
+                  luks->header.key_slots[0].key_offset * 512,
+                  splitkey, splitkeylen,
+                  errp,
+                  opaque) != splitkeylen) {
+        goto error;
+    }
+
+    memset(masterkey, 0, luks->header.key_bytes);
+    g_free(masterkey);

Nice, trying to avoid leaking the key from a heap attack.

crypto/block-luks.c line 1082

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+
+static int
+qcrypto_block_luks_decrypt(QCryptoBlock *block,
+                           uint64_t startsector,
+                           uint8_t *buf,
+                           size_t len,
+                           Error **errp)
+{
+    return qcrypto_block_decrypt_helper(block->cipher,
+                                        block->niv, block->ivgen,
+                                        startsector, buf, len, errp);
+}

What happens when we try to read a LUKS device with 4k sectors? Worth worrying about, maybe just as a comment that we are hard-coded to 512 bytes at the moment?

Quoted 17 lines

+++ b/qapi/crypto.json

qapi/crypto.json +2 -1
@@ -102,12 +102,13 @@
 #
 # @qcow: QCow/QCow2 built-in AES-CBC encryption. Use only
 #        for liberating data from old images.
+# @luks: LUKS encryption format. Recommended for new images
 #
 # Since: 2.6
 ##
 { 'enum': 'QCryptoBlockFormat',
 #  'prefix': 'QCRYPTO_BLOCK_FORMAT',
-  'data': ['qcow']}
+  'data': ['qcow', 'luks']}
 
 ##
 # QCryptoBlockOptionsBase:

qapi/crypto.json line 145

Quoted 9 lines
qapi/crypto.json +6 -0
@@ -136,6 +137,40 @@
   'data': { '*key-secret': 'str' }}
 
 ##
+# QCryptoBlockOptionsLUKS:
+#
+# The options that apply to LUKS encryption format
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing the
+#              decryption key

Maybe add "Mandatory except when probing the image for metadata only"

Quoted 6 lines
qapi/crypto.json +6 -0
+# Since: 2.6
+##
+{ 'struct': 'QCryptoBlockOptionsLUKS',
+  'data': { '*key-secret': 'str' }}
+
+

qapi/crypto.json line 161

Quoted 10 lines
qapi/crypto.json +10 -0
+##
+# QCryptoBlockCreateOptionsLUKS:
+#
+# The options that apply to LUKS encryption format initialization
+#
+# @cipher-alg: #optional the cipher algorithm for data encryption
+# @cipher-mode: #optional the cipher mode for data encryption
+# @ivgen-alg: #optional the initialization vector generator
+# @ivgen-hash-alg: #optional the initialization vector generator hash
+# @hash-alg: #optional the master key hash algorithm

Would be nice to mention the defaults, particularly since we may later change the default from cbc to xts.

qapi/crypto.json line 171

Quoted 10 lines
qapi/crypto.json +10 -0
+# Since: 2.6
+##
+{ 'struct': 'QCryptoBlockCreateOptionsLUKS',
+  'base': 'QCryptoBlockOptionsLUKS',
+  'data': { '*cipher-alg': 'QCryptoCipherAlgorithm',
+            '*cipher-mode': 'QCryptoCipherMode',
+            '*ivgen-alg': 'QCryptoIVGenAlgorithm',
+            '*ivgen-hash-alg': 'QCryptoHashAlgorithm',
+            '*hash-alg': 'QCryptoHashAlgorithm'}}
+

As mentioned earlier, we might also want to make stripes be customizable.

tests/test-crypto-block.c static QCryptoBlockOpenOptions qcow_open_opts = { · line 46

Quoted 9 lines
tests/test-crypto-block.c +4 -0
+++ b/tests/test-crypto-block.c
@@ -40,6 +40,69 @@ static QCryptoBlockOpenOptions qcow_open_opts = {
     .u.qcow = &qcow_opts,
 };
 
 
+    {
+        .path = "/crypto/block/luks/aes-256-cbc-eesiv",
+        .create_opts = &luks_create_opts_aes256_cbc_essiv,

s/eesiv/essiv/

Wow. A lot to read through, but looks mostly sane. v3 will probably be ready to go; meanwhile, I spotted enough typos in the LUKS spec that I'm half tempted to check out their source code and submit a patch.

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

Re: [Qemu-devel] [PATCH v2 07/17] crypto: implement the LUKS block encryption format

Quoted 21 lines · Eric Blake
Quoted 18 lines · Daniel P. Berrange

Provide a block encryption implementation that follows the LUKS/dm-crypt specification.

This supports all combinations of hash, cipher algorithm, cipher mode and iv generator that are implemented by the current crypto layer.

The notable missing feature is support for the 'xts' cipher mode, which is commonly used for disk encryption instead of 'cbc'. This is because it is not provided by either nettle or libgcrypt. A suitable implementation will be identified & integrated later.

There is support for opening existing volumes formatted by dm-crypt, and for formatting new volumes. In the latter case it will only use key slot 0.

Quoted 11 lines

crypto/block-luks.c line 43

Quoted 8 lines
crypto/block-luks.c new file +8 -0
+
+/*
+ * Reference for format is
+ *
+ * docs/on-disk-format.pdf
+ *
+ * In 'cryptsetup' package source code
+ *

Worth calling out the document version number? I reviewed based on version 1.2.1, dated Oct 2011.

Yep

Quoted 11 lines

crypto/block-luks.c line 106

Quoted 6 lines
crypto/block-luks.c new file +6 -0
+};
+
+
+struct QCryptoBlockLUKSKeySlot {
+    /* state of keyslot, enabled/disable */
+    uint32_t active;

May be worth a comment that this struct is written to disk in big-endian, but used in native-endian for most operations for convenience; to make sure future developers remember to put byteswaps in the correct locations. But it looks like you handled endianness correctly.

Yes, will note it.

Quoted 11 lines

crypto/block-luks.c line 115

Quoted 10 lines
crypto/block-luks.c new file +9 -0
+    /* iterations for PBKDF2 */
+    uint32_t iterations;
+    /* salt for PBKDF2 */
+    uint8_t salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
+    /* start sector of key material */
+    uint32_t key_offset;
+    /* number of anti-forensic stripes */
+    uint32_t stripes;
+} QEMU_PACKED;
Quoted 4 lines

Packed makes sense since we are writing it straight to disk; although it looks like natural alignment prevails and this did not need to be packed. Do we want some sort of BUG_ON() that we have the right size struct?

Yes, I'll add QEMU_BUILD_BUG_ON

Quoted 16 lines

crypto/block-luks.c line 124

Quoted 9 lines
crypto/block-luks.c new file +9 -0
+
+struct QCryptoBlockLUKSHeader {
+    /* 'L', 'U', 'K', 'S', '0xBA', '0xBE' */
+    char magic[QCRYPTO_BLOCK_LUKS_MAGIC_LEN];
+
+    /* LUKS version, currently 1 */
+    uint16_t version;
+
+    /* cipher name specification (aes, etc */

Missing )

crypto/block-luks.c line 127

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+    char cipher_name[QCRYPTO_BLOCK_LUKS_CIPHER_NAME_LEN];
+
+    /* cipher mode specification () */
Quoted 7 lines

text in the ()?

crypto/block-luks.c line 130

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+    char cipher_mode[QCRYPTO_BLOCK_LUKS_CIPHER_MODE_LEN];
+
+    /* hash specication () */

s/specication/specification/, text in the ()?

Will fix all these examples

Quoted 11 lines

crypto/block-luks.c line 134

Quoted 5 lines
crypto/block-luks.c new file +4 -0
+    char hash_spec[QCRYPTO_BLOCK_LUKS_HASH_SPEC_LEN];
+
+    /* start offset of the volume data (in sectors) */
+    uint32_t payload_offset;

Should we say "in 512-byte sectors"? I could not see anything in the LUKS specification that said whether SECTOR_SIZE can be larger than 512
- if you have a bare metal 4k sector disk, does a payload_offset of 2 mean 1024 or 8192 bytes into the disk? Eww. Sounds like we should submit a bug against the LUKS spec to have it clarified.

cryptsetup is hardcoded to use 512 byte sectors currently. IIUC they'll need a LUKS spec update before doing 4k sectors natively.

Quoted 18 lines
Quoted 5 lines
crypto/block-luks.c new file +4 -0
+
+    /* Number of key bytes */
+    uint32_t key_bytes;
+

crypto/block-luks.c line 148

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+    /* master key checksum after PBKDF2 */
+    uint8_t master_key_digest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
+
+    /* salt for master key PBKDF2 */
+    uint8_t master_key_salt[QCRYPTO_BLOCK_LUKS_SALT_LEN];
+
+    /* iterations for master key PBKDF2 */
+    uint32_t master_key_iterations;
+
+    /* UUID of the partition */

Should we say "in standard ASCII representation"?

Quoted 8 lines

crypto/block-luks.c line 153

Quoted 5 lines
crypto/block-luks.c new file +5 -0
+    uint8_t uuid[QCRYPTO_BLOCK_LUKS_UUID_LEN];
+
+    /* key slots */
+    QCryptoBlockLUKSKeySlot key_slots[QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS];
+} QEMU_PACKED;

Again, alignment should mean that we could get away without packing; but the packing doesn't hurt; and a BUG_ON may be nice to ensure size.

Yep, add QEMU_BUILD_BUG_ON

Quoted 21 lines

crypto/block-luks.c line 185

Quoted 2 lines
crypto/block-luks.c new file +2 -0
+/* XXX doesn't QEMU already have a string -> enum val convertor ? */
+static int qcrypto_block_luks_name_lookup(const char *name,

Yes, spelled qapi_enum_parse(). Works if the enum was defined in a .json file.

Quoted 14 lines
crypto/block-luks.c new file +14 -0
+
+    error_setg(errp, "%s %s not supported", type, name);
+    return 0;
+}
+
+#define qcrypto_block_luks_cipher_mode_lookup(name, errp)               \
+    qcrypto_block_luks_name_lookup(name,                                \
+                                   QCryptoCipherMode_lookup,            \
+                                   QCRYPTO_CIPHER_MODE__MAX,            \
+                                   "Cipher mode",                       \
+                                   errp)
+
+#define qcrypto_block_luks_hash_name_lookup(name, errp)                 \
+    qcrypto_block_luks_name_lookup(name,                                \
Quoted 8 lines

crypto/block-luks.c line 214

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+                                   QCryptoHashAlgorithm_lookup,         \
+                                   QCRYPTO_HASH_ALG__MAX,               \
+                                   "Hash algorithm",                    \
+                                   errp)

That said, your macro wrappers tweak the error message, so that it is perhaps more legible than the standard failure mode of qapi_enum_parse(). So up to you if you want to keep the wrappers.

I'll change my XXX note to mention qapi_enum_parse() as a future todo if we can improve its error reporting in some manner.

Quoted 24 lines
Quoted 24 lines
crypto/block-luks.c new file +24 -0
+static int
+qcrypto_block_luks_load_key(QCryptoBlock *block,
+                            QCryptoBlockLUKSKeySlot *slot,
+                            const char *password,
+                            QCryptoCipherAlgorithm cipheralg,
+                            QCryptoCipherMode ciphermode,
+                            QCryptoHashAlgorithm hash,
+                            QCryptoIVGenAlgorithm ivalg,
+                            QCryptoHashAlgorithm ivhash,
+                            uint8_t *masterkey,
+                            size_t masterkeylen,
+                            QCryptoBlockReadFunc readfunc,
+                            void *opaque,
+                            Error **errp)
+{
+    QCryptoBlockLUKS *luks = block->opaque;
+    uint8_t *splitkey;
+    size_t splitkeylen;
+    uint8_t *possiblekey;
+    int ret = -1;
+    ssize_t rv;
+    QCryptoCipher *cipher = NULL;
+    uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];
+    QCryptoIVGen *ivgen = NULL;
Quoted 8 lines

crypto/block-luks.c line 273

Quoted 5 lines
crypto/block-luks.c new file +5 -0
+    size_t niv;
+
+    if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {
+        return 0;
+    }

Would be worth documenting the convention of '0' (no key found, but no errp set), '1' (successful key), and negative (errp set).

Yes, will document that.

Quoted 5 lines
Quoted 1 line

+ splitkeylen = masterkeylen * slot->stripes;

Should we do any validation that masterkeylen was in bounds and this doesn't overflow? I don't want a malicious byte stream masquerading as a LUKS header to cause us to misbehave.

masterkeylen comes from luks->header.key_bytes. We should put some validation in for that earlier when we first get it off disk.

Quoted 5 lines

For that matter, the spec states that luks->payload_offset is a write-once calculation at creation time, and that it could be recomputed from key layout. Should we validate that the offset listed makes algorithmic sense with what we know about header and key data sizes for the parameters listed in the header?

While it says that the offsets could be recomputed, from a technical POV there's no reason why all impls must use the same layout / alignment for the key slots. So I feel it safer to just rely on the header values and not try to enforce that they match a particular offset.

Quoted 32 lines

Side note: I'm a bit surprised the upstream LUKS spec does not include any checksum over the header contents - it does a great job at ensuring the master key is only going to be found by someone knowing a correct password and that a single byte error in a key material section invalidates that entire slot's usefulness, but it is not as careful on what happens with certain single-byte errors in the header.

Quoted 25 lines
crypto/block-luks.c new file +25 -0
+    splitkey = g_new0(uint8_t, splitkeylen);
+    possiblekey = g_new0(uint8_t, masterkeylen);
+
+    /*
+     * The user password is used to generate a (possible)
+     * decryption key. This may or may not successfully
+     * decrypt the master key - we just blindly assume
+     * the key is correct and validate the results of
+     * decryption later.
+     */
+    if (qcrypto_pbkdf2(hash,
+                       (const uint8_t *)password, strlen(password),
+                       slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,
+                       slot->iterations,
+                       possiblekey, masterkeylen,
+                       errp) < 0) {
+        goto cleanup;
+    }
+
+    /*
+     * We need to read the master key material from the
+     * LUKS key material header. What we're reading is
+     * not the raw master key, but rather the data after
+     * it has been passed through AFSplit and the result
+     * then encrypted.
Quoted 8 lines

crypto/block-luks.c line 303

Quoted 3 lines
crypto/block-luks.c new file +3 -0
+     */
+    rv = readfunc(block,
+                  slot->key_offset * 512ll,

I tend to write LL rather than ll, to make it obvious I didn't typo '1'.
Looks like we're hard-coding our sector size (not the first time); but
maybe a constant instead of a magic number will make it easier for the poor guy down the road that tries to switch to 4k sectors.

I'll introduce a QCRYPTO_LUKS_SECTOR_SIZE constant throughout for now.

Quoted 20 lines
Quoted 3 lines
crypto/block-luks.c new file +3 -0
+     * it back together to get the actual master key.
+     */
+    if (qcrypto_afsplit_decode(hash,

...

crypto/block-luks.c line 392

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+
+    if (memcmp(keydigest, luks->header.master_key_digest,
+               QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {
+        /* Success, we got the right master key */
+        ret = 1;
+        goto cleanup;
+    }
+
+    /* Fail, user's password was not valid for this key slot,
+     * tell caller to try another slot */
+    ret = 0;
+

Matches the spec. Yay!

Quoted 11 lines

Side observation: The LUKS spec doesn't say anything about parallelizing the lookup loop across all 8 key slots, nor any randomization on which slot should be attempted first. The whole point of PBKDF2 iteration count is to burn CPU time so that an attacker can't brute force things easily. That means it is VERY easy to tell by timing how many active slots were attempted before a key was found, if slots are tried serially and we immediately break the loop on the first successful decryption. Is there any information leak caused by the timing observations when serially searching among 8 active slots, when the master key is only found in slot 7 vs. slot 0? But I don't see it as your problem to solve, so much as something to ask the upstream LUKS design team.

FWIW, cryptsetup will short circuit the search as soon as it finds a valid slot, so we're matching their behaviour at least.

Quoted 30 lines

crypto/block-luks.c

Quoted 12 lines
crypto/block-luks.c new file +11 -0
+static int
+qcrypto_block_luks_open(QCryptoBlock *block,
+                        QCryptoBlockOpenOptions *options,
+                        QCryptoBlockReadFunc readfunc,
+                        void *opaque,
+                        unsigned int flags,
+                        Error **errp)
+{
 
+    /*
+     * The cipher_mode header contains a string that we have
+     * to further parse of the format

s/parse/parse,/

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+     *
+     *    <cipher-mode>-<iv-generator>[:<iv-hash>]
+     *
+     * eg  cbc-essiv:sha256, cbc-plain64

crypto/block-luks.c line 553

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+     */
+    ivgen_name = strchr(luks->header.cipher_mode, '-');
+    if (!ivgen_name) {
+        ret = -EINVAL;
+        error_setg(errp, "Unexpected cipher mode string format %s",
+                   luks->header.cipher_mode);
+        goto fail;
+    }
+    *ivgen_name = '\0';
+    ivgen_name++;
Quoted 7 lines

We're modifying luks->header in place; we'd better not write it back out to disk in the modified form. I guess you are okay for now - your code only reads existing LUKS disks, and can only create a single key in slot 0 on conversion (that is, I don't see code for key management of an existing image). Probably things we should add later, though, at which point we'll need to be careful that we don't overwrite too much in the header.

Yeah, certainly something to be careful of later.

Quoted 5 lines
Quoted 1 line

+ block->payload_offset = luks->header.payload_offset;

Earlier, I argued that block->payload_offset should be in bytes. You are constrained that luks->header.payload_offset is in sectors, but we need not propagate that craziness any higher.

Yes, I've made that change.

Quoted 19 lines
Quoted 8 lines
crypto/block-luks.c new file +8 -0
+static int
+qcrypto_block_luks_create(QCryptoBlock *block,
+                          QCryptoBlockCreateOptions *options,
+                          QCryptoBlockInitFunc initfunc,
+                          QCryptoBlockWriteFunc writefunc,
+                          void *opaque,
+                          Error **errp)
+{

crypto/block-luks.c line 699

Quoted 10 lines
crypto/block-luks.c new file +9 -0
 
+
+    memcpy(&luks_opts, options->u.luks, sizeof(luks_opts));
+    if (!luks_opts.has_cipher_alg) {
+        luks_opts.cipher_alg = QCRYPTO_CIPHER_ALG_AES_256;
+    }
+    if (!luks_opts.has_cipher_mode) {
+        /* XXX switch to XTS */
+        luks_opts.cipher_mode = QCRYPTO_CIPHER_MODE_CBC;
+    }
Quoted 2 lines

Yeah, my (quick) reading made it seem like XTS is a slightly more secure default than CBC. But as you said, XTS implementation will come later.

Yes, I still hope to post an XTS impl before 2.6, so if this code merges before 2.6, hopefully we'll stil have time to use XTS as the default too, matching cryptsetup

Quoted 10 lines

crypto/block-luks.c line 726

Quoted 7 lines
crypto/block-luks.c new file +7 -0
+    luks = g_new0(QCryptoBlockLUKS, 1);
+    block->opaque = luks;
+
+    memcpy(luks->header.magic, qcrypto_block_luks_magic,
+           QCRYPTO_BLOCK_LUKS_MAGIC_LEN);
+
+    luks->header.version = QCRYPTO_BLOCK_LUKS_VERSION;

Maybe a comment here that endianness will be addressed later, as a lot of code appears between here and the actual write-to-disk.

Will do

Quoted 28 lines

crypto/block-luks.c line 738

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+    uuid_generate(uuid);
+    uuid_unparse(uuid, (char *)luks->header.uuid);
+
+    switch (luks_opts.cipher_alg) {
+    case QCRYPTO_CIPHER_ALG_AES_128:
+    case QCRYPTO_CIPHER_ALG_AES_192:
+    case QCRYPTO_CIPHER_ALG_AES_256:
+        cipher_alg = "aes";
+        break;
+    default:
+        error_setg(errp, "Cipher algorithm is not supported");
+        goto error;

That is, we aren't supporting "twofish", "serpent", "cast5", or "cast6".
Fine for now.

crypto/block-luks.c line 749

Quoted 11 lines
crypto/block-luks.c new file +11 -0
+    }
+
+    cipher_mode = QCryptoCipherMode_lookup[luks_opts.cipher_mode];
+    ivgen_alg = QCryptoIVGenAlgorithm_lookup[luks_opts.ivgen_alg];
+    if (luks_opts.has_ivgen_hash_alg) {
+        ivgen_hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.ivgen_hash_alg];
+        cipher_mode_spec = g_strdup_printf("%s-%s:%s", cipher_mode, ivgen_alg,
+                                           ivgen_hash_alg);
+    } else {
+        cipher_mode_spec = g_strdup_printf("%s-%s", cipher_mode, ivgen_alg);
+    }
Quoted 5 lines

Should we validate that the mode spec is among the set documented by the LUKS spec ("ecb", "cbc-plain", "cbc-essiv:hash", "xts-plain64") (well, we don't support xts yet), and reject combinations that aren't supported ("cbc-plain64" comes to mind as something the LUKS spec doesn't allow, even though we have the pieces to logically make it happen)?

The spec appears to be non-exhaustive, in that cryptsetup / linux allow for cbc-plain64 and other combinations that aren't listed. So QEMU should follow that for interoperability.

Quoted 4 lines
Quoted 1 line

+ hash_alg = QCryptoHashAlgorithm_lookup[luks_opts.hash_alg];

Likewise, should we validate that the hash is one of the specified names ("sha1", "sha256", "sha512", "ripemd160")?

The only one we're permitting that's not listed there is 'md5' and that should fail anyway since it provides too small a digest size but I see we're not validating the digest size.

Quoted 9 lines

crypto/block-luks.c line 774

Quoted 7 lines
crypto/block-luks.c new file +7 -0
+
+    memcpy(luks->header.cipher_name, cipher_alg,
+           strlen(cipher_alg) + 1);
+    memcpy(luks->header.cipher_mode, cipher_mode_spec,
+           strlen(cipher_mode_spec) + 1);
+    memcpy(luks->header.hash_spec, hash_alg,
+           strlen(hash_alg) + 1);

Couldn't these just be strcpy()?

Yes

Quoted 9 lines

crypto/block-luks.c line 860

Quoted 4 lines
crypto/block-luks.c new file +4 -0
+    /* Although LUKS has multiple key slots, we're just going
+     * to use the first key slot */
+
+    splitkeylen = luks->header.key_bytes * QCRYPTO_BLOCK_LUKS_STRIPES;

The LUKS spec says that it is okay to allow the user to specify stripes.
Should that be one of our options, with a sane default? But it can be
added later as a followup, this patch is already quite big and I'm fine with hardcoding stripes for now.

Cryptsetup doesn't allow the user to specify the stripes value, just fixing it at 4k, so I figure we're best todo the same, otherwise we'll create images that cant be read by linux.

Quoted 27 lines

crypto/block-luks.c line 869

Quoted 10 lines
crypto/block-luks.c new file +9 -0
+    for (i = 0; i < QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS; i++) {
+        luks->header.key_slots[i].active = i == 0 ?
+            QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED :
+            QCRYPTO_BLOCK_LUKS_KEY_SLOT_DISABLED;
+        luks->header.key_slots[i].stripes = QCRYPTO_BLOCK_LUKS_STRIPES;
+        luks->header.key_slots[i].key_offset =
+            (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512) +
+            (ROUND_UP(((splitkeylen + 511) / 512),
+                      (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512)) * i);

Eww. The spec seems buggy, saying:

Quoted 3 lines

// integer divisions, result rounded down:
baseOffset = (size of phdr)/SECTOR SIZE + 1 keymaterialSectors = (stripes*masterKeyLength)/SECTOR SIZE + 1

First, look at the calculation of baseOffset. Since size of phdr is 592 bytes, and that is NOT a SECTOR SIZE in any disk I know of, that makes sense that baseOffset will be at least 2 (512-byte) sectors into the disk, or, if SECTOR SIZE is 4, that will result in an offset of 1 (4096-byte) sector. However, you've defined QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET as 4096, which means for our 512-byte sector usage, you are setting the first key material at sector 4 no matter what. I guess that matches what cryptsetup does? Maybe worth a comment?

Quoted 8 lines

Now, look at the calculation of keymaterial Sectors. The algorithm in the spec mishandles the case where stripes happens to be an exact multiple of sector size (that is, for a keysize of 20 bytes coupled with 512 stripes, it would reserve 21 sectors rather than the 20 actually required). I think your use of ROUND_UP() makes more sense, but it would be nice to file a bug against the LUKS spec to have them fix their math, and/or document that it is okay to use values larger than the absolute minimum.

Yeah, what I am doing matches the cryptsetup code. I had originally written it to be more or less what the spec suggests, and noticed that my images were different from those created by cryptsetup. So I switched to use the same algorithm. I figure it is probably an optimization for on disk alignment to stop crossing sector boundaries.

Quoted 11 lines

crypto/block-luks.c line 970

Quoted 10 lines
crypto/block-luks.c new file +10 -0
+     * slot headers, rounded up to the nearest sector, combined with
+     * the size of each master key material region, also rounded up
+     * to the nearest sector */
+    luks->header.payload_offset =
+        (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512) +
+        (ROUND_UP(((splitkeylen + 511) / 512),
+                  (QCRYPTO_BLOCK_LUKS_KEY_SLOT_OFFSET / 512)) *
+         QCRYPTO_BLOCK_LUKS_NUM_KEY_SLOTS);
+
+    block->payload_offset = luks->header.payload_offset;
Quoted 1 line

Again, I argue that block->payload_offset would be saner in bytes.

Agreed

Quoted 7 lines

crypto/block-luks.c line 973

Quoted 2 lines
crypto/block-luks.c new file +2 -0
+    /* Reserve header space to match payload offset */
+    initfunc(block, block->payload_offset * 512, &local_err, opaque);

Especially since initfunc() takes bytes.

Quoted 16 lines

crypto/block-luks.c line 1082

Quoted 12 lines
crypto/block-luks.c new file +12 -0
+
+static int
+qcrypto_block_luks_decrypt(QCryptoBlock *block,
+                           uint64_t startsector,
+                           uint8_t *buf,
+                           size_t len,
+                           Error **errp)
+{
+    return qcrypto_block_decrypt_helper(block->cipher,
+                                        block->niv, block->ivgen,
+                                        startsector, buf, len, errp);
+}

What happens when we try to read a LUKS device with 4k sectors? Worth worrying about, maybe just as a comment that we are hard-coded to 512 bytes at the moment?

qcrypto_block_decrypt_helper() method processes 'buf' in units of 512 so even if the underling dev is 4k, we'll also do 512 byte I/O

Quoted 9 lines

qapi/crypto.json line 145

Quoted 7 lines

##

qapi/crypto.json +6 -0
+# QCryptoBlockOptionsLUKS:
+#
+# The options that apply to LUKS encryption format
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing the
+#              decryption key

Maybe add "Mandatory except when probing the image for metadata only"

Yes

Quoted 11 lines
Quoted 11 lines
qapi/crypto.json +11 -0
+# Since: 2.6
+##
+{ 'struct': 'QCryptoBlockOptionsLUKS',
+  'data': { '*key-secret': 'str' }}
+
+
+##
+# QCryptoBlockCreateOptionsLUKS:
+#
+# The options that apply to LUKS encryption format initialization
+#
Quoted 8 lines

qapi/crypto.json line 161

Quoted 5 lines
qapi/crypto.json +5 -0
+# @cipher-alg: #optional the cipher algorithm for data encryption
+# @cipher-mode: #optional the cipher mode for data encryption
+# @ivgen-alg: #optional the initialization vector generator
+# @ivgen-hash-alg: #optional the initialization vector generator hash
+# @hash-alg: #optional the master key hash algorithm

Would be nice to mention the defaults, particularly since we may later change the default from cbc to xts.

Yes, will do

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 :|
#32 lore raw

PATCH v2 8/17 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            | 33 +++++++++++++++++----------------
 4 files changed, 23 insertions(+), 18 deletions(-)
block.c +3 -2
index 54c37f9..0806d4f 100644
@@ -719,7 +719,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;
 }
@@ -739,7 +740,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 63e3678..ebd26cd 100644
@@ -859,6 +859,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) {
@@ -1145,6 +1146,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 c96923d..73ffbd5 100644
@@ -91,6 +91,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 +17 -16
index 4052aba..e79f29b 100644
@@ -267,7 +267,7 @@ static BlockBackend *img_open_opts(const char *id,
 
 static BlockBackend *img_open_file(const char *id, const char *filename,
                                    const char *fmt, int flags,
-                                   bool require_io, bool quiet)
+                                   bool quiet)
 {
     BlockBackend *blk;
     BlockDriverState *bs;
@@ -287,7 +287,7 @@ static BlockBackend *img_open_file(const char *id, const char *filename,
     }
 
     bs = blk_bs(blk);
-    if (bdrv_is_encrypted(bs) && require_io) {
+    if (bdrv_is_encrypted(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");
@@ -680,7 +680,7 @@ static int img_check(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, flags);
     } else {
-        blk = img_open_file("image", filename, fmt, flags, true, quiet);
+        blk = img_open_file("image", filename, fmt, flags, quiet);
     }
     if (!blk) {
         return 1;
@@ -885,7 +885,7 @@ static int img_commit(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, flags);
     } else {
-        blk = img_open_file("image", filename, fmt, flags, true, quiet);
+        blk = img_open_file("image", filename, fmt, flags, quiet);
     }
     if (!blk) {
         return 1;
@@ -1247,13 +1247,13 @@ static int img_compare(int argc, char **argv)
             goto out3;
         }
     } else {
-        blk1 = img_open_file("image_1", filename1, fmt1, flags, true, quiet);
+        blk1 = img_open_file("image_1", filename1, fmt1, flags, quiet);
         if (!blk1) {
             ret = 2;
             goto out3;
         }
 
-        blk2 = img_open_file("image_2", filename2, fmt2, flags, true, quiet);
+        blk2 = img_open_file("image_2", filename2, fmt2, flags, quiet);
         if (!blk2) {
             ret = 2;
             goto out2;
@@ -1933,7 +1933,7 @@ static int img_convert(int argc, char **argv)
             blk[bs_i] = img_open_opts(id, opts, src_flags);
         } else {
             blk[bs_i] = img_open_file(id, argv[optind + bs_i], fmt, src_flags,
-                                      true, quiet);
+                                      quiet);
         }
         g_free(id);
         if (!blk[bs_i]) {
@@ -2080,7 +2080,7 @@ static int img_convert(int argc, char **argv)
      * the bdrv_create() call which takes different params
      */
     out_blk = img_open_file("target", out_filename,
-                            out_fmt, flags, true, quiet);
+                            out_fmt, flags, quiet);
     if (!out_blk) {
         ret = -1;
         goto out;
@@ -2284,12 +2284,13 @@ static ImageInfoList *collect_image_info_list(bool image_opts,
                 goto err;
             }
             blk = img_open_opts("image", opts,
-                                BDRV_O_FLAGS | BDRV_O_NO_BACKING);
+                                BDRV_O_FLAGS | BDRV_O_NO_BACKING |
+                                BDRV_O_NO_IO);
             opts = NULL;
         } else {
             blk = img_open_file("image", filename, fmt,
-                                BDRV_O_FLAGS | BDRV_O_NO_BACKING,
-                                false, false);
+                                BDRV_O_FLAGS | BDRV_O_NO_BACKING |
+                                BDRV_O_NO_IO, false);
         }
         if (!blk) {
             goto err;
@@ -2606,7 +2607,7 @@ static int img_map(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, BDRV_O_FLAGS);
     } else {
-        blk = img_open_file("image", filename, fmt, BDRV_O_FLAGS, true, false);
+        blk = img_open_file("image", filename, fmt, BDRV_O_FLAGS, false);
     }
     if (!blk) {
         return 1;
@@ -2763,7 +2764,7 @@ static int img_snapshot(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, bdrv_oflags);
     } else {
-        blk = img_open_file("image", filename, NULL, bdrv_oflags, true, quiet);
+        blk = img_open_file("image", filename, NULL, bdrv_oflags, quiet);
     }
     if (!blk) {
         return 1;
@@ -2948,7 +2949,7 @@ static int img_rebase(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, flags);
     } else {
-        blk = img_open_file("image", filename, fmt, flags, true, quiet);
+        blk = img_open_file("image", filename, fmt, flags, quiet);
     }
     if (!blk) {
         ret = -1;
@@ -3302,7 +3303,7 @@ static int img_resize(int argc, char **argv)
         blk = img_open_opts("image", opts, BDRV_O_FLAGS | BDRV_O_RDWR);
     } else {
         blk = img_open_file("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
-                            true, quiet);
+                            quiet);
     }
     if (!blk) {
         ret = -1;
@@ -3473,7 +3474,7 @@ static int img_amend(int argc, char **argv)
         }
         blk = img_open_opts("image", opts, flags);
     } else {
-        blk = img_open_file("image", filename, fmt, flags, true, quiet);
+        blk = img_open_file("image", filename, fmt, flags, quiet);
     }
     if (!blk) {
         ret = -1;
Signature · 1 line
2.5.0
Reviewed-by on v2 8/17
#33 lore raw

Re: [Qemu-devel] [PATCH v2 08/17] block: add flag to indicate that no I/O will be performed

Quoted 10 lines · 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.

s/todo/to do/2

Quoted 9 lines
---
 block.c               |  5 +++--
 block/io.c            |  2 ++
 include/block/block.h |  1 +
 qemu-img.c            | 33 +++++++++++++++++----------------
 4 files changed, 23 insertions(+), 18 deletions(-)
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#34 lore raw

PATCH v2 9/17 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 e79f29b..faf4dbd 100644
@@ -287,7 +287,8 @@ static BlockBackend *img_open_file(const char *id, const char *filename,
     }
 
     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 1c20e9b..98b5cc2 100644
@@ -72,7 +72,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
Reviewed-by on v2 9/17
#35 lore raw

Re: [Qemu-devel] [PATCH v2 09/17] qemu-img/qemu-io: don't prompt for passwords if not required

Quoted 9 lines · 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.

Quoted 6 lines
---
 qemu-img.c | 3 ++-
 qemu-io.c  | 2 +-
 2 files changed, 3 insertions(+), 2 deletions(-)
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#36 lore raw

PATCH v2 10/17 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.

At this time, the "luks" driver is registered. New LUKS compatible volume can be formatted using qemu-img

$ 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 --object secret,data=123456,id=sec0  --source demo.luks,driver=luks,key-secret=sec0
image: json:{"key-secret": "sec0", "driver": "luks", "file": {"driver": "file", "filename": "demo.luks"}}
file format: luks
virtual size: 10.0G (10737416192 bytes)
disk size: 132K

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver. With this initial impl, not all volumes created with dm-crypt can be opened by the QEMU 'luks' driver. This is due to lack of support for certain algorithms, in particular the 'xts' cipher mode. These limitations will be addressed in a later series of patches, with the intent that QEMU should be able to open anything that dm-crypt LUKS supports.

---
 block/Makefile.objs  |   2 +
 block/crypto.c       | 541 +++++++++++++++++++++++++++++++++++++++++++++++++++
 qapi/block-core.json |  18 +-
 3 files changed, 560 insertions(+), 1 deletion(-)
 create mode 100644 block/crypto.c
block/Makefile.objs +2 -0
index 58ef2ef..12eae77 100644
@@ -23,6 +23,8 @@ block-obj-$(CONFIG_LIBSSH2) += ssh.o
 block-obj-y += accounting.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 +541 -0

541 lines not on this page · raw message

qapi/block-core.json +17 -1
index 0a915ed..a194658 100644
@@ -1546,7 +1546,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' ] }
 
@@ -1664,6 +1664,21 @@
   '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)
+#
+# Since: 2.6
+##
+{ 'struct': 'BlockdevOptionsLUKS',
+  'base': 'BlockdevOptionsGenericFormat',
+  'data': { '*key-secret': 'str' } }
+
+
+##
 # @BlockdevOptionsGenericCOWFormat
 #
 # Driver specific block device options for image format that have no option
@@ -2000,6 +2015,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',
Signature · 1 line
2.5.0
#37 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

block/crypto.c line 315

Quoted 5 lines · Daniel P. Berrange
block/crypto.c new file +5 -0
+    /* XXX Should we treat size as being total physical size
+     * of the image (ie payload + encryption header), or just
+     * the logical size of the image (ie payload). If the latter
+     * then we need to extend 'size' to include the header
+     * size */

The latter. :)

Quoted 32 lines
block/crypto.c new file +32 -0
+    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
+#define BLOCK_CRYPTO_DRIVER(name, format)                               \
+    static int block_crypto_probe_ ## name(const uint8_t *buf,          \
+                                           int buf_size,                \
+                                           const char *filename) {      \
+        return block_crypto_probe_generic(format,                       \
+                                          buf, buf_size, filename);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_open_ ## name(BlockDriverState *bs,         \
+                                          QDict *options,               \
+                                          int flags,                    \
+                                          Error **errp)                 \
+    {                                                                   \
+        return block_crypto_open_generic(format,                        \
+                                         &block_crypto_runtime_opts_ ## name, \
+                                         bs, options, flags, errp);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_create_ ## name(const char *filename,       \
+                                            QemuOpts *opts,             \
+                                            Error **errp)               \
+    {                                                                   \
+        return block_crypto_create_generic(format,                      \
+                                           filename, opts, errp);       \
+    }                                                                   \
+                                                                        \
+    BlockDriver bdrv_crypto_ ## name = {                                \
+        .format_name        = #name,                                    \
+        .instance_size      = sizeof(BlockCrypto),                      \
+        .bdrv_probe         = block_crypto_probe_ ## name,              \
+        .bdrv_open          = block_crypto_open_ ## name,               \

block/crypto.c line 534

Quoted 10 lines
block/crypto.c new file +10 -0
+        .bdrv_close         = block_crypto_close,                       \
+        .bdrv_create        = block_crypto_create_ ## name,             \
+        .create_opts        = &block_crypto_create_opts_ ## name,       \
+                                                                        \
+        .bdrv_co_readv      = block_crypto_co_readv,                    \
+        .bdrv_co_writev     = block_crypto_co_writev,                   \
+        .bdrv_getlength     = block_crypto_getlength,                   \
+    }
+
+BLOCK_CRYPTO_DRIVER(luks, Q_CRYPTO_BLOCK_FORMAT_LUKS);

Personally I really prefer a preprocessed version, for the ease of grep.

Fam

#38 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 8 lines · Fam Zheng

block/crypto.c line 315

Quoted 5 lines · Daniel P. Berrange
block/crypto.c new file +5 -0
+    /* XXX Should we treat size as being total physical size
+     * of the image (ie payload + encryption header), or just
+     * the logical size of the image (ie payload). If the latter
+     * then we need to extend 'size' to include the header
+     * size */

The latter. :)

Ok

Quoted 36 lines
Quoted 36 lines
block/crypto.c new file +36 -0
+    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
+#define BLOCK_CRYPTO_DRIVER(name, format)                               \
+    static int block_crypto_probe_ ## name(const uint8_t *buf,          \
+                                           int buf_size,                \
+                                           const char *filename) {      \
+        return block_crypto_probe_generic(format,                       \
+                                          buf, buf_size, filename);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_open_ ## name(BlockDriverState *bs,         \
+                                          QDict *options,               \
+                                          int flags,                    \
+                                          Error **errp)                 \
+    {                                                                   \
+        return block_crypto_open_generic(format,                        \
+                                         &block_crypto_runtime_opts_ ## name, \
+                                         bs, options, flags, errp);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_create_ ## name(const char *filename,       \
+                                            QemuOpts *opts,             \
+                                            Error **errp)               \
+    {                                                                   \
+        return block_crypto_create_generic(format,                      \
+                                           filename, opts, errp);       \
+    }                                                                   \
+                                                                        \
+    BlockDriver bdrv_crypto_ ## name = {                                \
+        .format_name        = #name,                                    \
+        .instance_size      = sizeof(BlockCrypto),                      \
+        .bdrv_probe         = block_crypto_probe_ ## name,              \
+        .bdrv_open          = block_crypto_open_ ## name,               \
+        .bdrv_close         = block_crypto_close,                       \
+        .bdrv_create        = block_crypto_create_ ## name,             \
+        .create_opts        = &block_crypto_create_opts_ ## name,       \
+                                                                        \
Quoted 8 lines

block/crypto.c line 534

Quoted 6 lines
block/crypto.c new file +6 -0
+        .bdrv_co_readv      = block_crypto_co_readv,                    \
+        .bdrv_co_writev     = block_crypto_co_writev,                   \
+        .bdrv_getlength     = block_crypto_getlength,                   \
+    }
+
+BLOCK_CRYPTO_DRIVER(luks, Q_CRYPTO_BLOCK_FORMAT_LUKS);

Personally I really prefer a preprocessed version, for the ease of grep.

I'm not sure I understand what you mean by a preprocessed version - could you expand on that.

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 :|
#39 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 57 lines · Daniel P. Berrange
Quoted 8 lines · Fam Zheng

block/crypto.c line 315

Quoted 5 lines · Daniel P. Berrange
block/crypto.c new file +5 -0
+    /* XXX Should we treat size as being total physical size
+     * of the image (ie payload + encryption header), or just
+     * the logical size of the image (ie payload). If the latter
+     * then we need to extend 'size' to include the header
+     * size */

The latter. :)

Ok

Quoted 36 lines
Quoted 36 lines
block/crypto.c new file +36 -0
+    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
+#define BLOCK_CRYPTO_DRIVER(name, format)                               \
+    static int block_crypto_probe_ ## name(const uint8_t *buf,          \
+                                           int buf_size,                \
+                                           const char *filename) {      \
+        return block_crypto_probe_generic(format,                       \
+                                          buf, buf_size, filename);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_open_ ## name(BlockDriverState *bs,         \
+                                          QDict *options,               \
+                                          int flags,                    \
+                                          Error **errp)                 \
+    {                                                                   \
+        return block_crypto_open_generic(format,                        \
+                                         &block_crypto_runtime_opts_ ## name, \
+                                         bs, options, flags, errp);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_create_ ## name(const char *filename,       \
+                                            QemuOpts *opts,             \
+                                            Error **errp)               \
+    {                                                                   \
+        return block_crypto_create_generic(format,                      \
+                                           filename, opts, errp);       \
+    }                                                                   \
+                                                                        \
+    BlockDriver bdrv_crypto_ ## name = {                                \
+        .format_name        = #name,                                    \
+        .instance_size      = sizeof(BlockCrypto),                      \
+        .bdrv_probe         = block_crypto_probe_ ## name,              \
+        .bdrv_open          = block_crypto_open_ ## name,               \
+        .bdrv_close         = block_crypto_close,                       \
+        .bdrv_create        = block_crypto_create_ ## name,             \
+        .create_opts        = &block_crypto_create_opts_ ## name,       \
+                                                                        \
Quoted 8 lines

block/crypto.c line 534

Quoted 6 lines
block/crypto.c new file +6 -0
+        .bdrv_co_readv      = block_crypto_co_readv,                    \
+        .bdrv_co_writev     = block_crypto_co_writev,                   \
+        .bdrv_getlength     = block_crypto_getlength,                   \
+    }
+
+BLOCK_CRYPTO_DRIVER(luks, Q_CRYPTO_BLOCK_FORMAT_LUKS);

Personally I really prefer a preprocessed version, for the ease of grep.

Quoted 2 lines

I'm not sure I understand what you mean by a preprocessed version - could you expand on that.

I mean don't use macro concatenation and use plain symbols like in other block drivers.

BlockDriver bdrv_crypto_luks = {
.format_name = "luks",
.instance_size = sizeof(BlockCrypto),
.bdrv_probe = block_crypto_probe_luks,
.bdrv_open = block_crypto_open_luks,
...

mostly because it's easier to grep (or for refactoring with tools).

But I can't how repeatitive this would be (I can see the "don't repeat yourself" with your approach). There is only one BLOCK_CRYPTO_DRIVER instance in this series. This is probably bikeshedding.

Fam

#40 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 71 lines · Fam Zheng
Quoted 57 lines · Daniel P. Berrange
Quoted 8 lines · Fam Zheng

block/crypto.c line 315

Quoted 5 lines · Daniel P. Berrange
block/crypto.c new file +5 -0
+    /* XXX Should we treat size as being total physical size
+     * of the image (ie payload + encryption header), or just
+     * the logical size of the image (ie payload). If the latter
+     * then we need to extend 'size' to include the header
+     * size */

The latter. :)

Ok

Quoted 36 lines
Quoted 36 lines
block/crypto.c new file +36 -0
+    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
+#define BLOCK_CRYPTO_DRIVER(name, format)                               \
+    static int block_crypto_probe_ ## name(const uint8_t *buf,          \
+                                           int buf_size,                \
+                                           const char *filename) {      \
+        return block_crypto_probe_generic(format,                       \
+                                          buf, buf_size, filename);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_open_ ## name(BlockDriverState *bs,         \
+                                          QDict *options,               \
+                                          int flags,                    \
+                                          Error **errp)                 \
+    {                                                                   \
+        return block_crypto_open_generic(format,                        \
+                                         &block_crypto_runtime_opts_ ## name, \
+                                         bs, options, flags, errp);     \
+    }                                                                   \
+                                                                        \
+    static int block_crypto_create_ ## name(const char *filename,       \
+                                            QemuOpts *opts,             \
+                                            Error **errp)               \
+    {                                                                   \
+        return block_crypto_create_generic(format,                      \
+                                           filename, opts, errp);       \
+    }                                                                   \
+                                                                        \
+    BlockDriver bdrv_crypto_ ## name = {                                \
+        .format_name        = #name,                                    \
+        .instance_size      = sizeof(BlockCrypto),                      \
+        .bdrv_probe         = block_crypto_probe_ ## name,              \
+        .bdrv_open          = block_crypto_open_ ## name,               \
+        .bdrv_close         = block_crypto_close,                       \
+        .bdrv_create        = block_crypto_create_ ## name,             \
+        .create_opts        = &block_crypto_create_opts_ ## name,       \
+                                                                        \
Quoted 8 lines

block/crypto.c line 534

Quoted 6 lines
block/crypto.c new file +6 -0
+        .bdrv_co_readv      = block_crypto_co_readv,                    \
+        .bdrv_co_writev     = block_crypto_co_writev,                   \
+        .bdrv_getlength     = block_crypto_getlength,                   \
+    }
+
+BLOCK_CRYPTO_DRIVER(luks, Q_CRYPTO_BLOCK_FORMAT_LUKS);

Personally I really prefer a preprocessed version, for the ease of grep.

Quoted 2 lines

I'm not sure I understand what you mean by a preprocessed version - could you expand on that.

I mean don't use macro concatenation and use plain symbols like in other block drivers.

BlockDriver bdrv_crypto_luks = {
.format_name = "luks",
.instance_size = sizeof(BlockCrypto),
.bdrv_probe = block_crypto_probe_luks,
.bdrv_open = block_crypto_open_luks,
...

Quoted 5 lines

mostly because it's easier to grep (or for refactoring with tools).

But I can't how repeatitive this would be (I can see the "don't repeat yourself" with your approach). There is only one BLOCK_CRYPTO_DRIVER instance in this series. This is probably bikeshedding.

Yeah, thinking about it, my macro approach is probably overkill for the forseeable future anyway. I was future proofing wrt possible addition of trucrypt support, but that's soo far off its not something i really need worry about now.

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 :|
#41 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

In reply to Daniel P. Berrange
Quoted 8 lines · 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.

Quoted 7 lines

At this time, the "luks" driver is registered. New LUKS compatible volume can be formatted using qemu-img

$ 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

Are you still adding -o options like this, or is it better to use the new --image-opts flag from your other series for this purpose?

Quoted 4 lines

And query its size

$ qemu-img info --object secret,data=123456,id=sec0  --source demo.luks,driver=luks,key-secret=sec0

And this definitely looks stale.

Quoted 3 lines

image: json:{"key-secret": "sec0", "driver": "luks", "file": {"driver": "file", "filename": "demo.luks"}} file format: luks
virtual size: 10.0G (10737416192 bytes)

That size is 2048 bytes less than 10G; what happened? With default striping, you have 4000 stripes * 32 byte aes-256 key * 8 key material + header (where I pointed out that you are using a default offset of 4096, even though 1024 would be sufficient on 512-byte sectors), or roughly 1M, occupied by the LUKS header (in fact, having the payload aligned to 1M is probably wise, even if it can pack in tighter, just because a 1M-aligned disk with a 1M header is a GOOD thing). Therefore, you should either be counting the _entire_ LUKS header as part of the image (and report a full 10G), or you should _only_ be counting the payload size (and report 10G-1M, not 10G-2k).

My vote: do the same as we do for qcow2 or any other format. Make the size requested by the user as the size visible to the guest, and a fully-allocated image will take more space on the host than what the guest is using (that is, a fully-allocated 10G LUKS disk would present 10G payload to the guest but occupy 10G+1M on the host).

Quoted 1 line

disk size: 132K

This, however, looks reasonable - with the defaults, key material 0 will occupy just under 128k, and nothing is written in key material 1-7.

Quoted 10 lines

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver. With this initial impl, not all volumes created with dm-crypt can be opened by the QEMU 'luks' driver. This is due to lack of support for certain algorithms, in particular the 'xts' cipher mode. These limitations will be addressed in a later series of patches, with the intent that QEMU should be able to open anything that dm-crypt LUKS supports.

Cool! Would it be worth augmenting the commit message to show a sequence of commands where you loopback mount a LUKS image file created by qemu, then wire that up with cryptsetup, as a proof that the two are compatible implementations?

Quoted 12 lines
---
 block/Makefile.objs  |   2 +
 block/crypto.c       | 541 +++++++++++++++++++++++++++++++++++++++++++++++++++
 qapi/block-core.json |  18 +-
 3 files changed, 560 insertions(+), 1 deletion(-)
 create mode 100644 block/crypto.c

+++ b/block/crypto.c

block/crypto.c line 33

Quoted 7 lines
block/crypto.c new file +7 -0
+
+#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"

I suggested in 7/17 that user-specified striping might be a parameter worth adding; I guess this would be impacted as well.

block/crypto.c line 50

Quoted 9 lines
block/crypto.c new file +9 -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)) {
+        return 100;

I don't know why we have particular values for any of the probes, but at least this matches the arbitrary value reported by qcow2.

Quoted 9 lines
block/crypto.c new file +9 -0
+    } else {
+        return 0;
+    }
+}
+
+
+static ssize_t block_crypto_read_func(QCryptoBlock *block,
+                                      size_t offset,
+                                      uint8_t *buf,

block/crypto.c line 69

Quoted 10 lines
block/crypto.c new file +10 -0
+                                      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");

Are we guaranteed that the offset being read here will always lie in the encryption header portion of the file?

Quoted 9 lines
block/crypto.c new file +9 -0
+        return ret;
+    }
+    return ret;
+}
+
+
+static ssize_t block_crypto_write_func(QCryptoBlock *block,
+                                       size_t offset,
+                                       const uint8_t *buf,

block/crypto.c line 88

Quoted 10 lines
block/crypto.c new file +10 -0
+                                       size_t buflen,
+                                       Error **errp,
+                                       void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    ssize_t ret;
+
+    ret = bdrv_pwrite(bs, offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not write encryption header");

Likewise.

block/crypto.c line 354

Quoted 2 lines
block/crypto.c new file +2 -0
+
+#define BLOCK_CRYPTO_MAX_SECTORS 32

16k is not enough space to represent the LUKS header and the first key material. Does this number need to be larger to allow reading up to 1M of the image to find all 8 key materials?

Or is this just being used to limit the maximum amount we'll encrypt/decrypt in one pass of the loop?

Quoted 15 lines
block/crypto.c new file +15 -0
+
+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);
+
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+

block/crypto.c line 379

Quoted 10 lines
block/crypto.c new file +10 -0
+    qemu_co_mutex_lock(&crypto->lock);
+
+    while (remaining_sectors) {
+        cur_nr_sectors = remaining_sectors;
+
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+        cipher_data =
+            qemu_try_blockalign(bs->file->bs, cur_nr_sectors * 512);

Why are you allocating the block in the loop? Can you hoist the allocation outside, and reuse the memory across iterations?

block/crypto.c line 489

Quoted 9 lines
block/crypto.c new file +9 -0
+
+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 * 512);

Will need a tweak if you fix qcrypto_block_get_payload_offset to be in bytes.

qapi/block-core.json line 1549

Quoted 7 lines

+++ b/qapi/block-core.json

qapi/block-core.json +1 -1
@@ -1546,7 +1546,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',

Missing documentation; BlockDeviceInfo has been where we've documented which release introduced which drivers.

qapi/block-core.json line 1672

Quoted 7 lines
qapi/block-core.json +6 -0
 ##
+# @BlockdevOptionsLUKS
+#
+# Driver specific block device options for LUKS.
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing
+#              the decryption key (since 2.6)

Worth mentioning that it is mandatory except when doing a metadata-only probe.

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

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 12 lines · Eric Blake
Quoted 11 lines · 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.

At this time, the "luks" driver is registered. New LUKS compatible volume can be formatted using qemu-img

Quoted 7 lines
Quoted 4 lines
$ 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

Are you still adding -o options like this, or is it better to use the new --image-opts flag from your other series for this purpose?

These are options for image creation, so they must still use -o. My patches only deal with options for pre-existing images.

Quoted 5 lines
Quoted 3 lines

And query its size

$ qemu-img info --object secret,data=123456,id=sec0  --source demo.luks,driver=luks,key-secret=sec0

And this definitely looks stale.

Yes, its wrong.

Quoted 5 lines
Quoted 4 lines

image: json:{"key-secret": "sec0", "driver": "luks", "file": {"driver": "file", "filename": "demo.luks"}} file format: luks
virtual size: 10.0G (10737416192 bytes)

Quoted 10 lines

That size is 2048 bytes less than 10G; what happened? With default striping, you have 4000 stripes * 32 byte aes-256 key * 8 key material + header (where I pointed out that you are using a default offset of 4096, even though 1024 would be sufficient on 512-byte sectors), or roughly 1M, occupied by the LUKS header (in fact, having the payload aligned to 1M is probably wise, even if it can pack in tighter, just because a 1M-aligned disk with a 1M header is a GOOD thing). Therefore, you should either be counting the _entire_ LUKS header as part of the image (and report a full 10G), or you should _only_ be counting the payload size (and report 10G-1M, not 10G-2k).

It is supposed to be reporting 10G - luks header size. Not sure why this example shown 2k less - probably a bug from a much earlier version of the patchset. I think it probably dates from when I had mistakenly not multiplied payload offset by sector size or some such.

Quoted 5 lines

My vote: do the same as we do for qcow2 or any other format. Make the size requested by the user as the size visible to the guest, and a fully-allocated image will take more space on the host than what the guest is using (that is, a fully-allocated 10G LUKS disk would present 10G payload to the guest but occupy 10G+1M on the host).

Yes, I had a todo item in the code asking which was better

/* XXX Should we treat size as being total physical size
* of the image (ie payload + encryption header), or just
* the logical size of the image (ie payload). If the latter
* then we need to extend 'size' to include the header
* size */
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);

And Fam suggested the same as you - show full 10 G to the guest.

The complication is that we need to create the backing file before we format the luks header, and we don't know the size of the luks header at that point. So either I could format the luks header into a temporary in-memory buffer, or I have to create the file and then resize it afterwards, or I have to provide some way to calculate the eventual header size prior to creating it. I didn't much like any of those options :-)

Quoted 16 lines
Quoted 1 line

disk size: 132K

This, however, looks reasonable - with the defaults, key material 0 will occupy just under 128k, and nothing is written in key material 1-7.

Quoted 10 lines

All volumes created by this new 'luks' driver should be capable of being opened by the kernel dm-crypt driver. With this initial impl, not all volumes created with dm-crypt can be opened by the QEMU 'luks' driver. This is due to lack of support for certain algorithms, in particular the 'xts' cipher mode. These limitations will be addressed in a later series of patches, with the intent that QEMU should be able to open anything that dm-crypt LUKS supports.

Quoted 4 lines

Cool! Would it be worth augmenting the commit message to show a sequence of commands where you loopback mount a LUKS image file created by qemu, then wire that up with cryptsetup, as a proof that the two are compatible implementations?

My intent is to add something to tests/qemu-iotests that will check interoperability between qemu + cryptsetup. Slight complication is that those io tests all expect to run unprivileged. So it'll need a manual step run privileged to create the cryptsetup disk images for testing with.

Quoted 12 lines

block/crypto.c line 33

Quoted 9 lines

+++ b/block/crypto.c

block/crypto.c new file +7 -0
+
+#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"

I suggested in 7/17 that user-specified striping might be a parameter worth adding; I guess this would be impacted as well.

Same note as before - cryptsetup hardcodes is to 4k, so I figure it is fine todo the same right now.

Quoted 8 lines
Quoted 8 lines
block/crypto.c new file +8 -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;
Quoted 8 lines

block/crypto.c line 69

Quoted 5 lines
block/crypto.c new file +5 -0
+    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");

Are we guaranteed that the offset being read here will always lie in the encryption header portion of the file?

I don't think we need to care about that here. We're just honouring reads from whereever the crypto driver wants - we don't want the block driver here to have specific knowledge of the underlying crypto format.

Quoted 30 lines
Quoted 10 lines
block/crypto.c new file +9 -0
+        return ret;
+    }
+    return ret;
+}
+
+
+static ssize_t block_crypto_write_func(QCryptoBlock *block,
+                                       size_t offset,
+                                       const uint8_t *buf,

block/crypto.c line 88

Quoted 10 lines
block/crypto.c new file +10 -0
+                                       size_t buflen,
+                                       Error **errp,
+                                       void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    ssize_t ret;
+
+    ret = bdrv_pwrite(bs, offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not write encryption header");

Likewise.

block/crypto.c line 354

Quoted 2 lines
block/crypto.c new file +2 -0
+
+#define BLOCK_CRYPTO_MAX_SECTORS 32

16k is not enough space to represent the LUKS header and the first key material. Does this number need to be larger to allow reading up to 1M of the image to find all 8 key materials?

Quoted 2 lines

Or is this just being used to limit the maximum amount we'll encrypt/decrypt in one pass of the loop?

Yeah, this is just used for batching I/O to the underling block device, so that we don't need to allocate an arbitrarily large temporary buffer for (en|de)cryption.

Quoted 19 lines
Quoted 19 lines
block/crypto.c new file +19 -0
+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);
+
+    qemu_iovec_init(&hd_qiov, qiov->niov);
+
+    qemu_co_mutex_lock(&crypto->lock);
+
+    while (remaining_sectors) {
+        cur_nr_sectors = remaining_sectors;
+
Quoted 8 lines

block/crypto.c line 379

Quoted 5 lines
block/crypto.c new file +5 -0
+        if (cur_nr_sectors > BLOCK_CRYPTO_MAX_SECTORS) {
+            cur_nr_sectors = BLOCK_CRYPTO_MAX_SECTORS;
+        }
+        cipher_data =
+            qemu_try_blockalign(bs->file->bs, cur_nr_sectors * 512);

Why are you allocating the block in the loop? Can you hoist the allocation outside, and reuse the memory across iterations?

No particular reason - this code pattern is just copied from equivalent methods in qcow2.c

Quoted 13 lines

block/crypto.c line 489

Quoted 10 lines
block/crypto.c new file +9 -0
+
+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 * 512);

Will need a tweak if you fix qcrypto_block_get_payload_offset to be in bytes.

Yep

Quoted 10 lines

qapi/block-core.json line 1549

Quoted 7 lines

+++ b/qapi/block-core.json

qapi/block-core.json +1 -1
@@ -1546,7 +1546,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',

Missing documentation; BlockDeviceInfo has been where we've documented which release introduced which drivers.

Ah ok

Quoted 11 lines

qapi/block-core.json line 1672

Quoted 8 lines
qapi/block-core.json +6 -0
 ##
+# @BlockdevOptionsLUKS
+#
+# Driver specific block device options for LUKS.
+#
+# @key-secret: #optional the ID of a QCryptoSecret object providing
+#              the decryption key (since 2.6)

Worth mentioning that it is mandatory except when doing a metadata-only probe.

Yes

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 :|
#43 lore raw

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 17 lines · Daniel P. Berrange
Quoted 5 lines

My vote: do the same as we do for qcow2 or any other format. Make the size requested by the user as the size visible to the guest, and a fully-allocated image will take more space on the host than what the guest is using (that is, a fully-allocated 10G LUKS disk would present 10G payload to the guest but occupy 10G+1M on the host).

Yes, I had a todo item in the code asking which was better

/* XXX Should we treat size as being total physical size
* of the image (ie payload + encryption header), or just
* the logical size of the image (ie payload). If the latter
* then we need to extend 'size' to include the header
* size */
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);

And Fam suggested the same as you - show full 10 G to the guest.

Quoted 7 lines

The complication is that we need to create the backing file before we format the luks header, and we don't know the size of the luks header at that point. So either I could format the luks header into a temporary in-memory buffer, or I have to create the file and then resize it afterwards, or I have to provide some way to calculate the eventual header size prior to creating it. I didn't much like any of those options :-)

Well, if we hard-code stripes==4000, then we pretty much know that the header is just under 1M for the maximum size key (aes-256); and rounding up to 1M is nice for all cluster sizes except 2M. I suppose we could fit in 512k if we use a smaller key (aes-128), but would it hurt to just hard-code a reservation of 1M?

Quoted 10 lines
Quoted 4 lines

Cool! Would it be worth augmenting the commit message to show a sequence of commands where you loopback mount a LUKS image file created by qemu, then wire that up with cryptsetup, as a proof that the two are compatible implementations?

My intent is to add something to tests/qemu-iotests that will check interoperability between qemu + cryptsetup. Slight complication is that those io tests all expect to run unprivileged. So it'll need a manual step run privileged to create the cryptsetup disk images for testing with.

We've checked in compressed binary images before; but 1M of key material won't compress well.

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

Re: [Qemu-devel] [PATCH v2 10/17] block: add generic full disk encryption driver

Quoted 27 lines · Eric Blake
Quoted 17 lines · Daniel P. Berrange
Quoted 5 lines

My vote: do the same as we do for qcow2 or any other format. Make the size requested by the user as the size visible to the guest, and a fully-allocated image will take more space on the host than what the guest is using (that is, a fully-allocated 10G LUKS disk would present 10G payload to the guest but occupy 10G+1M on the host).

Yes, I had a todo item in the code asking which was better

/* XXX Should we treat size as being total physical size
* of the image (ie payload + encryption header), or just
* the logical size of the image (ie payload). If the latter
* then we need to extend 'size' to include the header
* size */
qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);

And Fam suggested the same as you - show full 10 G to the guest.

Quoted 7 lines

The complication is that we need to create the backing file before we format the luks header, and we don't know the size of the luks header at that point. So either I could format the luks header into a temporary in-memory buffer, or I have to create the file and then resize it afterwards, or I have to provide some way to calculate the eventual header size prior to creating it. I didn't much like any of those options :-)

Quoted 5 lines

Well, if we hard-code stripes==4000, then we pretty much know that the header is just under 1M for the maximum size key (aes-256); and rounding up to 1M is nice for all cluster sizes except 2M. I suppose we could fit in 512k if we use a smaller key (aes-128), but would it hurt to just hard-code a reservation of 1M?

I actually figured out a way to deal with this - i just have to delay creation of the underling file, to be done in the callback which initilizes the luks header region.

Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Cool! Would it be worth augmenting the commit message to show a sequence of commands where you loopback mount a LUKS image file created by qemu, then wire that up with cryptsetup, as a proof that the two are compatible implementations?

Quoted 8 lines
Quoted 5 lines

My intent is to add something to tests/qemu-iotests that will check interoperability between qemu + cryptsetup. Slight complication is that those io tests all expect to run unprivileged. So it'll need a manual step run privileged to create the cryptsetup disk images for testing with.

We've checked in compressed binary images before; but 1M of key material won't compress well.

And realistically it is going to be 10's of MB per image, since I want the test to verify more than just the header, and there's probably about 10+ different cipher combinations, so it would be many 100's of MBs to check in. So that won't fly sadly.

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

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 :|
#45 lore raw

PATCH v2 11/17 qcow2: make qcow2_encrypt_sectors encrypt in place

In reply to Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change qcow2_encrypt_sectors() to assume use of a single buffer, encrypting in place. The current callers all used the same buffer for input/output already.

---
 block/qcow2-cluster.c | 17 +++++------------
 block/qcow2.c         |  5 ++---
 block/qcow2.h         |  3 +--
 3 files changed, 8 insertions(+), 17 deletions(-)
block/qcow2-cluster.c +5 -12
index 34112c3..f5bc4f2 100644
@@ -341,12 +341,8 @@ static int count_contiguous_clusters_by_type(int nb_clusters,
     return i;
 }
 
-/* The crypt function is compatible with the linux cryptoloop
-   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
-   supported */
 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
-                          uint8_t *out_buf, const uint8_t *in_buf,
-                          int nb_sectors, bool enc,
+                          uint8_t *buf, int nb_sectors, bool enc,
                           Error **errp)
 {
     union {
@@ -366,14 +362,12 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
         }
         if (enc) {
             ret = qcrypto_cipher_encrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         } else {
             ret = qcrypto_cipher_decrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         }
@@ -381,8 +375,7 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
             return -1;
         }
         sector_num++;
-        in_buf += 512;
-        out_buf += 512;
+        buf += 512;
     }
     return 0;
 }
@@ -430,7 +423,7 @@ static int coroutine_fn copy_sectors(BlockDriverState *bs,
         Error *err = NULL;
         assert(s->cipher);
         if (qcow2_encrypt_sectors(s, start_sect + n_start,
-                                  iov.iov_base, iov.iov_base, n,
+                                  iov.iov_base, n,
                                   true, &err) < 0) {
             ret = -EIO;
             error_free(err);
block/qcow2.c +2 -3
index d992e7f..2fae692 100644
@@ -1504,7 +1504,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 assert(s->cipher);
                 Error *err = NULL;
                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
-                                          cluster_data, cur_nr_sectors, false,
+                                          cur_nr_sectors, false,
                                           &err) < 0) {
                     error_free(err);
                     ret = -EIO;
@@ -1604,8 +1604,7 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
 
             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
-                                      cluster_data, cur_nr_sectors,
-                                      true, &err) < 0) {
+                                      cur_nr_sectors, true, &err) < 0) {
                 error_free(err);
                 ret = -EIO;
                 goto fail;
block/qcow2.h +1 -2
index a063a3c..ae04285 100644
@@ -540,8 +540,7 @@ int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index);
 void qcow2_l2_cache_reset(BlockDriverState *bs);
 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
-                          uint8_t *out_buf, const uint8_t *in_buf,
-                          int nb_sectors, bool enc, Error **errp);
+                          uint8_t *buf, int nb_sectors, bool enc, Error **errp);
 
 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     int *num, uint64_t *cluster_offset);
Signature · 1 line
2.5.0
Reviewed-by on v2 11/17
#46 lore raw

Re: [Qemu-devel] [PATCH v2 11/17] qcow2: make qcow2_encrypt_sectors encrypt in place

Quoted 106 lines · Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change qcow2_encrypt_sectors() to assume use of a single buffer, encrypting in place. The current callers all used the same buffer for input/output already.

---
 block/qcow2-cluster.c | 17 +++++------------
 block/qcow2.c         |  5 ++---
 block/qcow2.h         |  3 +--
 3 files changed, 8 insertions(+), 17 deletions(-)
block/qcow2-cluster.c +5 -12
index 34112c3..f5bc4f2 100644
@@ -341,12 +341,8 @@ static int count_contiguous_clusters_by_type(int nb_clusters,
     return i;
 }
 
-/* The crypt function is compatible with the linux cryptoloop
-   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
-   supported */
 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
-                          uint8_t *out_buf, const uint8_t *in_buf,
-                          int nb_sectors, bool enc,
+                          uint8_t *buf, int nb_sectors, bool enc,
                           Error **errp)
 {
     union {
@@ -366,14 +362,12 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
         }
         if (enc) {
             ret = qcrypto_cipher_encrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         } else {
             ret = qcrypto_cipher_decrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         }
@@ -381,8 +375,7 @@ int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
             return -1;
         }
         sector_num++;
-        in_buf += 512;
-        out_buf += 512;
+        buf += 512;
     }
     return 0;
 }
@@ -430,7 +423,7 @@ static int coroutine_fn copy_sectors(BlockDriverState *bs,
         Error *err = NULL;
         assert(s->cipher);
         if (qcow2_encrypt_sectors(s, start_sect + n_start,
-                                  iov.iov_base, iov.iov_base, n,
+                                  iov.iov_base, n,
                                   true, &err) < 0) {
             ret = -EIO;
             error_free(err);
block/qcow2.c +2 -3
index d992e7f..2fae692 100644
@@ -1504,7 +1504,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 assert(s->cipher);
                 Error *err = NULL;
                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
-                                          cluster_data, cur_nr_sectors, false,
+                                          cur_nr_sectors, false,
                                           &err) < 0) {
                     error_free(err);
                     ret = -EIO;
@@ -1604,8 +1604,7 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
 
             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
-                                      cluster_data, cur_nr_sectors,
-                                      true, &err) < 0) {
+                                      cur_nr_sectors, true, &err) < 0) {
                 error_free(err);
                 ret = -EIO;
                 goto fail;
block/qcow2.h +1 -2
index a063a3c..ae04285 100644
@@ -540,8 +540,7 @@ int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index);
 void qcow2_l2_cache_reset(BlockDriverState *bs);
 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
-                          uint8_t *out_buf, const uint8_t *in_buf,
-                          int nb_sectors, bool enc, Error **errp);
+                          uint8_t *buf, int nb_sectors, bool enc, Error **errp);
 
 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     int *num, uint64_t *cluster_offset);
Signature · 1 line
2.5.0
Reviewed-by on v2 11/17
#47 lore raw

Re: [Qemu-devel] [PATCH v2 11/17] qcow2: make qcow2_encrypt_sectors encrypt in place

In reply to Daniel P. Berrange
Quoted 11 lines · Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change qcow2_encrypt_sectors() to assume use of a single buffer, encrypting in place. The current callers all used the same buffer for input/output already.

---
 block/qcow2-cluster.c | 17 +++++------------
 block/qcow2.c         |  5 ++---
 block/qcow2.h         |  3 +--
 3 files changed, 8 insertions(+), 17 deletions(-)
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#48 lore raw

PATCH v2 12/17 qcow2: convert QCow2 to use QCryptoBlock for encryption

In reply to Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

With the LUKS format it is neccessary to store the LUKS partition header and key material in the QCow2 file. This data can be many MB in size, so cannot go into the QCow2 header region directly. Thus the spec is defines a FDE (Full Disk Encryption) header extension that specifies the offset of a set of clusters to hold the FDE headers, as well as the length of that region. The LUKS header is thus stored in these extra allocated clusters before the main image payload.

With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.

  $QEMU \
    -object secret,id=sec0,filename=/home/berrange/encrypted.pw \
    -drive file=/home/berrange/encrypted.qcow2,key-secret=sec0

The new LUKS format is set as the new default format when creating encrypted images. ie

  # qemu-img create --object secret,data=123456,id=sec0 \
       -f qcow2 -o encryption,key-secret=sec0 \
       test.qcow2 10G

Results in creation of an image using the LUKS format.

For compatibility the old qcow2 AES format can still be used via the 'encryption-format' parameter which accepts the values 'luks' or 'qcowaes'.

  # qemu-img create --object secret,data=123456,id=sec0 \
       -f qcow2 -o encryption,key-secret=sec0,encryption-format=qcowaes \
       test.qcow2 10G
---
 block/qcow2-cluster.c      |  46 +----
 block/qcow2-refcount.c     |  10 +
 block/qcow2.c              | 502 ++++++++++++++++++++++++++++++++++++++-------
 block/qcow2.h              |  21 +-
 crypto/block-luks.c        |   1 -
 docs/specs/qcow2.txt       |  74 +++++++
 qapi/block-core.json       |   6 +-
 tests/qemu-iotests/049     |   2 +-
 tests/qemu-iotests/049.out |   7 +-
 tests/qemu-iotests/082.out | 189 +++++++++++++++++
 tests/qemu-iotests/087     |  28 ++-
 tests/qemu-iotests/087.out |  12 +-
 tests/qemu-iotests/134     |  18 +-
 tests/qemu-iotests/134.out |  21 +-
 tests/qemu-iotests/common  |   1 +
 15 files changed, 775 insertions(+), 163 deletions(-)
block/qcow2-cluster.c +3 -43
index f5bc4f2..0512256 100644
@@ -341,45 +341,6 @@ static int count_contiguous_clusters_by_type(int nb_clusters,
     return i;
 }
 
-int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
-                          uint8_t *buf, int nb_sectors, bool enc,
-                          Error **errp)
-{
-    union {
-        uint64_t ll[2];
-        uint8_t b[16];
-    } ivec;
-    int i;
-    int ret;
-
-    for(i = 0; i < nb_sectors; i++) {
-        ivec.ll[0] = cpu_to_le64(sector_num);
-        ivec.ll[1] = 0;
-        if (qcrypto_cipher_setiv(s->cipher,
-                                 ivec.b, G_N_ELEMENTS(ivec.b),
-                                 errp) < 0) {
-            return -1;
-        }
-        if (enc) {
-            ret = qcrypto_cipher_encrypt(s->cipher,
-                                         buf, buf,
-                                         512,
-                                         errp);
-        } else {
-            ret = qcrypto_cipher_decrypt(s->cipher,
-                                         buf, buf,
-                                         512,
-                                         errp);
-        }
-        if (ret < 0) {
-            return -1;
-        }
-        sector_num++;
-        buf += 512;
-    }
-    return 0;
-}
-
 static int coroutine_fn copy_sectors(BlockDriverState *bs,
                                      uint64_t start_sect,
                                      uint64_t cluster_offset,
@@ -421,10 +382,9 @@ static int coroutine_fn copy_sectors(BlockDriverState *bs,
 
     if (bs->encrypted) {
         Error *err = NULL;
-        assert(s->cipher);
-        if (qcow2_encrypt_sectors(s, start_sect + n_start,
-                                  iov.iov_base, n,
-                                  true, &err) < 0) {
+        assert(s->crypto);
+        if (qcrypto_block_encrypt(s->crypto, start_sect + n_start,
+                                  iov.iov_base, n, &err) < 0) {
             ret = -EIO;
             error_free(err);
             goto out;
block/qcow2-refcount.c +10 -0
index af493f8..d34d59b 100644
@@ -1847,6 +1847,16 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
         return ret;
     }
 
+    /* encryption */
+    if (s->crypto_header.length) {
+        ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
+                            s->crypto_header.offset,
+                            s->crypto_header.length);
+        if (ret < 0) {
+            return ret;
+        }
+    }
+
     return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);
 }
 
block/qcow2.c +428 -74

713 lines not on this page · raw message

block/qcow2.h +19 -2
index ae04285..e1f0b5b 100644
@@ -25,7 +25,7 @@
 #ifndef BLOCK_QCOW2_H
 #define BLOCK_QCOW2_H
 
-#include "crypto/cipher.h"
+#include "crypto/block.h"
 #include "qemu/coroutine.h"
 
 //#define DEBUG_ALLOC
@@ -36,6 +36,7 @@
 
 #define QCOW_CRYPT_NONE 0
 #define QCOW_CRYPT_AES  1
+#define QCOW_CRYPT_LUKS 2
 
 #define QCOW_MAX_CRYPT_CLUSTERS 32
 #define QCOW_MAX_SNAPSHOTS 65536
@@ -98,6 +99,15 @@
 #define QCOW2_OPT_REFCOUNT_CACHE_SIZE "refcount-cache-size"
 #define QCOW2_OPT_CACHE_CLEAN_INTERVAL "cache-clean-interval"
 
+#define QCOW2_OPT_CRYPTO_FORMAT "encryption-format"
+#define QCOW2_OPT_KEY_SECRET "key-secret"
+#define QCOW2_OPT_CIPHER_ALG "cipher-alg"
+#define QCOW2_OPT_CIPHER_MODE "cipher-mode"
+#define QCOW2_OPT_IVGEN_ALG "ivgen-alg"
+#define QCOW2_OPT_IVGEN_HASH_ALG "ivgen-hash-alg"
+#define QCOW2_OPT_HASH_ALG "hash-alg"
+
+
 typedef struct QCowHeader {
     uint32_t magic;
     uint32_t version;
@@ -163,6 +173,11 @@ typedef struct QCowSnapshot {
 struct Qcow2Cache;
 typedef struct Qcow2Cache Qcow2Cache;
 
+typedef struct Qcow2CryptoHeaderExtension {
+    uint64_t offset;
+    uint64_t length;
+} QEMU_PACKED Qcow2CryptoHeaderExtension;
+
 typedef struct Qcow2UnknownHeaderExtension {
     uint32_t magic;
     uint32_t len;
@@ -256,7 +271,9 @@ typedef struct BDRVQcow2State {
 
     CoMutex lock;
 
-    QCryptoCipher *cipher; /* current cipher, NULL if no key yet */
+    Qcow2CryptoHeaderExtension crypto_header; /* QCow2 header extension */
+    QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
+    QCryptoBlock *crypto; /* Disk encryption format driver */
     uint32_t crypt_method_header;
     uint64_t snapshots_offset;
     int snapshots_size;
crypto/block-luks.c +0 -1
index 47630ee..2f4b983 100644
@@ -990,7 +990,6 @@ qcrypto_block_luks_create(QCryptoBlock *block,
         cpu_to_be32s(&luks->header.key_slots[i].stripes);
     }
 
-
     /* Write out the partition header and key slot headers */
     writefunc(block, 0,
               (const uint8_t *)&luks->header,
docs/specs/qcow2.txt +74 -0

92 lines not on this page · raw message

qapi/block-core.json +4 -2
index a194658..b704dd7 100644
@@ -1789,6 +1789,8 @@
 # @cache-clean-interval:  #optional clean unused entries in the L2 and refcount
 #                         caches. The interval is in seconds. The default value
 #                         is 0 and it disables this feature (since 2.5)
+# @key-secret:            #optional the ID of a QCryptoSecret object providing
+#                         the decryption key (since 2.6)
 #
 # Since: 1.7
 ##
@@ -1802,8 +1804,8 @@
             '*cache-size': 'int',
             '*l2-cache-size': 'int',
             '*refcount-cache-size': 'int',
-            '*cache-clean-interval': 'int' } }
-
+            '*cache-clean-interval': 'int',
+            '*key-secret': 'str' } }
 
 ##
 # @BlockdevOptionsArchipelago
tests/qemu-iotests/049 +1 -1
index 93aa0ea..765b950 100755
@@ -107,7 +107,7 @@ test_qemu_img create -f $IMGFMT -o preallocation=1234 "$TEST_IMG" 64M
 echo "== Check encryption option =="
 echo
 test_qemu_img create -f $IMGFMT -o encryption=off "$TEST_IMG" 64M
-test_qemu_img create -f $IMGFMT -o encryption=on "$TEST_IMG" 64M
+test_qemu_img create -f $IMGFMT --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 "$TEST_IMG" 64M
 
 echo "== Check lazy_refcounts option (only with v3) =="
 echo
tests/qemu-iotests/049.out +2 -5
index a2b6703..c9f0bc5 100644
@@ -186,14 +186,11 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si
 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 create -f qcow2 --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 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
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16 key-secret=sec0
 
 == Check lazy_refcounts option (only with v3) ==
 
tests/qemu-iotests/082.out +189 -0

351 lines not on this page · raw message

tests/qemu-iotests/087 +24 -4
index af44299..3386668 100755
@@ -184,9 +184,18 @@ echo
 echo === Encrypted image ===
 echo
 
-_make_test_img -o encryption=on $size
+_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 $size
 run_qemu -S <<EOF
 { "execute": "qmp_capabilities" }
+{ "execute": "object-add",
+  "arguments": {
+      "qom-type": "secret",
+      "id": "sec0",
+      "props": {
+          "data": "123456"
+      }
+  }
+}
 { "execute": "blockdev-add",
   "arguments": {
       "options": {
@@ -195,7 +204,8 @@ run_qemu -S <<EOF
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
-        }
+        },
+        "key-secret": "sec0"
       }
     }
   }
@@ -204,6 +214,15 @@ EOF
 
 run_qemu <<EOF
 { "execute": "qmp_capabilities" }
+{ "execute": "object-add",
+  "arguments": {
+      "qom-type": "secret",
+      "id": "sec0",
+      "props": {
+          "data": "123456"
+      }
+  }
+}
 { "execute": "blockdev-add",
   "arguments": {
       "options": {
@@ -212,7 +231,8 @@ run_qemu <<EOF
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
-        }
+        },
+        "key-secret": "sec0"
       }
     }
   }
@@ -223,7 +243,7 @@ echo
 echo === Missing driver ===
 echo
 
-_make_test_img -o encryption=on $size
+_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 $size
 run_qemu -S <<EOF
 { "execute": "qmp_capabilities" }
 { "execute": "blockdev-add",
tests/qemu-iotests/087.out +4 -8
index 7d62cd5..5fc4823 100644
@@ -41,13 +41,11 @@ QMP_VERSION
 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
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 Testing: -S
 QMP_VERSION
 {"return": {}}
+{"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.
@@ -58,6 +56,7 @@ You can use 'qemu-img convert' to convert your image to an unencrypted one.
 Testing:
 QMP_VERSION
 {"return": {}}
+{"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.
@@ -71,10 +70,7 @@ 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.
-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
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 Testing: -S
 QMP_VERSION
 {"return": {}}
tests/qemu-iotests/134 +13 -5
index 1c3820b..e0d634e 100755
@@ -44,23 +44,31 @@ _supported_os Linux
 
 
 size=128M
-IMGOPTS="encryption=on" _make_test_img $size
+
+SECRET="secret,id=sec0,data=astrochicken"
+SECRETALT="secret,id=sec0,data=platypus"
+
+_make_test_img --object $SECRET -o "encryption=on,key-secret=sec0" $size
+
+IMGSPEC="driver=$IMGFMT,file=$TEST_IMG,key-secret=sec0"
+
+QEMU_IO_OPTIONS=$QEMU_IO_OPTIONS_NO_FMT
 
 echo
 echo "== reading whole image =="
-echo "astrochicken" | $QEMU_IO -c "read 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir
+$QEMU_IO --object $SECRET --image-opts -c "read 0 $size" $IMGSPEC | _filter_qemu_io | _filter_testdir
 
 echo
 echo "== rewriting whole image =="
-echo "astrochicken" | $QEMU_IO -c "write -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir
+$QEMU_IO --object $SECRET --image-opts -c "write -P 0xa 0 $size" $IMGSPEC | _filter_qemu_io | _filter_testdir
 
 echo
 echo "== verify pattern =="
-echo "astrochicken" | $QEMU_IO -c "read -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir
+$QEMU_IO --object $SECRET --image-opts -c "read -P 0xa 0 $size" $IMGSPEC | _filter_qemu_io | _filter_testdir
 
 echo
 echo "== verify pattern failure with wrong password =="
-echo "platypus" | $QEMU_IO -c "read -P 0xa 0 $size" "$TEST_IMG" | _filter_qemu_io | _filter_testdir
+$QEMU_IO --object $SECRETALT --image-opts -c "read -P 0xa 0 $size" $IMGSPEC | _filter_qemu_io | _filter_testdir
 
 
 # success, all done
tests/qemu-iotests/134.out +3 -18
index a16acb8..e9bf302 100644
@@ -2,17 +2,12 @@ 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
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 
 == 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)
 
@@ -20,8 +15,6 @@ read 134217728/134217728 bytes at offset 0
 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)
 
@@ -29,18 +22,10 @@ wrote 134217728/134217728 bytes at offset 0
 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
-read 134217728/134217728 bytes at offset 0
-128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+can't open device /home/berrange/src/virt/qemu/tests/qemu-iotests/scratch/t.qcow2: Invalid password, cannot unlock any keyslot
+no file open, try 'help open'
 *** done
tests/qemu-iotests/common +1 -0
index ff84f4b..f65d04c 100644
@@ -398,6 +398,7 @@ BEGIN        { for (t='$start'; t<='$end'; t++) printf "%03d\n",t }' \
 done
 
 # Set qemu-io cache mode with $CACHEMODE we have
+QEMU_IO_OPTIONS_NO_FMT="$QEMU_IO_OPTIONS --cache $CACHEMODE"
 QEMU_IO_OPTIONS="$QEMU_IO_OPTIONS -f $IMGFMT --cache $CACHEMODE"
 
 # Set default options for qemu-img create -o if they were not specified
Signature · 1 line
2.5.0
#49 lore raw

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

FWIW, with today's QEMU, it's possible to stack format drivers on top of each other. In other words, even without this patch, we can make LUKS driver encrypt/decrypt the qcow2 payload, while keeping them completely orthogonal.

It's someting like:

           --------------------
           |       LUKS       |
           --------------------
                    |
                    v
           --------------------
           |      qcow2       |
           --------------------
                    |
                    v
           --------------------
           |       file       |
           --------------------

The command line looks like this:

-drive driver=luks,file.driver=qcow2,file.file.driver=file,\
file.file.filename=$qcow2_image_whose_payload_is_in_luks_format

unfortunately I don't know how to create nested images with qemu-img. I tested the nested qcow2 by attaching the outter image to a VM and running "qemu-img create -f qcow2 /dev/vda" in guest shell. Kevin?

Fam

#50 lore raw

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

Quoted 9 lines · Fam Zheng
Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

FWIW, with today's QEMU, it's possible to stack format drivers on top of each other. In other words, even without this patch, we can make LUKS driver encrypt/decrypt the qcow2 payload, while keeping them completely orthogonal.

Yep, that is certainly possible, and it is what is intended for using LUKS with RBD, iSCSI, & other network drivers.

I think there is value in having LUKS integrated directly into qcow2 though. It means that given a qcow2 file you can 100% reliably distinguish between a file created with the intention of QEMU managing the LUKS encryption, from a file where the guest OS happens to have set up LUKS encryption in its virtual disk. If you don't have this, then given a random qcow2 file, you have to probe to see if LUKS is present or not. Given the security issues we've had in the past with raw images being turned into qcow2 images by a malicious guest writing a qcow2 header, I feel that having explicitly integration LUKS support in QCow is worthwhile as a concept.

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 :|
#51 lore raw

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

Quoted 14 lines · Daniel P. Berrange
Quoted 9 lines · Fam Zheng
Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

FWIW, with today's QEMU, it's possible to stack format drivers on top of each other. In other words, even without this patch, we can make LUKS driver encrypt/decrypt the qcow2 payload, while keeping them completely orthogonal.

Yep, that is certainly possible, and it is what is intended for using LUKS with RBD, iSCSI, & other network drivers.

Quoted 10 lines

I think there is value in having LUKS integrated directly into qcow2 though. It means that given a qcow2 file you can 100% reliably distinguish between a file created with the intention of QEMU managing the LUKS encryption, from a file where the guest OS happens to have set up LUKS encryption in its virtual disk. If you don't have this, then given a random qcow2 file, you have to probe to see if LUKS is present or not. Given the security issues we've had in the past with raw images being turned into qcow2 images by a malicious guest writing a qcow2 header, I feel that having explicitly integration LUKS support in QCow is worthwhile as a concept.

Yes, I'm not objecting to explicit (read: mandatory) encryption in qcow2 in any way, and extending the format spec for LUKS is a good thing.

I mentioned stacked drivers because I wonder how good we can do in reusing block/crypto.c code to achieve this (to save 500+ new code in qcow2). For example I have a rough idea along this:

* In qcow2 spec, define type "2" of crypt_method for LUKS encryption, and state that if this method is used, the payload must be LUKS format as defined in cryptsetup's docs/on-disk-format.pdf, and driver will take care of encrypting/decrypting data in a way that is transparent to guest.

* In qcow2_open, if header's crypt_method is LUKS, set a special flag in the BlockDriverState to indicate that block layer should create an overlay crypto driver (which will be luks in this case), on top of this BDS. To do this we need some modification to bdrv_open.

* When qcow2_open is done, block layer will then instantiate a LUKS driver, which backed by the qcow2 BDS (as the BDS.file). This LUKS BDS will then be attached to guest device.

* From the guest PoV, R/W reqs are served as if it's an ordinary qcow2; from LUKS driver's PoV, it works properly formatted luks data, which is backed by whatever it doesn't care, be it an iscsi target, rbd block, local file, or a qcow2 image that has metadata; from the qcow2 driver's PoV, it only made sure that a LUKS driver covers itself, at instantiation time. Everything else operates the same way as a non-encrypted qcow2.

* Of course, qcow2_create would need some similar changes to the block layer as to bdrv_open, but that shouldn't be too hard.

Makes sense?

Fam

#52 lore raw

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

Quoted 54 lines · Fam Zheng
Quoted 14 lines · Daniel P. Berrange
Quoted 9 lines · Fam Zheng
Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

FWIW, with today's QEMU, it's possible to stack format drivers on top of each other. In other words, even without this patch, we can make LUKS driver encrypt/decrypt the qcow2 payload, while keeping them completely orthogonal.

Yep, that is certainly possible, and it is what is intended for using LUKS with RBD, iSCSI, & other network drivers.

Quoted 10 lines

I think there is value in having LUKS integrated directly into qcow2 though. It means that given a qcow2 file you can 100% reliably distinguish between a file created with the intention of QEMU managing the LUKS encryption, from a file where the guest OS happens to have set up LUKS encryption in its virtual disk. If you don't have this, then given a random qcow2 file, you have to probe to see if LUKS is present or not. Given the security issues we've had in the past with raw images being turned into qcow2 images by a malicious guest writing a qcow2 header, I feel that having explicitly integration LUKS support in QCow is worthwhile as a concept.

Yes, I'm not objecting to explicit (read: mandatory) encryption in qcow2 in any way, and extending the format spec for LUKS is a good thing.

I mentioned stacked drivers because I wonder how good we can do in reusing block/crypto.c code to achieve this (to save 500+ new code in qcow2). For example I have a rough idea along this:

* In qcow2 spec, define type "2" of crypt_method for LUKS encryption, and state that if this method is used, the payload must be LUKS format as defined in cryptsetup's docs/on-disk-format.pdf, and driver will take care of encrypting/decrypting data in a way that is transparent to guest.

* In qcow2_open, if header's crypt_method is LUKS, set a special flag in the BlockDriverState to indicate that block layer should create an overlay crypto driver (which will be luks in this case), on top of this BDS. To do this we need some modification to bdrv_open.

* When qcow2_open is done, block layer will then instantiate a LUKS driver, which backed by the qcow2 BDS (as the BDS.file). This LUKS BDS will then be attached to guest device.

* From the guest PoV, R/W reqs are served as if it's an ordinary qcow2; from LUKS driver's PoV, it works properly formatted luks data, which is backed by whatever it doesn't care, be it an iscsi target, rbd block, local file, or a qcow2 image that has metadata; from the qcow2 driver's PoV, it only made sure that a LUKS driver covers itself, at instantiation time. Everything else operates the same way as a non-encrypted qcow2.

Quoted 4 lines

* Of course, qcow2_create would need some similar changes to the block layer as to bdrv_open, but that shouldn't be too hard.

Makes sense?

Hmm, interesting idea. So essentially we'd be having a format driver be able to inform the generic block code to insert an encryption layer above it. The downside is that it leaks details about use of encryption out into the generic block code. The upside is that it reduces code in the qcow2 impl. I do wonder if that would lead to more or less code overall, or whether the generic block layer additions would cancel out the removals from qcow2.

BTW, we can probably reduce the amount of code in qcow2 regardless, as about 1/2 of the addition is related to handling of the QemuOpts <-> QCryptoBlockOpenOptions conversion, and I could share that with the block/crypto.c driver to a greater extent than I do now.

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 :|
#53 lore raw

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

In reply to Daniel P. Berrange
Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

I know Fam had some interesting ideas on changing qcow2 to be able to auto-load a LUKS format driver rather than duplicating code, which may completely change this patch, but I'll go ahead and review this patch as-is.

Quoted 2 lines

With the LUKS format it is neccessary to store the LUKS

s/neccessary/necessary/

Quoted 3 lines

partition header and key material in the QCow2 file. This data can be many MB in size, so cannot go into the QCow2 header region directly. Thus the spec is defines a FDE

s/is //

Quoted 14 lines

(Full Disk Encryption) header extension that specifies the offset of a set of clusters to hold the FDE headers, as well as the length of that region. The LUKS header is thus stored in these extra allocated clusters before the main image payload.

With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.

  $QEMU \
    -object secret,id=sec0,filename=/home/berrange/encrypted.pw \
    -drive file=/home/berrange/encrypted.qcow2,key-secret=sec0
Quoted 6 lines

The new LUKS format is set as the new default format when creating encrypted images. ie

  # qemu-img create --object secret,data=123456,id=sec0 \
       -f qcow2 -o encryption,key-secret=sec0 \
       test.qcow2 10G

Did we add '-o encryption' earlier in the series, or is this line a bit stale in reference to your --image-opts series?

Quoted 2 lines

Results in creation of an image using the LUKS format.

since this is a continuation of the earlier thought, s/Results/results/ s/in/in the/

Quoted 4 lines

For compatibility the old qcow2 AES format can still be used via the 'encryption-format' parameter which accepts the values 'luks' or 'qcowaes'.

s/qcowaes/qcow/ to match your earlier changes

Quoted 6 lines
  # qemu-img create --object secret,data=123456,id=sec0 \
       -f qcow2 -o encryption,key-secret=sec0,encryption-format=qcowaes \
       test.qcow2 10G
Quoted 8 lines
---
 block/qcow2-cluster.c      |  46 +----
 block/qcow2-refcount.c     |  10 +
 block/qcow2.c              | 502 ++++++++++++++++++++++++++++++++++++++-------
 block/qcow2.h              |  21 +-
 crypto/block-luks.c        |   1 -
 docs/specs/qcow2.txt       |  74 +++++++
 qapi/block-core.json       |   6 +-

As mentioned earlier in the series, a well-chosen order file (format-patch -Ofile, or git config diff.orderFile) that hoists these two changes first might make the overall patch easier to review.

Quoted 10 lines
 tests/qemu-iotests/049     |   2 +-
 tests/qemu-iotests/049.out |   7 +-
 tests/qemu-iotests/082.out | 189 +++++++++++++++++
 tests/qemu-iotests/087     |  28 ++-
 tests/qemu-iotests/087.out |  12 +-
 tests/qemu-iotests/134     |  18 +-
 tests/qemu-iotests/134.out |  21 +-
 tests/qemu-iotests/common  |   1 +
 15 files changed, 775 insertions(+), 163 deletions(-)

Starting my review at [1], then I'll return here [2].

Quoted 9 lines
block/qcow2-cluster.c +1 -1
index f5bc4f2..0512256 100644
--- a/block/qcow2-cluster.c
 
+++ b/block/qcow2-refcount.c
@@ -1847,6 +1847,16 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
         return ret;
     }
 

block/qcow2-cluster.c static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res, · line 1859

Quoted 10 lines
block/qcow2-cluster.c +10 -0
+    /* encryption */
+    if (s->crypto_header.length) {
+        ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
+                            s->crypto_header.offset,
+                            s->crypto_header.length);
+        if (ret < 0) {
+            return ret;
+        }
+    }
+

Do we ever allow turning off encryption, where we'd need to decrement the refcounts as the FDE header is removed?

Quoted 17 lines
block/qcow2-cluster.c +0 -0
     return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);
 }
 
block/qcow2.c +2 -0
index 2fae692..5249ca2 100644
@@ -34,6 +34,8 @@
 #include "qapi-event.h"
 #include "trace.h"
 #include "qemu/option_int.h"
+#include "qapi/opts-visitor.h"
+#include "qapi-visit.h"
 
 /*
   Differences with QCOW:

block/qcow2.c typedef struct { · line 65

Quoted 4 lines
block/qcow2.c +1 -0
@@ -60,6 +62,7 @@ typedef struct {
 #define  QCOW2_EXT_MAGIC_END 0
 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
+#define  QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x4c554b53

Aha: ASCII "LUKS", even though we expect the header to be useful for more than just LUKS encryption schemes. Would ASCII "CRYP" be any nicer? Or a random number, or the next set of hex digits from pi, or...?

I guess we don't have any real rules or patterns describing how magic numbers are supposed to be chosen, so it works for me.

Quoted 6 lines
block/qcow2.c +0 -0
 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
 {
@@ -74,6 +77,75 @@ static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
 }
 

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 88

Quoted 10 lines
block/qcow2.c +9 -0
 
+static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
+                                          uint8_t *buf, size_t buflen,
+                                          Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
+    ssize_t ret;
+
+    if ((offset + buflen) > s->crypto_header.length) {

The inner () are redundant, but I don't mind them.

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 90

Quoted 2 lines
block/qcow2.c +2 -0
+        error_setg(errp, "Request for data outside of extension header");
+        return -1;

Nice that you are trying to prevent reads beyond the block of data reserved by the FDE header; but is s->crypto_header.length the rounded-up cluster boundary, or just the length of the used portion of the LUKS header?...

Quoted 10 lines
block/qcow2.c +10 -0
+    }
+
+    ret = bdrv_pread(bs->file->bs,
+                     s->crypto_header.offset + offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not read encryption header");
+        return -1;
+    }
+    return ret;
+}

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 110

Quoted 10 lines
block/qcow2.c +10 -0
+
+
+static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
+                                          Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
+    int64_t ret;
+
+    s->crypto_header.length = headerlen + (headerlen % s->cluster_size);

...Huh? Are you trying to round up to a cluster boundary? This doesn't do what you want. And even if you had correctly rounded up to cluster boundary size, that means that qcow2_crypto_hdr_read_func() can now read the tail beyond the size recorded in the crypto header - which could be dangerous if it means that tail can overlap the same sector number used for the first guest payload sector which uses a sector number of payload_offset from the LUKS header for its IV.

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 112

Quoted 2 lines
block/qcow2.c +2 -0
+
+    ret = qcow2_alloc_clusters(bs, s->crypto_header.length);

Does qcow2_alloc_clusters(bs, headerlen) properly round up the allocation to a cluster boundary? If so, I think you want s->crypto_header.length = headerlen, full stop.

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 114

Quoted 2 lines
block/qcow2.c +2 -0
+    if (ret < 0) {
+        s->crypto_header.length = 0;

And it may be easier to not modify s->crypto_header.length except on successful allocation, rather than having to undo it on failure.

Quoted 11 lines
block/qcow2.c +11 -0
+        error_setg_errno(errp, -ret,
+                         "Cannot allocate cluster for LUKS header size %zu",
+                         headerlen);
+        return -1;
+    }
+
+    s->crypto_header.offset = ret;
+    return ret;
+}
+
+

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 135

Quoted 10 lines
block/qcow2.c +10 -0
+static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
+                                           const uint8_t *buf, size_t buflen,
+                                           Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
+    ssize_t ret;
+
+    if ((offset + buflen) > s->crypto_header.length) {
+        error_setg(errp, "Request for data outside of extension header");

Again, I think you want to be very careful and not allow writes beyond the initial header length reservation, even if that leaves the tail of the cluster-aligned FDE area unwritable.

Quoted 17 lines
block/qcow2.c +13 -0
+        return -1;
+    }
+
+    ret = bdrv_pwrite(bs->file->bs,
+                      s->crypto_header.offset + offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not read encryption header");
+        return -1;
+    }
+    return ret;
+}
+
+
 /* 
  * read qcow2 extension and fill bs
  * start reading from start_offset

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 159

Quoted 5 lines
block/qcow2.c +1 -0
@@ -83,6 +155,7 @@ static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
  */
 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
                                  uint64_t end_offset, void **p_feature_table,
+                                 int flags,
                                  Error **errp)

Worth packing these last two parameters on a single line?

Quoted 18 lines
block/qcow2.c +12 -0
 {
     BDRVQcow2State *s = bs->opaque;
@@ -159,6 +232,39 @@ static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
             }
             break;
 
+        case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
+            unsigned int cflags = 0;
+            if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
+                error_setg(errp, "CRYPTO header extension only "
+                           "expected with LUKS encryption method");
+                return -EINVAL;
+            }
+            if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
+                error_setg(errp, "CRYPTO header extension size %u, "
+                           "but expected size %zu", ext.len,
+                           sizeof(Qcow2CryptoHeaderExtension));
+                return -EINVAL;

block/qcow2.c static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 256

Quoted 10 lines
block/qcow2.c +10 -0
+            }
+
+            ret = bdrv_pread(bs->file->bs, offset, &s->crypto_header, ext.len);
+            if (ret < 0) {
+                error_setg_errno(errp, -ret,
+                                 "Unable to read CRYPTO header extension");
+                return ret;
+            }
+            be64_to_cpu(s->crypto_header.offset);
+            be64_to_cpu(s->crypto_header.length);

Seeing this made me look back at patch 7. It's convenient that the LUKS header also uses big-endian storage (otherwise, you'd have to tweak the portion of the qcow2 spec that requires big-endian everywhere to special case LUKS header content - although that is not the content being byte-swapped here).

block/qcow2.c static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 269

Quoted 13 lines
block/qcow2.c +11 -0
+
+            if (flags & BDRV_O_NO_IO) {
+                cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
+            }
+            s->crypto = qcrypto_block_open(s->crypto_opts,
+                                           qcow2_crypto_hdr_read_func,
+                                           bs, cflags, errp);
+            if (!s->crypto) {
+                return -EINVAL;
+            }
+        }   break;
         default:
             /* unknown magic - save it in case we need to rewrite the header */

Hmm. Based solely on the presence or absence of unknown headers, earlier versions of qemu-img that don't recognize the new FDE extension header would happily open an image without decrypting it, which may have disastrous results if it writes to guest data. But I think we are safe in that the only time the FDE extension header is present is if the crypt_method is 2, but older versions of qemu should reject crypt_method 2 as unknown. Phew - we don't have to burn an incompatible feature bit to protect newer images from being corrupted by an older qemu.

Quoted 14 lines
block/qcow2.c +5 -0
             {
@@ -472,6 +578,11 @@ static QemuOptsList qcow2_runtime_opts = {
             .type = QEMU_OPT_NUMBER,
             .help = "Clean unused cache entries after this time (in seconds)",
         },
+        {
+            .name = QCOW2_OPT_KEY_SECRET,
+            .type = QEMU_OPT_STRING,
+            .help = "ID of the secret that provides the encryption key",
+        },
         { /* end of list */ }
     },
 };

block/qcow2.c static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts, · line 705

Quoted 6 lines
block/qcow2.c +3 -0
@@ -589,6 +700,111 @@ static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
     }
 }
 
+
+static QCryptoBlockOpenOptions *
+qcow2_crypto_open_opts_init(QCryptoBlockFormat format, QemuOpts *opts,

qemu style doesn't usually split return type from function name. I won't request a reformat, but others might be more picky.

Quoted 5 lines
block/qcow2.c +5 -0
+static QCryptoBlockCreateOptions *
+qcow2_crypto_create_opts_init(QCryptoBlockFormat format, QemuOpts *opts,
+                              Error **errp)
+{
+    OptsVisitor *ov;

block/qcow2.c static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts, · line 763

Quoted 10 lines
block/qcow2.c +10 -0
+    QCryptoBlockCreateOptions *ret;
+    Error *local_err = NULL, *end_err = NULL;
+    Visitor *v;
+
+    ret = g_new0(QCryptoBlockCreateOptions, 1);
+    ret->format = format;
+
+    ov = opts_visitor_new(opts);
+    v = opts_get_visitor(ov);
+    visit_start_struct(v, NULL, NULL, NULL, 0, &local_err);

Depending on whether Markus' qapi-next branch lands first, this (and similar) lines will have to change to drop an unused NULL.

block/qcow2.c static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts, · line 722

Quoted 2 lines
block/qcow2.c +2 -0
+
+    visit_end_struct(v, &end_err);

and my pending patches beyond what is in qapi-next affect this line. Oh well, we'll get it figured out.

block/qcow2.c static int qcow2_update_options_prepare(BlockDriverState *bs, · line 976

Quoted 7 lines
block/qcow2.c +3 -0
@@ -754,6 +971,28 @@ static int qcow2_update_options_prepare(BlockDriverState *bs,
     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
 
+    switch (s->crypt_method_header) {
+    case QCOW_CRYPT_NONE:
+        break;

Are we allowing in-place updates to change the encryption method? It may be safer to require that in-place updates can't change encryption, for now (that is, you can only set encryption at creation of a new file, and then copy data from one file to another to change how it is encrypted). And even if we DO want to allow a user to convert an image from encrypted to plain, or from plain to encrypted, I would favor it as a separate patch, so that we make sure we properly handle the creation/removal of the FDE extension, as well as en/decrypting every byte of payload independently from simpler read/write of an encrypted image.

Quoted 11 lines
block/qcow2.c +3 -0
@@ -788,6 +1027,9 @@ static void qcow2_update_options_commit(BlockDriverState *bs,
         s->cache_clean_interval = r->cache_clean_interval;
         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
     }
+
+    qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
+    s->crypto_opts = r->crypto_opts;
 }
 
 static void qcow2_update_options_abort(BlockDriverState *bs,

block/qcow2.c static void qcow2_update_options_abort(BlockDriverState *bs, · line 1044

Quoted 4 lines
block/qcow2.c +1 -0
@@ -799,6 +1041,7 @@ static void qcow2_update_options_abort(BlockDriverState *bs,
     if (r->refcount_block_cache) {
         qcow2_cache_destroy(bs, r->refcount_block_cache);
     }
+    qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);

Again, I don't know that we should allow updating the use of crypto during an update options task, or if we do, it should be in a separate patch (let's get reading/writing to an encrypted image correct first, before we worry about in-place conversion).

block/qcow2.c static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, · line 1346

Quoted 12 lines
block/qcow2.c +2 -1
@@ -1104,12 +1337,37 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
 
     /* read qcow2 extensions */
     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
-        &local_err)) {
+                              flags, &local_err)) {
         error_propagate(errp, local_err);
         ret = -EINVAL;
         goto fail;
     }
 
+    /* qcow2_read_extension may have setup the crypto context

s/setup/set up/

Quoted 25 lines
block/qcow2.c +20 -0
+     * if the crypt method needs a header region, some methods
+     * don't need header extensions, so must check here
+     */
+    if (s->crypt_method_header && !s->crypto) {
 
@@ -1984,6 +2222,77 @@ static int qcow2_change_backing_file(BlockDriverState *bs,
     return qcow2_update_header(bs);
 }
 
+
+static int qcow2_change_encryption(BlockDriverState *bs, QemuOpts *opts,
+                                   Error **errp)
+{
+    BDRVQcow2State *s = bs->opaque;
+    const char *cryptostr;
+    QCryptoBlockCreateOptions *cryptoopts = NULL;
+    QCryptoBlock *crypto = NULL;
+    size_t i;
+    int ret = -EINVAL;
+
+    /* Default to LUKS if crypto-format is not set */
+    cryptostr = qemu_opt_get_del(opts, QCOW2_OPT_CRYPTO_FORMAT);
+    if (cryptostr) {
+        for (i = 0; i < Q_CRYPTO_BLOCK_FORMAT__MAX; i++) {
+            if (g_str_equal(QCryptoBlockFormat_lookup[i], cryptostr)) {

block/qcow2.c static int qcow2_change_backing_file(BlockDriverState *bs, · line 2250

Quoted 10 lines
block/qcow2.c +10 -0
+                cryptoopts = qcow2_crypto_create_opts_init(i, opts, errp);
+                if (!cryptoopts) {
+                    ret = -EINVAL;
+                    goto out;
+                }
+                break;
+            }
+        }
+        if (!cryptoopts) {
+            error_setg(errp, "Unknown crypto format %s", cryptostr);

Could use qapi_enum_parse() here.

block/qcow2.c static int qcow2_create2(const char *filename, int64_t total_size, · line 2584

Quoted 6 lines
block/qcow2.c +1 -1
@@ -2267,11 +2581,17 @@ static int qcow2_create2(const char *filename, int64_t total_size,
     bdrv_unref(bs);
     bs = NULL;
 
-    /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
+    /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning

s/$/./

block/qcow2.c static int qcow2_create2(const char *filename, int64_t total_size, · line 2594

Quoted 11 lines
block/qcow2.c +7 -1
+     * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
+     * have to setup decryption context. We're not doing any I/O on the top
+     * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
+     * not have effect.
+     */
     options = qdict_new();
     qdict_put(options, "driver", qstring_from_str("qcow2"));
     ret = bdrv_open(&bs, filename, NULL, options,
-                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
+                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING |
+                    BDRV_O_NO_IO, /* Don't want to activate encryption */

Do we really need the second comment, after the first?

block/qcow2.c static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts, · line 3372

Quoted 13 lines
block/qcow2.c +2 -2
                     &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
@@ -3046,9 +3366,9 @@ static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
-                                        !!s->cipher);
+                                        !!s->crypto);
 
-            if (encrypt != !!s->cipher) {
+            if (encrypt != !!s->crypto) {
                 error_report("Changing the encryption flag is not supported");

Oh, so we don't support changing the encryptiong yet (good). But it means I was confused about what was happening above with regards to code on changing encryption metadata.

Quoted 13 lines
block/qcow2.c +5 -0
@@ -163,6 +173,11 @@ typedef struct QCowSnapshot {
 struct Qcow2Cache;
 typedef struct Qcow2Cache Qcow2Cache;
 
+typedef struct Qcow2CryptoHeaderExtension {
+    uint64_t offset;
+    uint64_t length;
+} QEMU_PACKED Qcow2CryptoHeaderExtension;
+
 typedef struct Qcow2UnknownHeaderExtension {
     uint32_t magic;
     uint32_t len;

block/qcow2.c typedef struct BDRVQcow2State { · line 277

Quoted 8 lines
block/qcow2.c +3 -1
@@ -256,7 +271,9 @@ typedef struct BDRVQcow2State {
 
     CoMutex lock;
 
-    QCryptoCipher *cipher; /* current cipher, NULL if no key yet */
+    Qcow2CryptoHeaderExtension crypto_header; /* QCow2 header extension */
+    QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
+    QCryptoBlock *crypto; /* Disk encryption format driver */
     uint32_t crypt_method_header;

Seems reasonable.

Quoted 7 lines
block/qcow2.c +0 -0
     uint64_t snapshots_offset;
     int snapshots_size;
crypto/block-luks.c +0 -0
index 47630ee..2f4b983 100644

crypto/block-luks.c qcrypto_block_luks_create(QCryptoBlock *block, · line 995

Quoted 7 lines
crypto/block-luks.c +0 -1
@@ -990,7 +990,6 @@ qcrypto_block_luks_create(QCryptoBlock *block,
         cpu_to_be32s(&luks->header.key_slots[i].stripes);
     }
 
-
     /* Write out the partition header and key slot headers */
     writefunc(block, 0,
               (const uint8_t *)&luks->header,

Spurious hunk, probably from rebasing.

Continuing on at [3].

docs/specs/qcow2.txt

Quoted 4 lines
docs/specs/qcow2.txt +0 -0
index f236d8c..4d141a6 100644

[1] Starting my review here.

docs/specs/qcow2.txt The first cluster of a qcow2 image contains the file header: · line 48

Quoted 5 lines
docs/specs/qcow2.txt +1 -0
@@ -45,6 +45,7 @@ The first cluster of a qcow2 image contains the file header:
          32 - 35:   crypt_method
                     0 for no encryption
                     1 for AES encryption
+                    2 for LUKS encryption

May be worth an additional comment:

The choice of crypt_method affects whether the full disk encryption header extension must be used; see details below.

docs/specs/qcow2.txt be stored. Each extension has a structure like the following: · line 127

Quoted 8 lines
docs/specs/qcow2.txt +1 -0
          36 - 39:   l1_size
                     Number of entries in the active L1 table
@@ -123,6 +124,7 @@ be stored. Each extension has a structure like the following:
                         0x00000000 - End of the header extension area
                         0xE2792ACA - Backing file format name
                         0x6803f857 - Feature name table
+                        0x4c554b53 - Full disk encryption header pointer

We aren't very consistent on case within the hex constants. Not your fault, but might be nice to fix.

Quoted 11 lines
docs/specs/qcow2.txt +4 -0
                         other      - Unknown header extension, can be safely
                                      ignored
 
@@ -166,6 +168,78 @@ the header extension data. Each entry look like this:
                     terminated if it has full length)
 
 
+== Full disk encryption header pointer ==
+
+The full disk encryption header must be present if, and only if, the
+'crypt_method' header requires metadata. Currently this is only true

docs/specs/qcow2.txt the header extension data. Each entry look like this: · line 184

Quoted 10 lines
docs/specs/qcow2.txt +10 -0
+of the 'LUKS' crypt method. The header extension must be absent for
+other methods.
+
+This header provides the offset at which the crypt method can store
+its additional data, as well as the length of such data.
+
+    Byte  0 -  7:   Offset into the image file at which the encryption
+                    header starts. Must be aligned to a cluster boundary.
+    Byte  8 - 16:   Length of the encryption header. Must be a multiple
+                    of the cluster size.

I would add "in bytes" to both descriptions.

Should we explicitly document that the length occupied by the extension header is NOT counted towards the guest-visible length; therefore, the guest-visible size is the payload of the encrypted disk?

docs/specs/qcow2.txt the header extension data. Each entry look like this: · line 188

Quoted 4 lines
docs/specs/qcow2.txt +4 -0
+
+While the header extension allocates the length as a multiple of the
+cluster size, the encryption header may not consume the full permitted
+allocation.

Should we require that any unused trailing space be all 0?

docs/specs/qcow2.txt the header extension data. Each entry look like this: · line 201

Quoted 13 lines
docs/specs/qcow2.txt +13 -0
+
+For the LUKS crypt method, the encryption header works as follows.
+
+The first 592 bytes of the header clusters will contain the LUKS
+partition header. This is then followed by the key material data areas.
+The size of the key material data areas is determined by the number of
+stripes in the key slot and key size. Refer to the LUKS format
+specification ('docs/on-disk-format.pdf' in the cryptsetup source
+package) for details of the LUKS partition header format.
+
+In the LUKS partition header, the "payload-offset" field does not refer
+to the offset of the QCow2 payload. Instead it simply refers to the
+total required length of the LUKS header plus key material regions.

I'm guessing that you are allowing the payload-offset to NOT be a multiple of the cluster size. It may be worth documenting that since LUKS requires encryption to happen on 512-byte sector boundaries, where the sector number feeds the IV used to encrypt that sector, that guest-visible sector 0 is treated as LUKS sector payload-offset, even if payload-offset is not qcow2-cluster-aligned.

docs/specs/qcow2.txt the header extension data. Each entry look like this: · line 208

Quoted 7 lines
docs/specs/qcow2.txt +7 -0
+
+In the LUKS key slots header, the "key-material-offset" is relative
+to the start of the LUKS header clusters in the qcow2 container,
+not the start of the qcow2 file.
+
+Logically the layout looks like
+

How does encryption interact with internal snapshots? Is the encryption header over all snapshots at once, or are we taking snapshots of the current key slot usage? That is, if we later add a command to allow key slot manipulation (add a new user password on a vacant key slot, or revoke a key slot), what happens if the user takes a snapshot, revokes a key slot, then takes a second snapshot, then wants to revert to the first snapshot? Will the revoked password still be usable to unlock the first snapshot contents, or did revoking it destroy that user's ability to access the snapshot?

I'm leaning towards the latter - there is only a single LUKS header for the entire qcow2 file; LUKS key management is global regardless of what ever other content is stored, and the user passwords that unlock the LUKS master key control whether a user can access all or none of the rest of the qcow2 data.

I suspect that backing files are NOT encrypted by the LUKS header of the active file. That is, if we go to read a sector, and it is not present in the current qcow2 image, then reading it from the backing file does NOT need to decrypt data (unless the backing file itself independently used a LUKS header).

Conversely, if we have a backing file that is encrypted, do we want to place any requirements that the wrapper file can/must use encryption? I don't see any technical reasons that would require it, but from a data safety standpoint, it seems awkward that a user that provides the LUKS password to read the backing file can then write the same data unencrypted into their wrapper file on copy-on-write operations.

docs/specs/qcow2.txt line 1793

Quoted 7 lines
docs/specs/qcow2.txt +3 -0
+++ b/qapi/block-core.json
@@ -1789,6 +1789,8 @@
 # @cache-clean-interval:  #optional clean unused entries in the L2 and refcount
 #                         caches. The interval is in seconds. The default value
 #                         is 0 and it disables this feature (since 2.5)
+# @key-secret:            #optional the ID of a QCryptoSecret object providing
+#                         the decryption key (since 2.6)

As in other patches in this series, may be worth mentioning that this is mandatory for doing I/O on an encrypted disk, and optional when the disk is not encrypted or when only metadata is being probed.

Quoted 16 lines
docs/specs/qcow2.txt +2 -2
 #
 # Since: 1.7
 ##
@@ -1802,8 +1804,8 @@
             '*cache-size': 'int',
             '*l2-cache-size': 'int',
             '*refcount-cache-size': 'int',
-            '*cache-clean-interval': 'int' } }
-
+            '*cache-clean-interval': 'int',
+            '*key-secret': 'str' } }
 
 ##
 # @BlockdevOptionsArchipelago
tests/qemu-iotests/049 +0 -0
index 93aa0ea..765b950 100755

tests/qemu-iotests/049

Quoted 1 line
tests/qemu-iotests/049 +0 -1
--- a/tests/qemu-iotests/049

Okay, back to [2], then this will be spot [3].

Quoted 18 lines

+++ b/tests/qemu-iotests/049

tests/qemu-iotests/049 +1 -1
@@ -107,7 +107,7 @@ test_qemu_img create -f $IMGFMT -o preallocation=1234 "$TEST_IMG" 64M
 echo "== Check encryption option =="
 echo
 test_qemu_img create -f $IMGFMT -o encryption=off "$TEST_IMG" 64M
-test_qemu_img create -f $IMGFMT -o encryption=on "$TEST_IMG" 64M
+test_qemu_img create -f $IMGFMT --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 "$TEST_IMG" 64M
 
 echo "== Check lazy_refcounts option (only with v3) =="
 echo
tests/qemu-iotests/049.out +0 -0
index a2b6703..c9f0bc5 100644
@@ -186,14 +186,11 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si
 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
 

tests/qemu-iotests/049.out Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si · line 193

Quoted 10 lines
tests/qemu-iotests/049.out +2 -5
-qemu-img create -f qcow2 -o encryption=on TEST_DIR/t.qcow2 64M
+qemu-img create -f qcow2 --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 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
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16 key-secret=sec0

So now that we support LUKS encryption by default, we no longer need the deprecation warning. Do we still forbid the creation of new images with non-LUKS encryption? That is, even though the new code will let us read old images, I want to make sure we test the error message (or deprecation warning) when trying to use the new options to request the old format during image creation.

Quoted 9 lines
tests/qemu-iotests/049.out +0 -0
 == Check lazy_refcounts option (only with v3) ==
 
tests/qemu-iotests/082.out +0 -0
index a952330..b0572d4 100644
@@ -53,6 +53,13 @@ cluster_size     qcow2 cluster size
 preallocation    Preallocation mode (allowed values: off, metadata, falloc, full)

tests/qemu-iotests/082.out cluster_size qcow2 cluster size · line 63

Quoted 10 lines
tests/qemu-iotests/082.out +7 -0
 lazy_refcounts   Postpone refcount updates
 refcount_bits    Width of a reference count entry in bits
+encryption-format Encryption format, 'luks' (default), 'qcow' (deprecated)
+key-secret       ID of the secret that provides the encryption key
+cipher-alg       Name of encryption cipher algorithm
+cipher-mode      Name of encryption cipher mode
+ivgen-alg        Name of IV generator algorithm
+ivgen-hash-alg   Name of IV generator hash algorithm
+hash-alg         Name of encryption hash algorithm
 nocow            Turn off copy-on-write (valid only on btrfs)

Should this help text mention defaults?

Quoted 22 lines
tests/qemu-iotests/082.out +11 -1
+++ b/tests/qemu-iotests/087
@@ -184,9 +184,18 @@ echo
 echo === Encrypted image ===
 echo
 
-_make_test_img -o encryption=on $size
+_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 $size
 run_qemu -S <<EOF
 { "execute": "qmp_capabilities" }
+{ "execute": "object-add",
+  "arguments": {
+      "qom-type": "secret",
+      "id": "sec0",
+      "props": {
+          "data": "123456"
+      }
+  }
+}
 { "execute": "blockdev-add",
   "arguments": {
       "options": {

tests/qemu-iotests/082.out run_qemu -S <<EOF · line 209

Quoted 7 lines
tests/qemu-iotests/082.out +2 -1
@@ -195,7 +204,8 @@ run_qemu -S <<EOF
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
-        }
+        },
+        "key-secret": "sec0"
       }

Nice - proof that we can hot-plug a secret. Which means libvirt will have to be taught to _always_ prepopulate a master key for new enough qemu, even if there is no encrypted disk on the command line, to cater for hotplug down the road.

tests/qemu-iotests/082.out _supported_os Linux · line 47

Quoted 7 lines
tests/qemu-iotests/082.out +3 -1
+++ b/tests/qemu-iotests/134
@@ -44,23 +44,31 @@ _supported_os Linux
 
 
-128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+can't open device /home/berrange/src/virt/qemu/tests/qemu-iotests/scratch/t.qcow2: Invalid password, cannot unlock any keyslot
+no file open, try 'help open'

Umm, you'll want to fix this test to run on more than just your machine.

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

Re: [Qemu-devel] [PATCH v2 12/17] qcow2: convert QCow2 to use QCryptoBlock for encryption

Quoted 28 lines · Eric Blake
Quoted 4 lines · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. As well as continued support for the legacy QCow2 encryption format, the appealing benefit is that it enables support for the LUKS format inside qcow2.

I know Fam had some interesting ideas on changing qcow2 to be able to auto-load a LUKS format driver rather than duplicating code, which may completely change this patch, but I'll go ahead and review this patch as-is.

Quoted 17 lines

(Full Disk Encryption) header extension that specifies the offset of a set of clusters to hold the FDE headers, as well as the length of that region. The LUKS header is thus stored in these extra allocated clusters before the main image payload.

With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.

  $QEMU \
    -object secret,id=sec0,filename=/home/berrange/encrypted.pw \
    -drive file=/home/berrange/encrypted.qcow2,key-secret=sec0

The new LUKS format is set as the new default format when creating encrypted images. ie

Quoted 6 lines
Quoted 3 lines
  # qemu-img create --object secret,data=123456,id=sec0 \
       -f qcow2 -o encryption,key-secret=sec0 \
       test.qcow2 10G

Did we add '-o encryption' earlier in the series, or is this line a bit stale in reference to your --image-opts series?

'-o encryption' is actually the pre-existing flag used to turn on the existing qcow2 built-in AES encryption. I repurposed it as a generic flag to indicate desire for encryption, and have the new 'encryption-format' flag to say whether you want the legacy AES or modern LUKS format. IOW people using '-o encryption' today will automatically start getting LUKS format after this change is applied.

Quoted 9 lines
Quoted 9 lines
block/qcow2-cluster.c +1 -1
index f5bc4f2..0512256 100644
--- a/block/qcow2-cluster.c
 
+++ b/block/qcow2-refcount.c
@@ -1847,6 +1847,16 @@ static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
         return ret;
     }
 
Quoted 13 lines

block/qcow2-cluster.c static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res, · line 1859

Quoted 10 lines
block/qcow2-cluster.c +10 -0
+    /* encryption */
+    if (s->crypto_header.length) {
+        ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
+                            s->crypto_header.offset,
+                            s->crypto_header.length);
+        if (ret < 0) {
+            return ret;
+        }
+    }
+

Do we ever allow turning off encryption, where we'd need to decrement the refcounts as the FDE header is removed?

No, once a fle has encryption it can't be removed. Likewise you have to choose it at time of creation - you can't add it afterwards.

Quoted 23 lines
Quoted 14 lines
block/qcow2.c +2 -0
index 2fae692..5249ca2 100644
@@ -34,6 +34,8 @@
 #include "qapi-event.h"
 #include "trace.h"
 #include "qemu/option_int.h"
+#include "qapi/opts-visitor.h"
+#include "qapi-visit.h"
 
 /*
   Differences with QCOW:

block/qcow2.c typedef struct { · line 65

Quoted 4 lines
block/qcow2.c +1 -0
@@ -60,6 +62,7 @@ typedef struct {
 #define  QCOW2_EXT_MAGIC_END 0
 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
+#define  QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x4c554b53

Aha: ASCII "LUKS", even though we expect the header to be useful for more than just LUKS encryption schemes. Would ASCII "CRYP" be any nicer? Or a random number, or the next set of hex digits from pi, or...?

Quoted 2 lines

I guess we don't have any real rules or patterns describing how magic numbers are supposed to be chosen, so it works for me.

Hah, top marks for reverse engineering my magic constant. I had completely forgotten that I used the ASCII values of 'LUKS' for this constant :-)

Since this is not luks specific anymore I'll change this value to 0x0537be77. Bonus points to anyone who can explain the significance of that number (hint it is not an ascii representation of anything - its a special number in its own right :-)

Quoted 12 lines

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 88

Quoted 9 lines
block/qcow2.c +9 -0
+static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
+                                          uint8_t *buf, size_t buflen,
+                                          Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
+    ssize_t ret;
+
+    if ((offset + buflen) > s->crypto_header.length) {

The inner () are redundant, but I don't mind them.

Quoted 7 lines

block/qcow2.c

Quoted 2 lines
block/qcow2.c +2 -0
+        error_setg(errp, "Request for data outside of extension header");
+        return -1;

Nice that you are trying to prevent reads beyond the block of data reserved by the FDE header; but is s->crypto_header.length the rounded-up cluster boundary, or just the length of the used portion of the LUKS header?...

It is intended to record the allocated space (ie rounded to the cluster boundary), but on reflection, I think I'll change it to exactly the size of the LUKS header.

Quoted 28 lines
Quoted 10 lines
block/qcow2.c +10 -0
+    }
+
+    ret = bdrv_pread(bs->file->bs,
+                     s->crypto_header.offset + offset, buf, buflen);
+    if (ret < 0) {
+        error_setg_errno(errp, -ret, "Could not read encryption header");
+        return -1;
+    }
+    return ret;
+}

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 110

Quoted 10 lines
block/qcow2.c +10 -0
+
+
+static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
+                                          Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
+    int64_t ret;
+
+    s->crypto_header.length = headerlen + (headerlen % s->cluster_size);

...Huh? Are you trying to round up to a cluster boundary? This doesn't do what you want. And even if you had correctly rounded up to cluster boundary size, that means that qcow2_crypto_hdr_read_func() can now read the tail beyond the size recorded in the crypto header - which could be dangerous if it means that tail can overlap the same sector number used for the first guest payload sector which uses a sector number of payload_offset from the LUKS header for its IV.>

Quoted 6 lines

block/qcow2.c

Quoted 2 lines
block/qcow2.c +2 -0
+
+    ret = qcow2_alloc_clusters(bs, s->crypto_header.length);

Does qcow2_alloc_clusters(bs, headerlen) properly round up the allocation to a cluster boundary? If so, I think you want s->crypto_header.length = headerlen, full stop.

Agreed, I will make it so.

Quoted 24 lines

block/qcow2.c

Quoted 3 lines
block/qcow2.c +2 -0
+    if (ret < 0) {
+        s->crypto_header.length = 0;

And it may be easier to not modify s->crypto_header.length except on successful allocation, rather than having to undo it on failure.

Quoted 17 lines
block/qcow2.c +17 -0
+        error_setg_errno(errp, -ret,
+                         "Cannot allocate cluster for LUKS header size %zu",
+                         headerlen);
+        return -1;
+    }
+
+    s->crypto_header.offset = ret;
+    return ret;
+}
+
+
+static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
+                                           const uint8_t *buf, size_t buflen,
+                                           Error **errp, void *opaque)
+{
+    BlockDriverState *bs = opaque;
+    BDRVQcow2State *s = bs->opaque;
Quoted 8 lines

block/qcow2.c static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) · line 89

Quoted 4 lines
block/qcow2.c +4 -0
+    ssize_t ret;
+
+    if ((offset + buflen) > s->crypto_header.length) {
+        error_setg(errp, "Request for data outside of extension header");

Again, I think you want to be very careful and not allow writes beyond the initial header length reservation, even if that leaves the tail of the cluster-aligned FDE area unwritable.

Yes, this will be ok when the length refers to the luks header only

Quoted 26 lines
Quoted 26 lines
 {
     BDRVQcow2State *s = bs->opaque;
block/qcow2.c +20 -0
@@ -159,6 +232,39 @@ static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
             }
             break;
 
+        case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
+            unsigned int cflags = 0;
+            if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
+                error_setg(errp, "CRYPTO header extension only "
+                           "expected with LUKS encryption method");
+                return -EINVAL;
+            }
+            if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
+                error_setg(errp, "CRYPTO header extension size %u, "
+                           "but expected size %zu", ext.len,
+                           sizeof(Qcow2CryptoHeaderExtension));
+                return -EINVAL;
+            }
+
+            ret = bdrv_pread(bs->file->bs, offset, &s->crypto_header, ext.len);
+            if (ret < 0) {
+                error_setg_errno(errp, -ret,
+                                 "Unable to read CRYPTO header extension");
+                return ret;
+            }
Quoted 8 lines

block/qcow2.c static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 256

Quoted 2 lines
block/qcow2.c +2 -0
+            be64_to_cpu(s->crypto_header.offset);
+            be64_to_cpu(s->crypto_header.length);

Seeing this made me look back at patch 7. It's convenient that the LUKS header also uses big-endian storage (otherwise, you'd have to tweak the portion of the qcow2 spec that requires big-endian everywhere to special case LUKS header content - although that is not the content being byte-swapped here).

Yes its fortunate everyone agrees that big-endian is best on disk :-)

Quoted 14 lines

block/qcow2.c static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, · line 269

Quoted 13 lines
block/qcow2.c +11 -0
+
+            if (flags & BDRV_O_NO_IO) {
+                cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
+            }
+            s->crypto = qcrypto_block_open(s->crypto_opts,
+                                           qcow2_crypto_hdr_read_func,
+                                           bs, cflags, errp);
+            if (!s->crypto) {
+                return -EINVAL;
+            }
+        }   break;
         default:
             /* unknown magic - save it in case we need to rewrite the header */
Quoted 8 lines

Hmm. Based solely on the presence or absence of unknown headers, earlier versions of qemu-img that don't recognize the new FDE extension header would happily open an image without decrypting it, which may have disastrous results if it writes to guest data. But I think we are safe in that the only time the FDE extension header is present is if the crypt_method is 2, but older versions of qemu should reject crypt_method 2 as unknown. Phew - we don't have to burn an incompatible feature bit to protect newer images from being corrupted by an older qemu.

Yeah, the crypt_method value saves us, because all older versions are careful to validate that.

Quoted 6 lines

block/qcow2.c static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts, · line 705

Quoted 3 lines
block/qcow2.c +3 -0
+
+static QCryptoBlockOpenOptions *
+qcow2_crypto_open_opts_init(QCryptoBlockFormat format, QemuOpts *opts,

qemu style doesn't usually split return type from function name. I won't request a reformat, but others might be more picky.

The lines get rather long if I dont :-)

Quoted 4 lines
Quoted 4 lines
block/qcow2.c +0 -0
@@ -754,6 +971,28 @@ static int qcow2_update_options_prepare(BlockDriverState *bs,
     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
 
Quoted 13 lines

block/qcow2.c static int qcow2_update_options_prepare(BlockDriverState *bs, · line 976

Quoted 3 lines
block/qcow2.c +3 -0
+    switch (s->crypt_method_header) {
+    case QCOW_CRYPT_NONE:
+        break;

Are we allowing in-place updates to change the encryption method? It may be safer to require that in-place updates can't change encryption, for now (that is, you can only set encryption at creation of a new file, and then copy data from one file to another to change how it is encrypted). And even if we DO want to allow a user to convert an image from encrypted to plain, or from plain to encrypted, I would favor it as a separate patch, so that we make sure we properly handle the creation/removal of the FDE extension, as well as en/decrypting every byte of payload independently from simpler read/write of an encrypted image.

I don't see us ever allowing in-place changes to encryption. You'd have to re-write the entire file contents with obvious disaster if you hit an error 1/2 way through. Far better to use qemu-img convert instead.

Quoted 11 lines

block/qcow2.c static void qcow2_update_options_abort(BlockDriverState *bs, · line 1044

Quoted 6 lines
block/qcow2.c +1 -0
 static void qcow2_update_options_abort(BlockDriverState *bs,
@@ -799,6 +1041,7 @@ static void qcow2_update_options_abort(BlockDriverState *bs,
     if (r->refcount_block_cache) {
         qcow2_cache_destroy(bs, r->refcount_block_cache);
     }
+    qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);

Again, I don't know that we should allow updating the use of crypto during an update options task, or if we do, it should be in a separate patch (let's get reading/writing to an encrypted image correct first, before we worry about in-place conversion).

Note despite the name the qcow2_update_options* methods are actually used during initial image creation, so this code is about updating in-place options.

Quoted 12 lines

block/qcow2.c static int qcow2_create2(const char *filename, int64_t total_size, · line 2594

Quoted 11 lines
block/qcow2.c +7 -1
+     * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
+     * have to setup decryption context. We're not doing any I/O on the top
+     * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
+     * not have effect.
+     */
     options = qdict_new();
     qdict_put(options, "driver", qstring_from_str("qcow2"));
     ret = bdrv_open(&bs, filename, NULL, options,
-                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
+                    BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING |
+                    BDRV_O_NO_IO, /* Don't want to activate encryption */
Quoted 1 line

Do we really need the second comment, after the first?

Not any more, no.

Quoted 7 lines
Quoted 7 lines
block/qcow2.c +1 -1
@@ -3046,9 +3366,9 @@ static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
-                                        !!s->cipher);
+                                        !!s->crypto);
 
Quoted 7 lines

block/qcow2.c static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts, · line 3372

Quoted 3 lines
block/qcow2.c +1 -1
-            if (encrypt != !!s->cipher) {
+            if (encrypt != !!s->crypto) {
                 error_report("Changing the encryption flag is not supported");

Oh, so we don't support changing the encryptiong yet (good). But it means I was confused about what was happening above with regards to code on changing encryption metadata.

Yes, its a misleading method name earlier used for 2 different things :-)

Quoted 4 lines
Quoted 4 lines
block/qcow2.c +0 -0
@@ -166,6 +168,78 @@ the header extension data. Each entry look like this:
                     terminated if it has full length)
 
 
Quoted 16 lines
Quoted 4 lines
block/qcow2.c +4 -0
+== Full disk encryption header pointer ==
+
+The full disk encryption header must be present if, and only if, the
+'crypt_method' header requires metadata. Currently this is only true

block/qcow2.c the header extension data. Each entry look like this: · line 184

Quoted 10 lines
block/qcow2.c +10 -0
+of the 'LUKS' crypt method. The header extension must be absent for
+other methods.
+
+This header provides the offset at which the crypt method can store
+its additional data, as well as the length of such data.
+
+    Byte  0 -  7:   Offset into the image file at which the encryption
+                    header starts. Must be aligned to a cluster boundary.
+    Byte  8 - 16:   Length of the encryption header. Must be a multiple
+                    of the cluster size.

I would add "in bytes" to both descriptions.

Ok.

Quoted 3 lines

Should we explicitly document that the length occupied by the extension header is NOT counted towards the guest-visible length; therefore, the guest-visible size is the payload of the encrypted disk?

Sure, can do.

Quoted 5 lines

block/qcow2.c the header extension data. Each entry look like this: · line 187

Quoted 3 lines
block/qcow2.c +3 -0
+While the header extension allocates the length as a multiple of the
+cluster size, the encryption header may not consume the full permitted
+allocation.

Should we require that any unused trailing space be all 0?

I guess it might be a nice idea to have it zeroed in case it becomes important later.

Quoted 11 lines
Quoted 11 lines
block/qcow2.c +11 -0
+For the LUKS crypt method, the encryption header works as follows.
+
+The first 592 bytes of the header clusters will contain the LUKS
+partition header. This is then followed by the key material data areas.
+The size of the key material data areas is determined by the number of
+stripes in the key slot and key size. Refer to the LUKS format
+specification ('docs/on-disk-format.pdf' in the cryptsetup source
+package) for details of the LUKS partition header format.
+
+In the LUKS partition header, the "payload-offset" field does not refer
+to the offset of the QCow2 payload. Instead it simply refers to the
Quoted 8 lines

block/qcow2.c the header extension data. Each entry look like this: · line 199

Quoted 1 line
block/qcow2.c +1 -0
+total required length of the LUKS header plus key material regions.

I'm guessing that you are allowing the payload-offset to NOT be a multiple of the cluster size. It may be worth documenting that since LUKS requires encryption to happen on 512-byte sector boundaries, where the sector number feeds the IV used to encrypt that sector, that guest-visible sector 0 is treated as LUKS sector payload-offset, even if payload-offset is not qcow2-cluster-aligned.

Yeah, there's no restriction on payload-offset at all. Essentially the payload-offset is completely redundant when used in the context of qcow2. We could easily have said it should be 0, since qcow2 determines the actual payload offset. I felt it was worth leving it to record the value LUKS would ordinarily have used, even though we don't need it.

Quoted 17 lines

block/qcow2.c the header extension data. Each entry look like this: · line 205

Quoted 6 lines
block/qcow2.c +6 -0
+In the LUKS key slots header, the "key-material-offset" is relative
+to the start of the LUKS header clusters in the qcow2 container,
+not the start of the qcow2 file.
+
+Logically the layout looks like
+

How does encryption interact with internal snapshots? Is the encryption header over all snapshots at once, or are we taking snapshots of the current key slot usage? That is, if we later add a command to allow key slot manipulation (add a new user password on a vacant key slot, or revoke a key slot), what happens if the user takes a snapshot, revokes a key slot, then takes a second snapshot, then wants to revert to the first snapshot? Will the revoked password still be usable to unlock the first snapshot contents, or did revoking it destroy that user's ability to access the snapshot?

Quoted 5 lines

I'm leaning towards the latter - there is only a single LUKS header for the entire qcow2 file; LUKS key management is global regardless of what ever other content is stored, and the user passwords that unlock the LUKS master key control whether a user can access all or none of the rest of the qcow2 data.

NB passwords have no direct relationship to the data encryption key. The passwords are just used to encrypt the master key. So you can change the passwords at any time, without loosing ability to decrypt old data. IOW, we can completely ignore the issue of snapshots. All snapshot data is using the same master key.

Quoted 5 lines

I suspect that backing files are NOT encrypted by the LUKS header of the active file. That is, if we go to read a sector, and it is not present in the current qcow2 image, then reading it from the backing file does NOT need to decrypt data (unless the backing file itself independently used a LUKS header).

Yep, whether any backing file uses encryption is independant of the decision wrt encryption for this file.

Quoted 6 lines

Conversely, if we have a backing file that is encrypted, do we want to place any requirements that the wrapper file can/must use encryption? I don't see any technical reasons that would require it, but from a data safety standpoint, it seems awkward that a user that provides the LUKS password to read the backing file can then write the same data unencrypted into their wrapper file on copy-on-write operations.

This feels like a policy decision that belongs in the mgmt app - indeed that situation already exists today. ie you could have created a qcow2 file that points to a /dev/mapper/BLAH that is in fact backed by a LUKS volume.

Quoted 11 lines

block/qcow2.c line 1793

Quoted 7 lines
block/qcow2.c +3 -0
+++ b/qapi/block-core.json
@@ -1789,6 +1789,8 @@
 # @cache-clean-interval:  #optional clean unused entries in the L2 and refcount
 #                         caches. The interval is in seconds. The default value
 #                         is 0 and it disables this feature (since 2.5)
+# @key-secret:            #optional the ID of a QCryptoSecret object providing
+#                         the decryption key (since 2.6)

As in other patches in this series, may be worth mentioning that this is mandatory for doing I/O on an encrypted disk, and optional when the disk is not encrypted or when only metadata is being probed.

Yes

Quoted 17 lines
Quoted 17 lines
tests/qemu-iotests/049.out +1 -5
index a2b6703..c9f0bc5 100644
@@ -186,14 +186,11 @@ Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si
 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 create -f qcow2 --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 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
Quoted 8 lines

tests/qemu-iotests/049.out Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=off cluster_si · line 193

Quoted 1 line
tests/qemu-iotests/049.out +1 -0
+Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16 key-secret=sec0

So now that we support LUKS encryption by default, we no longer need the deprecation warning. Do we still forbid the creation of new images with non-LUKS encryption? That is, even though the new code will let us read old images, I want to make sure we test the error message (or deprecation warning) when trying to use the new options to request the old format during image creation.

Forbidding creation of legacy encryption is dealt with in a later patch.

Quoted 12 lines
Quoted 12 lines
tests/qemu-iotests/049.out +0 -0
 == Check lazy_refcounts option (only with v3) ==
 
tests/qemu-iotests/082.out +2 -0
index a952330..b0572d4 100644
@@ -53,6 +53,13 @@ cluster_size     qcow2 cluster size
 preallocation    Preallocation mode (allowed values: off, metadata, falloc, full)
 lazy_refcounts   Postpone refcount updates
 refcount_bits    Width of a reference count entry in bits
+encryption-format Encryption format, 'luks' (default), 'qcow' (deprecated)
+key-secret       ID of the secret that provides the encryption key
Quoted 8 lines

tests/qemu-iotests/082.out cluster_size qcow2 cluster size · line 63

Quoted 6 lines
tests/qemu-iotests/082.out +5 -0
+cipher-alg       Name of encryption cipher algorithm
+cipher-mode      Name of encryption cipher mode
+ivgen-alg        Name of IV generator algorithm
+ivgen-hash-alg   Name of IV generator hash algorithm
+hash-alg         Name of encryption hash algorithm
 nocow            Turn off copy-on-write (valid only on btrfs)

Should this help text mention defaults?

Yeah, good idea.

Quoted 26 lines
Quoted 26 lines
tests/qemu-iotests/082.out +11 -2
+++ b/tests/qemu-iotests/087
@@ -184,9 +184,18 @@ echo
 echo === Encrypted image ===
 echo
 
-_make_test_img -o encryption=on $size
+_make_test_img --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 $size
 run_qemu -S <<EOF
 { "execute": "qmp_capabilities" }
+{ "execute": "object-add",
+  "arguments": {
+      "qom-type": "secret",
+      "id": "sec0",
+      "props": {
+          "data": "123456"
+      }
+  }
+}
 { "execute": "blockdev-add",
   "arguments": {
       "options": {
@@ -195,7 +204,8 @@ run_qemu -S <<EOF
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
-        }
Quoted 8 lines

tests/qemu-iotests/082.out run_qemu -S <<EOF · line 209

Quoted 3 lines
tests/qemu-iotests/082.out +2 -0
+        },
+        "key-secret": "sec0"
       }

Nice - proof that we can hot-plug a secret. Which means libvirt will have to be taught to _always_ prepopulate a master key for new enough qemu, even if there is no encrypted disk on the command line, to cater for hotplug down the road.

You can actually hotplug the master key too, but for simplicity I expect that libvirt will just generate a AES master key for all QEMU versions >= 2.6. We need it for encrypting RBD, iSCSI, Curl passwords too.

Quoted 9 lines

tests/qemu-iotests/082.out _supported_os Linux · line 47

Quoted 7 lines
tests/qemu-iotests/082.out +3 -1
+++ b/tests/qemu-iotests/134
@@ -44,23 +44,31 @@ _supported_os Linux
 
 
-128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
+can't open device /home/berrange/src/virt/qemu/tests/qemu-iotests/scratch/t.qcow2: Invalid password, cannot unlock any keyslot
+no file open, try 'help open'

Umm, you'll want to fix this test to run on more than just your machine.

Opps :-)

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 :|
#55 lore raw

PATCH v2 13/17 qcow: make encrypt_sectors encrypt in place

In reply to Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change encrypt_sectors() to assume use of a single buffer, encrypting in place. One current caller all uses the same buffer for input/output already and the other two callers are easily converted todo so.

---
 block/qcow.c | 31 ++++++++++---------------------
 1 file changed, 10 insertions(+), 21 deletions(-)
block/qcow.c +10 -21
index 635085e..5a4f310 100644
@@ -293,12 +293,9 @@ static int qcow_set_key(BlockDriverState *bs, const char *key)
     return 0;
 }
 
-/* The crypt function is compatible with the linux cryptoloop
-   algorithm for < 4 GB images. NOTE: out_buf == in_buf is
-   supported */
 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                           uint8_t *out_buf, const uint8_t *in_buf,
-                           int nb_sectors, bool enc, Error **errp)
+                           uint8_t *buf, int nb_sectors, bool enc,
+                           Error **errp)
 {
     union {
         uint64_t ll[2];
@@ -317,14 +314,12 @@ static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
         }
         if (enc) {
             ret = qcrypto_cipher_encrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         } else {
             ret = qcrypto_cipher_decrypt(s->cipher,
-                                         in_buf,
-                                         out_buf,
+                                         buf, buf,
                                          512,
                                          errp);
         }
@@ -332,8 +327,7 @@ static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
             return -1;
         }
         sector_num++;
-        in_buf += 512;
-        out_buf += 512;
+        buf += 512;
     }
     return 0;
 }
@@ -453,13 +447,12 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                     uint64_t start_sect;
                     assert(s->cipher);
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
-                    memset(s->cluster_data + 512, 0x00, 512);
+                    memset(s->cluster_data, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {
                         if (i < n_start || i >= n_end) {
                             Error *err = NULL;
                             if (encrypt_sectors(s, start_sect + i,
-                                                s->cluster_data,
-                                                s->cluster_data + 512, 1,
+                                                s->cluster_data, 1,
                                                 true, &err) < 0) {
                                 error_free(err);
                                 errno = EIO;
@@ -637,7 +630,7 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
             }
             if (bs->encrypted) {
                 assert(s->cipher);
-                if (encrypt_sectors(s, sector_num, buf, buf,
+                if (encrypt_sectors(s, sector_num, buf,
                                     n, false, &err) < 0) {
                     goto fail;
                 }
@@ -672,7 +665,6 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
     BDRVQcowState *s = bs->opaque;
     int index_in_cluster;
     uint64_t cluster_offset;
-    const uint8_t *src_buf;
     int ret = 0, n;
     uint8_t *cluster_data = NULL;
     struct iovec hd_iov;
@@ -715,18 +707,15 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
             if (!cluster_data) {
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            if (encrypt_sectors(s, sector_num, cluster_data, buf,
+            if (encrypt_sectors(s, sector_num, buf,
                                 n, true, &err) < 0) {
                 error_free(err);
                 ret = -EIO;
                 break;
             }
-            src_buf = cluster_data;
-        } else {
-            src_buf = buf;
         }
 
-        hd_iov.iov_base = (void *)src_buf;
+        hd_iov.iov_base = (void *)buf;
         hd_iov.iov_len = n * 512;
         qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
         qemu_co_mutex_unlock(&s->lock);
Signature · 1 line
2.5.0
#56 lore raw

Re: [Qemu-devel] [PATCH v2 13/17] qcow: make encrypt_sectors encrypt in place

Quoted 5 lines · Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change encrypt_sectors() to assume use of a single buffer, encrypting in place. One current caller all uses the same buffer for input/output already and the other two callers are easily converted todo so.

s/todo/to do/

Quoted 8 lines
---
 block/qcow.c | 31 ++++++++++---------------------
 1 file changed, 10 insertions(+), 21 deletions(-)

block/qcow.c static uint64_t get_cluster_offset(BlockDriverState *bs, · line 451

Quoted 6 lines
block/qcow.c +1 -1
@@ -453,13 +447,12 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                     uint64_t start_sect;
                     assert(s->cipher);
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
-                    memset(s->cluster_data + 512, 0x00, 512);
+                    memset(s->cluster_data, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {

As long as you're touching near here, is it worth adding a space before '('?

Quoted 10 lines
block/qcow.c +0 -1
@@ -672,7 +665,6 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
     BDRVQcowState *s = bs->opaque;
     int index_in_cluster;
     uint64_t cluster_offset;
-    const uint8_t *src_buf;
     int ret = 0, n;
     uint8_t *cluster_data = NULL;
     struct iovec hd_iov;
@@ -715,18 +707,15 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
             if (!cluster_data) {

block/qcow.c static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num, · line 724

Quoted 10 lines
block/qcow.c +1 -2
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            if (encrypt_sectors(s, sector_num, cluster_data, buf,
+            if (encrypt_sectors(s, sector_num, buf,
                                 n, true, &err) < 0) {
                 error_free(err);
                 ret = -EIO;
                 break;
             }
-            src_buf = cluster_data;

cluster_data is now unused; you've got a wasted g_malloc0() here and g_free() later on.

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

Re: [Qemu-devel] [PATCH v2 13/17] qcow: make encrypt_sectors encrypt in place

Quoted 41 lines · Eric Blake
Quoted 5 lines · Daniel P. Berrange

Instead of requiring separate input/output buffers for encrypting data, change encrypt_sectors() to assume use of a single buffer, encrypting in place. One current caller all uses the same buffer for input/output already and the other two callers are easily converted todo so.

s/todo/to do/

Quoted 8 lines
---
 block/qcow.c | 31 ++++++++++---------------------
 1 file changed, 10 insertions(+), 21 deletions(-)

block/qcow.c static uint64_t get_cluster_offset(BlockDriverState *bs, · line 451

Quoted 6 lines
block/qcow.c +1 -1
@@ -453,13 +447,12 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                     uint64_t start_sect;
                     assert(s->cipher);
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
-                    memset(s->cluster_data + 512, 0x00, 512);
+                    memset(s->cluster_data, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {

As long as you're touching near here, is it worth adding a space before '('?

Quoted 15 lines
block/qcow.c +1 -2
@@ -672,7 +665,6 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
     BDRVQcowState *s = bs->opaque;
     int index_in_cluster;
     uint64_t cluster_offset;
-    const uint8_t *src_buf;
     int ret = 0, n;
     uint8_t *cluster_data = NULL;
     struct iovec hd_iov;
@@ -715,18 +707,15 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
             if (!cluster_data) {
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            if (encrypt_sectors(s, sector_num, cluster_data, buf,
+            if (encrypt_sectors(s, sector_num, buf,
                                 n, true, &err) < 0) {
Quoted 8 lines

block/qcow.c static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num, · line 724

Quoted 5 lines
block/qcow.c +0 -1
                 error_free(err);
                 ret = -EIO;
                 break;
             }
-            src_buf = cluster_data;

cluster_data is now unused; you've got a wasted g_malloc0() here and g_free() later on.

Oh, good point.

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 :|
#58 lore raw

PATCH v2 14/17 qcow: convert QCow to use QCryptoBlock for encryption

In reply to Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock APIs for encrypting image content. This is only wired up to permit use of the legacy QCow encryption format. Users who wish to have the strong LUKS format should switch to qcow2 instead.

With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.

  $QEMU \
    -object secret,id=sec0,filename=/home/berrange/encrypted.pw \
    -drive file=/home/berrange/encrypted.qcow,key-secret=sec0
---
 block/qcow.c         | 173 +++++++++++++++++++++++----------------------------
 qapi/block-core.json |  17 ++++-
 2 files changed, 93 insertions(+), 97 deletions(-)
block/qcow.c +77 -96
index 5a4f310..3b7c2b9 100644
@@ -26,7 +26,9 @@
 #include "qemu/module.h"
 #include <zlib.h>
 #include "qapi/qmp/qerror.h"
-#include "crypto/cipher.h"
+#include "crypto/block.h"
+#include "qapi/opts-visitor.h"
+#include "qapi-visit.h"
 #include "migration/migration.h"
 
 /**************************************************************/
@@ -40,6 +42,8 @@
 
 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
 
+#define QCOW_OPT_KEY_SECRET "key-secret"
+
 typedef struct QCowHeader {
     uint32_t magic;
     uint32_t version;
@@ -72,7 +76,7 @@ typedef struct BDRVQcowState {
     uint8_t *cluster_cache;
     uint8_t *cluster_data;
     uint64_t cluster_cache_offset;
-    QCryptoCipher *cipher; /* NULL if no key yet */
+    QCryptoBlock *crypto; /* Disk encryption format driver */
     uint32_t crypt_method_header;
     CoMutex lock;
     Error *migration_blocker;
@@ -92,6 +96,19 @@ static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
         return 0;
 }
 
+static QemuOptsList qcow_runtime_opts = {
+    .name = "qcow",
+    .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
+    .desc = {
+        {
+            .name = QCOW_OPT_KEY_SECRET,
+            .type = QEMU_OPT_STRING,
+            .help = "ID of the secret that provides the encryption key",
+        },
+        { /* end of list */ }
+    },
+};
+
 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
                      Error **errp)
 {
@@ -99,6 +116,11 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     unsigned int len, i, shift;
     int ret;
     QCowHeader header;
+    QemuOpts *opts = NULL;
+    Error *local_err = NULL;
+    QCryptoBlockOpenOptions *crypto_opts = NULL;
+    unsigned int cflags = 0;
+    OptsVisitor *ov;
 
     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
     if (ret < 0) {
@@ -147,19 +169,50 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         goto fail;
     }
 
-    if (header.crypt_method > QCOW_CRYPT_AES) {
-        error_setg(errp, "invalid encryption method in qcow header");
-        ret = -EINVAL;
-        goto fail;
-    }
-    if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
-        error_setg(errp, "AES cipher not available");
+    opts = qemu_opts_create(&qcow_runtime_opts, NULL, 0, &error_abort);
+    qemu_opts_absorb_qdict(opts, options, &local_err);
+    if (local_err) {
+        error_propagate(errp, local_err);
         ret = -EINVAL;
         goto fail;
     }
+
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
+        if (s->crypt_method_header == QCOW_CRYPT_AES) {
+            ov = opts_visitor_new(opts);
+
+            crypto_opts = g_new0(QCryptoBlockOpenOptions, 1);
+            crypto_opts->format = Q_CRYPTO_BLOCK_FORMAT_QCOW;
+            crypto_opts->u.qcow = g_new0(QCryptoBlockOptionsQCow, 1);
+            visit_type_QCryptoBlockOptionsQCow(opts_get_visitor(ov),
+                                               &crypto_opts->u.qcow,
+                                               "qcow", &local_err);
+            if (local_err) {
+                error_propagate(errp, local_err);
+                opts_visitor_cleanup(ov);
+                ret = -EINVAL;
+                goto fail;
+            }
+            opts_visitor_cleanup(ov);
+
+            if (flags & BDRV_O_NO_IO) {
+                cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
+            }
+            s->crypto = qcrypto_block_open(crypto_opts, NULL, NULL,
+                                           cflags, errp);
+            if (!s->crypto) {
+                error_setg(errp, "Could not setup encryption layer");
+                ret = -EINVAL;
+                goto fail;
+            }
+        } else {
+            error_setg(errp, "invalid encryption method in qcow header");
+            ret = -EINVAL;
+            goto fail;
+        }
         bs->encrypted = 1;
+        bs->valid_key = 1;
     }
     s->cluster_bits = header.cluster_bits;
     s->cluster_size = 1 << s->cluster_bits;
@@ -238,6 +291,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
                bdrv_get_device_or_node_name(bs));
     migrate_add_blocker(s->migration_blocker);
 
+    qapi_free_QCryptoBlockOpenOptions(crypto_opts);
     qemu_co_mutex_init(&s->lock);
     return 0;
 
@@ -246,6 +300,7 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
     qemu_vfree(s->l2_cache);
     g_free(s->cluster_cache);
     g_free(s->cluster_data);
+    qapi_free_QCryptoBlockOpenOptions(crypto_opts);
     return ret;
 }
 
@@ -258,79 +313,6 @@ static int qcow_reopen_prepare(BDRVReopenState *state,
     return 0;
 }
 
-static int qcow_set_key(BlockDriverState *bs, const char *key)
-{
-    BDRVQcowState *s = bs->opaque;
-    uint8_t keybuf[16];
-    int len, i;
-    Error *err;
-
-    memset(keybuf, 0, 16);
-    len = strlen(key);
-    if (len > 16)
-        len = 16;
-    /* XXX: we could compress the chars to 7 bits to increase
-       entropy */
-    for(i = 0;i < len;i++) {
-        keybuf[i] = key[i];
-    }
-    assert(bs->encrypted);
-
-    qcrypto_cipher_free(s->cipher);
-    s->cipher = qcrypto_cipher_new(
-        QCRYPTO_CIPHER_ALG_AES_128,
-        QCRYPTO_CIPHER_MODE_CBC,
-        keybuf, G_N_ELEMENTS(keybuf),
-        &err);
-
-    if (!s->cipher) {
-        /* XXX would be nice if errors in this method could
-         * be properly propagate to the caller. Would need
-         * the bdrv_set_key() API signature to be fixed. */
-        error_free(err);
-        return -1;
-    }
-    return 0;
-}
-
-static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                           uint8_t *buf, int nb_sectors, bool enc,
-                           Error **errp)
-{
-    union {
-        uint64_t ll[2];
-        uint8_t b[16];
-    } ivec;
-    int i;
-    int ret;
-
-    for(i = 0; i < nb_sectors; i++) {
-        ivec.ll[0] = cpu_to_le64(sector_num);
-        ivec.ll[1] = 0;
-        if (qcrypto_cipher_setiv(s->cipher,
-                                 ivec.b, G_N_ELEMENTS(ivec.b),
-                                 errp) < 0) {
-            return -1;
-        }
-        if (enc) {
-            ret = qcrypto_cipher_encrypt(s->cipher,
-                                         buf, buf,
-                                         512,
-                                         errp);
-        } else {
-            ret = qcrypto_cipher_decrypt(s->cipher,
-                                         buf, buf,
-                                         512,
-                                         errp);
-        }
-        if (ret < 0) {
-            return -1;
-        }
-        sector_num++;
-        buf += 512;
-    }
-    return 0;
-}
 
 /* 'allocate' is:
  *
@@ -445,15 +427,15 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                 if (bs->encrypted &&
                     (n_end - n_start) < s->cluster_sectors) {
                     uint64_t start_sect;
-                    assert(s->cipher);
+                    assert(s->crypto);
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
                     memset(s->cluster_data, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {
                         if (i < n_start || i >= n_end) {
                             Error *err = NULL;
-                            if (encrypt_sectors(s, start_sect + i,
-                                                s->cluster_data, 1,
-                                                true, &err) < 0) {
+                            if (qcrypto_block_encrypt(s->crypto, start_sect + i,
+                                                      s->cluster_data, 1,
+                                                      &err) < 0) {
                                 error_free(err);
                                 errno = EIO;
                                 return -1;
@@ -498,7 +480,7 @@ static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
     if (!cluster_offset) {
         return 0;
     }
-    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
+    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
         return BDRV_BLOCK_DATA;
     }
     cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
@@ -629,9 +611,9 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
                 break;
             }
             if (bs->encrypted) {
-                assert(s->cipher);
-                if (encrypt_sectors(s, sector_num, buf,
-                                    n, false, &err) < 0) {
+                assert(s->crypto);
+                if (qcrypto_block_decrypt(s->crypto, sector_num, buf,
+                                          n, &err) < 0) {
                     goto fail;
                 }
             }
@@ -703,12 +685,12 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
         }
         if (bs->encrypted) {
             Error *err = NULL;
-            assert(s->cipher);
+            assert(s->crypto);
             if (!cluster_data) {
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            if (encrypt_sectors(s, sector_num, buf,
-                                n, true, &err) < 0) {
+            if (qcrypto_block_encrypt(s->crypto, sector_num, buf,
+                                      n, &err) < 0) {
                 error_free(err);
                 ret = -EIO;
                 break;
@@ -746,8 +728,8 @@ static void qcow_close(BlockDriverState *bs)
 {
     BDRVQcowState *s = bs->opaque;
 
-    qcrypto_cipher_free(s->cipher);
-    s->cipher = NULL;
+    qcrypto_block_free(s->crypto);
+    s->crypto = NULL;
     g_free(s->l1_table);
     qemu_vfree(s->l2_cache);
     g_free(s->cluster_cache);
@@ -1012,7 +994,6 @@ static BlockDriver bdrv_qcow = {
     .bdrv_co_writev         = qcow_co_writev,
     .bdrv_co_get_block_status   = qcow_co_get_block_status,
 
-    .bdrv_set_key           = qcow_set_key,
     .bdrv_make_empty        = qcow_make_empty,
     .bdrv_write_compressed  = qcow_write_compressed,
     .bdrv_get_info          = qcow_get_info,
qapi/block-core.json +16 -1
index b704dd7..e0d423f 100644
@@ -1756,6 +1756,21 @@
             'mode':  'Qcow2OverlapCheckMode' } }
 
 ##
+# @BlockdevOptionsQcow
+#
+# Driver specific block device options for qcow.
+#
+# @key-secret:   #optional ID of the "secret" object providing the
+#                AES decryption key.
+#
+# Since: 2.6
+##
+{ 'struct': 'BlockdevOptionsQcow',
+  'base': 'BlockdevOptionsGenericCOWFormat',
+  'data': { '*key-secret': 'str' } }
+
+
+##
 # @BlockdevOptionsQcow2
 #
 # Driver specific block device options for qcow2.
@@ -2024,7 +2039,7 @@
       'null-co':    'BlockdevOptionsNull',
       'parallels':  'BlockdevOptionsGenericFormat',
       'qcow2':      'BlockdevOptionsQcow2',
-      'qcow':       'BlockdevOptionsGenericCOWFormat',
+      'qcow':       'BlockdevOptionsQcow',
       'qed':        'BlockdevOptionsGenericCOWFormat',
       'quorum':     'BlockdevOptionsQuorum',
       'raw':        'BlockdevOptionsGenericFormat',
Signature · 1 line
2.5.0
Reviewed-by on v2 14/17
#59 lore raw

Re: [Qemu-devel] [PATCH v2 14/17] qcow: convert QCow to use QCryptoBlock for encryption

Quoted 1 line · Daniel P. Berrange

This converts the qcow2 driver to make use of the QCryptoBlock

s/qcow2/qcow/

Quoted 22 lines

APIs for encrypting image content. This is only wired up to permit use of the legacy QCow encryption format. Users who wish to have the strong LUKS format should switch to qcow2 instead.

With this change it is now required to use the QCryptoSecret object for providing passwords, instead of the current block password APIs / interactive prompting.

  $QEMU \
    -object secret,id=sec0,filename=/home/berrange/encrypted.pw \
    -drive file=/home/berrange/encrypted.qcow,key-secret=sec0
---
 block/qcow.c         | 173 +++++++++++++++++++++++----------------------------
 qapi/block-core.json |  17 ++++-
 2 files changed, 93 insertions(+), 97 deletions(-)

+++ b/qapi/block-core.json

qapi/block-core.json line 1764

Quoted 9 lines
qapi/block-core.json +6 -0
@@ -1756,6 +1756,21 @@
             'mode':  'Qcow2OverlapCheckMode' } }
 
 ##
+# @BlockdevOptionsQcow
+#
+# Driver specific block device options for qcow.
+#
+# @key-secret:   #optional ID of the "secret" object providing the
+#                AES decryption key.

Maybe worth a mention that this is supported for decrypting old images, but not for use in creating new images (but then again, who creates new qcow images these days).

With the commit typo fixed,

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

PATCH v2 15/17 block: rip out all traces of password prompting

In reply to Daniel P. Berrange

Now that qcow & qcow2 are wired up to get encryption keys via the QCryptoSecret object, nothing is relying on the interactive prompting for passwords. All the code related to password prompting can thus be ripped out.

---
 hmp.c                        | 31 --------------------
 hw/usb/dev-storage.c         | 34 ----------------------
 include/monitor/monitor.h    |  7 -----
 include/qemu/osdep.h         |  2 --
 monitor.c                    | 68 --------------------------------------------
 qemu-img.c                   | 15 ----------
 qemu-io.c                    | 21 --------------
 qmp.c                        |  9 ------
 tests/qemu-iotests/087       |  2 ++
 tests/qemu-iotests/087.out   |  4 +--
 tests/qemu-iotests/common.rc |  4 +--
 util/oslib-posix.c           | 66 ------------------------------------------
 util/oslib-win32.c           | 24 ----------------
 13 files changed, 6 insertions(+), 281 deletions(-)
hmp.c +0 -31
index 95930b0..bfd42d0 100644
@@ -966,37 +966,12 @@ void hmp_ringbuf_read(Monitor *mon, const QDict *qdict)
     g_free(data);
 }
 
-static void hmp_cont_cb(void *opaque, int err)
-{
-    if (!err) {
-        qmp_cont(NULL);
-    }
-}
-
-static bool key_is_missing(const BlockInfo *bdev)
-{
-    return (bdev->inserted && bdev->inserted->encryption_key_missing);
-}
-
 void hmp_cont(Monitor *mon, const QDict *qdict)
 {
-    BlockInfoList *bdev_list, *bdev;
     Error *err = NULL;
 
-    bdev_list = qmp_query_block(NULL);
-    for (bdev = bdev_list; bdev; bdev = bdev->next) {
-        if (key_is_missing(bdev->value)) {
-            monitor_read_block_device_key(mon, bdev->value->device,
-                                          hmp_cont_cb, NULL);
-            goto out;
-        }
-    }
-
     qmp_cont(&err);
     hmp_handle_error(mon, &err);
-
-out:
-    qapi_free_BlockInfoList(bdev_list);
 }
 
 void hmp_system_wakeup(Monitor *mon, const QDict *qdict)
@@ -1377,12 +1352,6 @@ void hmp_change(Monitor *mon, const QDict *qdict)
 
         qmp_blockdev_change_medium(device, target, !!arg, arg,
                                    !!read_only, read_only_mode, &err);
-        if (err &&
-            error_get_class(err) == ERROR_CLASS_DEVICE_ENCRYPTED) {
-            error_free(err);
-            monitor_read_block_device_key(mon, device, NULL, NULL);
-            return;
-        }
     }
 
     hmp_handle_error(mon, &err);
hw/usb/dev-storage.c +0 -34
index 597d8fd..2122f4f 100644
@@ -553,21 +553,6 @@ static void usb_msd_handle_data(USBDevice *dev, USBPacket *p)
     }
 }
 
-static void usb_msd_password_cb(void *opaque, int err)
-{
-    MSDState *s = opaque;
-    Error *local_err = NULL;
-
-    if (!err) {
-        usb_device_attach(&s->dev, &local_err);
-    }
-
-    if (local_err) {
-        error_report_err(local_err);
-        qdev_unplug(&s->dev.qdev, NULL);
-    }
-}
-
 static void *usb_msd_load_request(QEMUFile *f, SCSIRequest *req)
 {
     MSDState *s = DO_UPCAST(MSDState, dev.qdev, req->bus->qbus.parent);
@@ -613,25 +598,6 @@ static void usb_msd_realize_storage(USBDevice *dev, Error **errp)
         return;
     }
 
-    if (blk_bs(blk)) {
-        bdrv_add_key(blk_bs(blk), NULL, &err);
-        if (err) {
-            if (monitor_cur_is_qmp()) {
-                error_propagate(errp, err);
-                return;
-            }
-            error_free(err);
-            err = NULL;
-            if (cur_mon) {
-                monitor_read_bdrv_key_start(cur_mon, blk_bs(blk),
-                                            usb_msd_password_cb, s);
-                s->dev.auto_attach = 0;
-            } else {
-                autostart = 0;
-            }
-        }
-    }
-
     blkconf_serial(&s->conf, &dev->serial);
     blkconf_blocksizes(&s->conf);
 
include/monitor/monitor.h +0 -7
index aa0f373..cd38020 100644
@@ -21,13 +21,6 @@ void monitor_init(CharDriverState *chr, int flags);
 int monitor_suspend(Monitor *mon);
 void monitor_resume(Monitor *mon);
 
-int monitor_read_bdrv_key_start(Monitor *mon, BlockDriverState *bs,
-                                BlockCompletionFunc *completion_cb,
-                                void *opaque);
-int monitor_read_block_device_key(Monitor *mon, const char *device,
-                                  BlockCompletionFunc *completion_cb,
-                                  void *opaque);
-
 int monitor_get_fd(Monitor *mon, const char *fdname, Error **errp);
 int monitor_fd_param(Monitor *mon, const char *fdname, Error **errp);
 
include/qemu/osdep.h +0 -2
index 59a7f8d..3420ac6 100644
@@ -301,8 +301,6 @@ void qemu_set_tty_echo(int fd, bool echo);
 
 void os_mem_prealloc(int fd, char *area, size_t sz);
 
-int qemu_read_password(char *buf, int buf_size);
-
 /**
  * qemu_fork:
  *
monitor.c +0 -68

74 lines not on this page · raw message

qemu-img.c +0 -15
index faf4dbd..e99c000 100644
@@ -270,8 +270,6 @@ static BlockBackend *img_open_file(const char *id, const char *filename,
                                    bool quiet)
 {
     BlockBackend *blk;
-    BlockDriverState *bs;
-    char password[256];
     Error *local_err = NULL;
     QDict *options = NULL;
 
@@ -286,19 +284,6 @@ static BlockBackend *img_open_file(const char *id, const char *filename,
         goto fail;
     }
 
-    bs = blk_bs(blk);
-    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");
-            goto fail;
-        }
-        if (bdrv_set_key(bs, password) < 0) {
-            error_report("invalid password");
-            goto fail;
-        }
-    }
     return blk;
 fail:
     blk_unref(blk);
qemu-io.c +0 -21
index 98b5cc2..6ae59f0 100644
@@ -56,7 +56,6 @@ static const cmdinfo_t close_cmd = {
 static int openfile(char *name, int flags, QDict *opts)
 {
     Error *local_err = NULL;
-    BlockDriverState *bs;
 
     if (qemuio_blk) {
         error_report("file open already, try 'help close'");
@@ -71,27 +70,7 @@ static int openfile(char *name, int flags, QDict *opts)
         return 1;
     }
 
-    bs = blk_bs(qemuio_blk);
-    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) {
-            error_report("No password given");
-            goto error;
-        }
-        if (bdrv_set_key(bs, password) < 0) {
-            error_report("invalid password");
-            goto error;
-        }
-    }
-
-
     return 0;
-
- error:
-    blk_unref(qemuio_blk);
-    qemuio_blk = NULL;
-    return 1;
 }
 
 static void open_help(void)
qmp.c +0 -9
index c5d9be7..effc5b8 100644
@@ -170,9 +170,7 @@ SpiceInfo *qmp_query_spice(Error **errp)
 
 void qmp_cont(Error **errp)
 {
-    Error *local_err = NULL;
     BlockBackend *blk;
-    BlockDriverState *bs;
 
     if (runstate_needs_reset()) {
         error_setg(errp, "Resetting the Virtual Machine is required");
@@ -184,13 +182,6 @@ void qmp_cont(Error **errp)
     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
         blk_iostatus_reset(blk);
     }
-    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
-        bdrv_add_key(bs, NULL, &local_err);
-        if (local_err) {
-            error_propagate(errp, local_err);
-            return;
-        }
-    }
 
     if (runstate_check(RUN_STATE_INMIGRATE)) {
         autostart = 1;
tests/qemu-iotests/087 +2 -0
index 3386668..065d9af 100755
@@ -201,6 +201,7 @@ run_qemu -S <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
@@ -228,6 +229,7 @@ run_qemu <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
tests/qemu-iotests/087.out +2 -2
index 5fc4823..6582dda 100644
@@ -49,7 +49,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
@@ -60,7 +60,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
tests/qemu-iotests/common.rc +2 -2
index d9913f8..da78459 100644
@@ -135,9 +135,9 @@ _make_test_img()
     # XXX(hch): have global image options?
     (
      if [ $use_backing = 1 ]; then
-        $QEMU_IMG create -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
      else
-        $QEMU_IMG create -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
      fi
     ) | _filter_img_create
 
util/oslib-posix.c +0 -66

72 lines not on this page · raw message

util/oslib-win32.c +0 -24
index 6a47019..6ccc952 100644
@@ -474,30 +474,6 @@ void os_mem_prealloc(int fd, char *area, size_t memory)
 }
 
 
-/* XXX: put correct support for win32 */
-int qemu_read_password(char *buf, int buf_size)
-{
-    int c, i;
-
-    printf("Password: ");
-    fflush(stdout);
-    i = 0;
-    for (;;) {
-        c = getchar();
-        if (c < 0) {
-            buf[i] = '\0';
-            return -1;
-        } else if (c == '\n') {
-            break;
-        } else if (i < (buf_size - 1)) {
-            buf[i++] = c;
-        }
-    }
-    buf[i] = '\0';
-    return 0;
-}
-
-
 pid_t qemu_fork(Error **errp)
 {
     errno = ENOSYS;
Signature · 1 line
2.5.0
#61 lore raw

Re: [Qemu-devel] [PATCH v2 15/17] block: rip out all traces of password prompting

Quoted 48 lines · Daniel P. Berrange
tests/qemu-iotests/087 +2 -0
index 3386668..065d9af 100755
@@ -201,6 +201,7 @@ run_qemu -S <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
@@ -228,6 +229,7 @@ run_qemu <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
tests/qemu-iotests/087.out +2 -2
index 5fc4823..6582dda 100644
@@ -49,7 +49,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
@@ -60,7 +60,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
tests/qemu-iotests/common.rc +0 -0
index d9913f8..da78459 100644
@@ -135,9 +135,9 @@ _make_test_img()
     # XXX(hch): have global image options?

tests/qemu-iotests/common.rc _make_test_img() · line 143

Quoted 10 lines
tests/qemu-iotests/common.rc +2 -2
     (
      if [ $use_backing = 1 ]; then
-        $QEMU_IMG create -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
      else
-        $QEMU_IMG create -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
      fi
     ) | _filter_img_create
 

Does this change belong to a separate patch?

Fam

#62 lore raw

Re: [Qemu-devel] [PATCH v2 15/17] block: rip out all traces of password prompting

Quoted 53 lines · Fam Zheng
Quoted 52 lines · Daniel P. Berrange
tests/qemu-iotests/087 +2 -0
index 3386668..065d9af 100755
@@ -201,6 +201,7 @@ run_qemu -S <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
@@ -228,6 +229,7 @@ run_qemu <<EOF
       "options": {
         "driver": "$IMGFMT",
         "id": "disk",
+        "key-secret": "sec0",
         "file": {
             "driver": "file",
             "filename": "$TEST_IMG"
tests/qemu-iotests/087.out +2 -2
index 5fc4823..6582dda 100644
@@ -49,7 +49,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
@@ -60,7 +60,7 @@ QMP_VERSION
 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"}}
+{"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
 
tests/qemu-iotests/common.rc +1 -1
index d9913f8..da78459 100644
@@ -135,9 +135,9 @@ _make_test_img()
     # XXX(hch): have global image options?
     (
      if [ $use_backing = 1 ]; then
-        $QEMU_IMG create -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options -b "$backing_file" "$img_name" $image_size 2>&1
Quoted 8 lines

tests/qemu-iotests/common.rc _make_test_img() · line 143

Quoted 6 lines
tests/qemu-iotests/common.rc +1 -1
      else
-        $QEMU_IMG create -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
+        $QEMU_IMG create $EXTRA_IMG_ARGS -f $IMGFMT $extra_img_options "$img_name" $image_size 2>&1
      fi
     ) | _filter_img_create
 

Does this change belong to a separate patch?

Opps, no. This change to common.rc should be deleted - it was something I added which turned out to not be needed

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 :|
#63 lore raw

PATCH v2 16/17 block: remove all encryption handling APIs

In reply to Daniel P. Berrange

Now that all encryption keys must be provided upfront via the QCryptoSecret API and associated block driver properties there is no need for any explicit encryption handling APIs in the block layer. Encryption can be handled transparently within the block driver. We only retain an API for querying whether an image is encrypted or not, since that is a potentially useful piece of metadata to report to the user.

---
 block.c                   | 82 ++---------------------------------------------
 block/crypto.c            |  1 -
 block/qapi.c              |  2 +-
 block/qcow.c              |  1 -
 block/qcow2.c             |  1 -
 blockdev.c                | 40 ++---------------------
 include/block/block.h     |  4 ---
 include/block/block_int.h |  1 -
 8 files changed, 5 insertions(+), 127 deletions(-)
block.c +2 -80
index 0806d4f..5403355 100644
@@ -1693,17 +1693,8 @@ static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
         goto close_and_fail;
     }
 
-    if (!bdrv_key_required(bs)) {
-        if (bs->blk) {
-            blk_dev_change_media_cb(bs->blk, true);
-        }
-    } else if (!runstate_check(RUN_STATE_PRELAUNCH)
-               && !runstate_check(RUN_STATE_INMIGRATE)
-               && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
-        error_setg(errp,
-                   "Guest must be stopped for opening of encrypted image");
-        ret = -EBUSY;
-        goto close_and_fail;
+    if (bs->blk) {
+        blk_dev_change_media_cb(bs->blk, true);
     }
 
     QDECREF(options);
@@ -2190,7 +2181,6 @@ void bdrv_close(BlockDriverState *bs)
         bs->backing_format[0] = '\0';
         bs->total_sectors = 0;
         bs->encrypted = 0;
-        bs->valid_key = 0;
         bs->sg = 0;
         bs->zero_beyond_eof = false;
         QDECREF(bs->options);
@@ -2774,74 +2764,6 @@ int bdrv_is_encrypted(BlockDriverState *bs)
     return bs->encrypted;
 }
 
-int bdrv_key_required(BlockDriverState *bs)
-{
-    BdrvChild *backing = bs->backing;
-
-    if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
-        return 1;
-    }
-    return (bs->encrypted && !bs->valid_key);
-}
-
-int bdrv_set_key(BlockDriverState *bs, const char *key)
-{
-    int ret;
-    if (bs->backing && bs->backing->bs->encrypted) {
-        ret = bdrv_set_key(bs->backing->bs, key);
-        if (ret < 0)
-            return ret;
-        if (!bs->encrypted)
-            return 0;
-    }
-    if (!bs->encrypted) {
-        return -EINVAL;
-    } else if (!bs->drv || !bs->drv->bdrv_set_key) {
-        return -ENOMEDIUM;
-    }
-    ret = bs->drv->bdrv_set_key(bs, key);
-    if (ret < 0) {
-        bs->valid_key = 0;
-    } else if (!bs->valid_key) {
-        bs->valid_key = 1;
-        if (bs->blk) {
-            /* call the change callback now, we skipped it on open */
-            blk_dev_change_media_cb(bs->blk, true);
-        }
-    }
-    return ret;
-}
-
-/*
- * Provide an encryption key for @bs.
- * If @key is non-null:
- *     If @bs is not encrypted, fail.
- *     Else if the key is invalid, fail.
- *     Else set @bs's key to @key, replacing the existing key, if any.
- * If @key is null:
- *     If @bs is encrypted and still lacks a key, fail.
- *     Else do nothing.
- * On failure, store an error object through @errp if non-null.
- */
-void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
-{
-    if (key) {
-        if (!bdrv_is_encrypted(bs)) {
-            error_setg(errp, "Node '%s' is not encrypted",
-                      bdrv_get_device_or_node_name(bs));
-        } else if (bdrv_set_key(bs, key) < 0) {
-            error_setg(errp, QERR_INVALID_PASSWORD);
-        }
-    } else {
-        if (bdrv_key_required(bs)) {
-            error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
-                      "'%s' (%s) is encrypted",
-                      bdrv_get_device_or_node_name(bs),
-                      bdrv_get_encrypted_filename(bs));
-        }
-    }
-}
-
 const char *bdrv_get_format_name(BlockDriverState *bs)
 {
     return bs->drv ? bs->drv->format_name : NULL;
block/crypto.c +0 -1
index 2ba78bd..03194e5 100644
@@ -278,7 +278,6 @@ static int block_crypto_open_generic(QCryptoBlockFormat format,
     }
 
     bs->encrypted = 1;
-    bs->valid_key = 1;
 
     qemu_co_mutex_init(&crypto->lock);
 
block/qapi.c +1 -1
index 58d3975..639b231 100644
@@ -42,7 +42,7 @@ BlockDeviceInfo *bdrv_block_device_info(BlockDriverState *bs, Error **errp)
     info->ro                     = bs->read_only;
     info->drv                    = g_strdup(bs->drv->format_name);
     info->encrypted              = bs->encrypted;
-    info->encryption_key_missing = bdrv_key_required(bs);
+    info->encryption_key_missing = false;
 
     info->cache = g_new(BlockdevCacheInfo, 1);
     *info->cache = (BlockdevCacheInfo) {
block/qcow.c +0 -1
index 3b7c2b9..2fc7c3c 100644
@@ -212,7 +212,6 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
             goto fail;
         }
         bs->encrypted = 1;
-        bs->valid_key = 1;
     }
     s->cluster_bits = header.cluster_bits;
     s->cluster_size = 1 << s->cluster_bits;
block/qcow2.c +0 -1
index 5249ca2..1fbae85 100644
@@ -1210,7 +1210,6 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
         bs->encrypted = 1;
-        bs->valid_key = 1;
     }
 
     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
blockdev.c +2 -38
index 1392fff..d3c3317 100644
@@ -623,10 +623,6 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
             bdrv_set_io_limits(bs, &cfg);
         }
 
-        if (bdrv_key_required(bs)) {
-            autostart = 0;
-        }
-
         block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
 
         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
@@ -2261,24 +2257,8 @@ void qmp_block_passwd(bool has_device, const char *device,
                       bool has_node_name, const char *node_name,
                       const char *password, Error **errp)
 {
-    Error *local_err = NULL;
-    BlockDriverState *bs;
-    AioContext *aio_context;
-
-    bs = bdrv_lookup_bs(has_device ? device : NULL,
-                        has_node_name ? node_name : NULL,
-                        &local_err);
-    if (local_err) {
-        error_propagate(errp, local_err);
-        return;
-    }
-
-    aio_context = bdrv_get_aio_context(bs);
-    aio_context_acquire(aio_context);
-
-    bdrv_add_key(bs, password, errp);
-
-    aio_context_release(aio_context);
+    error_setg_errno(errp, -ENOSYS,
+                     "Setting block passwords directly is no longer supported");
 }
 
 void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
@@ -2505,12 +2485,6 @@ void qmp_blockdev_change_medium(const char *device, const char *filename,
 
     blk_apply_root_state(blk, medium_bs);
 
-    bdrv_add_key(medium_bs, NULL, &err);
-    if (err) {
-        error_propagate(errp, err);
-        goto fail;
-    }
-
     qmp_blockdev_open_tray(device, false, false, &err);
     if (err) {
         error_propagate(errp, err);
@@ -3849,16 +3823,6 @@ void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
         }
     }
 
-    if (bs && bdrv_key_required(bs)) {
-        if (blk) {
-            blk_unref(blk);
-        } else {
-            bdrv_unref(bs);
-        }
-        error_setg(errp, "blockdev-add doesn't support encrypted devices");
-        goto fail;
-    }
-
 fail:
     qmp_output_visitor_cleanup(ov);
 }
include/block/block.h +0 -4
index 73ffbd5..379a24c 100644
@@ -414,10 +414,6 @@ bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base);
 BlockDriverState *bdrv_next_node(BlockDriverState *bs);
 BlockDriverState *bdrv_next(BlockDriverState *bs);
 int bdrv_is_encrypted(BlockDriverState *bs);
-int bdrv_key_required(BlockDriverState *bs);
-int bdrv_set_key(BlockDriverState *bs, const char *key);
-void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp);
-int bdrv_query_missing_keys(void);
 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
                          void *opaque);
 const char *bdrv_get_node_name(const BlockDriverState *bs);
include/block/block_int.h +0 -1
index 256609d..191ce83 100644
@@ -374,7 +374,6 @@ struct BlockDriverState {
     int read_only; /* if true, the media is read only */
     int open_flags; /* flags used to open the file, re-used for re-open */
     int encrypted; /* if true, the media is encrypted */
-    int valid_key; /* if true, a valid encryption key has been set */
     int sg;        /* if true, the device is a /dev/sg* */
     int copy_on_read; /* if true, copy read backing sectors into image
                          note this is a reference count */
Signature · 1 line
2.5.0
#64 lore raw

Re: [Qemu-devel] [PATCH v2 16/17] block: remove all encryption handling APIs

Quoted 12 lines · Daniel P. Berrange

Now that all encryption keys must be provided upfront via the QCryptoSecret API and associated block driver properties there is no need for any explicit encryption handling APIs in the block layer. Encryption can be handled transparently within the block driver. We only retain an API for querying whether an image is encrypted or not, since that is a potentially useful piece of metadata to report to the user.

---

block.c void bdrv_close(BlockDriverState *bs) · line 2193

Quoted 4 lines
block.c +0 -1
@@ -2190,7 +2181,6 @@ void bdrv_close(BlockDriverState *bs)
         bs->backing_format[0] = '\0';
         bs->total_sectors = 0;
         bs->encrypted = 0;
-        bs->valid_key = 0;

It would be nice if this patch (or maybe a followup) switched bs->encrypted to bool, rather than int.

block.c int bdrv_is_encrypted(BlockDriverState *bs) · line 2833

Quoted 8 lines
block.c +0 -8
-void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
-{
-    if (key) {
-        if (!bdrv_is_encrypted(bs)) {
-            error_setg(errp, "Node '%s' is not encrypted",
-                      bdrv_get_device_or_node_name(bs));
-        } else if (bdrv_set_key(bs, key) < 0) {
-            error_setg(errp, QERR_INVALID_PASSWORD);

If I'm not mistaken, this was the only use of QERR_INVALID_PASSWORD; please also nuke it from include/qapi/qmp/qerror.h.

block.c int bdrv_is_encrypted(BlockDriverState *bs) · line 2838

Quoted 5 lines
block.c +0 -5
-        }
-    } else {
-        if (bdrv_key_required(bs)) {
-            error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
-                      "'%s' (%s) is encrypted",

Likewise, this looks like the last use of ERROR_CLASS_DEVICE_ENCRYPTED (since 15/17 nuked the only client in hmp.c that cared about the error class); it would be nice to nuke the remains in include/qapi/error.h and in qapi/common.json.

Quoted 15 lines

+++ b/blockdev.c

blockdev.c +0 -10
@@ -2261,24 +2257,8 @@ void qmp_block_passwd(bool has_device, const char *device,
                       bool has_node_name, const char *node_name,
                       const char *password, Error **errp)
 {
-    Error *local_err = NULL;
-    BlockDriverState *bs;
-    AioContext *aio_context;
-
-    bs = bdrv_lookup_bs(has_device ? device : NULL,
-                        has_node_name ? node_name : NULL,
-                        &local_err);
-    if (local_err) {
-        error_propagate(errp, local_err);
-        return;

blockdev.c void qmp_block_passwd(bool has_device, const char *device, · line 2261

Quoted 10 lines
blockdev.c +2 -8
-    }
-
-    aio_context = bdrv_get_aio_context(bs);
-    aio_context_acquire(aio_context);
-
-    bdrv_add_key(bs, password, errp);
-
-    aio_context_release(aio_context);
+    error_setg_errno(errp, -ENOSYS,
+                     "Setting block passwords directly is no longer supported");

We should document in qapi/block-core.json that the QMP 'block_passwd' command is deprecated, and will be removed in a future release (but I suspect we don't want to completely remove it in 2.6, so that we at least have time to find clients that were relying on it and should be using the new methods).

include/block/block_int.h struct BlockDriverState { · line 379

Quoted 9 lines
include/block/block_int.h +1 -1
+++ b/include/block/block_int.h
@@ -374,7 +374,6 @@ struct BlockDriverState {
     int read_only; /* if true, the media is read only */
     int open_flags; /* flags used to open the file, re-used for re-open */
     int encrypted; /* if true, the media is encrypted */
-    int valid_key; /* if true, a valid encryption key has been set */
     int sg;        /* if true, the device is a /dev/sg* */
     int copy_on_read; /* if true, copy read backing sectors into image
                          note this is a reference count */

Hmm - several variables that are only 'true' or 'false' and should be typed 'bool'. Only 'encrypted' is a candidate for change in this patch; 'sg' is unrelated. And 'copy_on_read' should be tweaked to document 'nonzero', not 'true', since it is used as a reference count rather than bool.

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

Re: [Qemu-devel] [PATCH v2 16/17] block: remove all encryption handling APIs

Quoted 12 lines · Eric Blake
Quoted 10 lines · Daniel P. Berrange

Now that all encryption keys must be provided upfront via the QCryptoSecret API and associated block driver properties there is no need for any explicit encryption handling APIs in the block layer. Encryption can be handled transparently within the block driver. We only retain an API for querying whether an image is encrypted or not, since that is a potentially useful piece of metadata to report to the user.

---

Quoted 8 lines

block.c void bdrv_close(BlockDriverState *bs) · line 2193

Quoted 5 lines
block.c +0 -1
@@ -2190,7 +2181,6 @@ void bdrv_close(BlockDriverState *bs)
         bs->backing_format[0] = '\0';
         bs->total_sectors = 0;
         bs->encrypted = 0;
-        bs->valid_key = 0;

It would be nice if this patch (or maybe a followup) switched bs->encrypted to bool, rather than int.

I'll prefer todo it later to avoid mixing unrelated changes.

Quoted 18 lines

block.c int bdrv_is_encrypted(BlockDriverState *bs) · line 2833

Quoted 8 lines
block.c +0 -8
-void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
-{
-    if (key) {
-        if (!bdrv_is_encrypted(bs)) {
-            error_setg(errp, "Node '%s' is not encrypted",
-                      bdrv_get_device_or_node_name(bs));
-        } else if (bdrv_set_key(bs, key) < 0) {
-            error_setg(errp, QERR_INVALID_PASSWORD);

If I'm not mistaken, this was the only use of QERR_INVALID_PASSWORD; please also nuke it from include/qapi/qmp/qerror.h.

block.c int bdrv_is_encrypted(BlockDriverState *bs) · line 2838

Quoted 5 lines
block.c +0 -5
-        }
-    } else {
-        if (bdrv_key_required(bs)) {
-            error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
-                      "'%s' (%s) is encrypted",
Quoted 4 lines

Likewise, this looks like the last use of ERROR_CLASS_DEVICE_ENCRYPTED (since 15/17 nuked the only client in hmp.c that cared about the error class); it would be nice to nuke the remains in include/qapi/error.h and in qapi/common.json.

Oh yes, goo points.

Quoted 23 lines
Quoted 23 lines

+++ b/blockdev.c

blockdev.c +0 -18
@@ -2261,24 +2257,8 @@ void qmp_block_passwd(bool has_device, const char *device,
                       bool has_node_name, const char *node_name,
                       const char *password, Error **errp)
 {
-    Error *local_err = NULL;
-    BlockDriverState *bs;
-    AioContext *aio_context;
-
-    bs = bdrv_lookup_bs(has_device ? device : NULL,
-                        has_node_name ? node_name : NULL,
-                        &local_err);
-    if (local_err) {
-        error_propagate(errp, local_err);
-        return;
-    }
-
-    aio_context = bdrv_get_aio_context(bs);
-    aio_context_acquire(aio_context);
-
-    bdrv_add_key(bs, password, errp);
-
-    aio_context_release(aio_context);
Quoted 8 lines

blockdev.c void qmp_block_passwd(bool has_device, const char *device, · line 2261

Quoted 2 lines
blockdev.c +2 -0
+    error_setg_errno(errp, -ENOSYS,
+                     "Setting block passwords directly is no longer supported");

We should document in qapi/block-core.json that the QMP 'block_passwd' command is deprecated, and will be removed in a future release (but I suspect we don't want to completely remove it in 2.6, so that we at least have time to find clients that were relying on it and should be using the new methods).

I thought that I had mentioned that already, but will do so if its not already there.

Quoted 7 lines
Quoted 7 lines
include/block/block_int.h +1 -1
+++ b/include/block/block_int.h
@@ -374,7 +374,6 @@ struct BlockDriverState {
     int read_only; /* if true, the media is read only */
     int open_flags; /* flags used to open the file, re-used for re-open */
     int encrypted; /* if true, the media is encrypted */
-    int valid_key; /* if true, a valid encryption key has been set */
     int sg;        /* if true, the device is a /dev/sg* */
Quoted 8 lines

include/block/block_int.h struct BlockDriverState { · line 379

Quoted 2 lines
include/block/block_int.h +0 -0
     int copy_on_read; /* if true, copy read backing sectors into image
                          note this is a reference count */

Hmm - several variables that are only 'true' or 'false' and should be typed 'bool'. Only 'encrypted' is a candidate for change in this patch; 'sg' is unrelated. And 'copy_on_read' should be tweaked to document 'nonzero', not 'true', since it is used as a reference count rather than bool.

Yeah, these should all be changed separately really.

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 :|
#66 lore raw

PATCH v2 17/17 block: remove support for legecy AES qcow/qcow2 encryption

In reply to Daniel P. Berrange

Refuse to use images with the legacy AES-CBC encryption format in the system emulators. They are still fully supported in the qemu-img, qemu-io & qemu-nbd tools in order to allow data to be liberated and for compatibility with older QEMU versions. Continued support in these tools is not a notable burden with the new FDE framework.

---
 block.c                    | 12 +++++-------
 block/qcow.c               |  8 ++++++++
 block/qcow2.c              |  8 ++++++++
 include/block/block.h      |  1 +
 tests/qemu-iotests/049.out |  3 ---
 tests/qemu-iotests/087.out | 12 ------------
 tests/qemu-iotests/134.out | 12 ------------
 7 files changed, 22 insertions(+), 34 deletions(-)
block.c +5 -7
index 5403355..b59bd81 100644
@@ -312,6 +312,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;
@@ -1021,13 +1026,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 +8 -0
index 2fc7c3c..3ae438e 100644
@@ -180,6 +180,14 @@ 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) {
+            if (bdrv_uses_whitelist()) {
+                error_setg(errp,
+                           "Use of AES-CBC encrypted qcow images is no longer "
+                           "supported. Please use the qcow2 LUKS format instead.");
+                ret = -ENOSYS;
+                goto fail;
+            }
+
             ov = opts_visitor_new(opts);
 
             crypto_opts = g_new0(QCryptoBlockOpenOptions, 1);
block/qcow2.c +8 -0
index 1fbae85..a737c6c 100644
@@ -1209,6 +1209,14 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
 
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
+        if (bdrv_uses_whitelist() &&
+            s->crypt_method_header == QCOW_CRYPT_AES) {
+            error_setg(errp,
+                       "Use of AES-CBC encrypted qcow2 images is no longer "
+                       "supported. Please use the qcow2 LUKS format instead.");
+            ret = -ENOSYS;
+            goto fail;
+        }
         bs->encrypted = 1;
     }
 
include/block/block.h +1 -0
index 379a24c..58006d2 100644
@@ -190,6 +190,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 -3
index c9f0bc5..e0bedc0 100644
@@ -187,9 +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 --object secret,id=sec0,data=123456 -o encryption=on,key-secret=sec0 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.
 Formatting 'TEST_DIR/t.qcow2', fmt=qcow2 size=67108864 encryption=on cluster_size=65536 lazy_refcounts=off refcount_bits=16 key-secret=sec0
 
 == Check lazy_refcounts option (only with v3) ==
tests/qemu-iotests/087.out +0 -12
index 6582dda..b8842d5 100644
@@ -38,17 +38,11 @@ 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.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 Testing: -S
 QMP_VERSION
 {"return": {}}
 {"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.
 {"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
@@ -57,9 +51,6 @@ Testing:
 QMP_VERSION
 {"return": {}}
 {"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.
 {"return": {}}
 {"return": {}}
 {"timestamp": {"seconds":  TIMESTAMP, "microseconds":  TIMESTAMP}, "event": "SHUTDOWN"}
@@ -67,9 +58,6 @@ You can use 'qemu-img convert' to convert your image to an unencrypted one.
 
 === 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.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 Testing: -S
 QMP_VERSION
tests/qemu-iotests/134.out +0 -12
index e9bf302..d498570 100644
@@ -1,27 +1,15 @@
 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.
 Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=134217728 encryption=on key-secret=sec0
 
 == 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.
 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.
 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.
 read 134217728/134217728 bytes at offset 0
 128 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 
Signature · 1 line
2.5.0
#67 lore raw

Re: [Qemu-devel] [PATCH v2 17/17] block: remove support for legecy AES qcow/qcow2 encryption

Quoted 12 lines · Daniel P. Berrange

Refuse to use images with the legacy AES-CBC encryption format in the system emulators. They are still fully supported in the qemu-img, qemu-io & qemu-nbd tools in order to allow data to be liberated and for compatibility with older QEMU versions. Continued support in these tools is not a notable burden with the new FDE framework.

---

+++ b/block/qcow.c

block/qcow.c static int qcow_open(BlockDriverState *bs, QDict *options, int flags, · line 186

Quoted 7 lines
block/qcow.c +4 -0
@@ -180,6 +180,14 @@ 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) {
+            if (bdrv_uses_whitelist()) {
+                error_setg(errp,
+                           "Use of AES-CBC encrypted qcow images is no longer "
+                           "supported. Please use the qcow2 LUKS format instead.");

error_setg() should be a single phrase with no trailing punctuation, not two sentences. Use error_append_hint() for the suggestion of the replacement.

block/qcow2.c static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, · line 1216

Quoted 10 lines
block/qcow2.c +6 -0
+++ b/block/qcow2.c
@@ -1209,6 +1209,14 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
 
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
+        if (bdrv_uses_whitelist() &&
+            s->crypt_method_header == QCOW_CRYPT_AES) {
+            error_setg(errp,
+                       "Use of AES-CBC encrypted qcow2 images is no longer "
+                       "supported. Please use the qcow2 LUKS format instead.");

Ditto

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

Re: [Qemu-devel] [PATCH v2 17/17] block: remove support for legecy AES qcow/qcow2 encryption

Quoted 11 lines · Eric Blake
Quoted 9 lines · Daniel P. Berrange

Refuse to use images with the legacy AES-CBC encryption format in the system emulators. They are still fully supported in the qemu-img, qemu-io & qemu-nbd tools in order to allow data to be liberated and for compatibility with older QEMU versions. Continued support in these tools is not a notable burden with the new FDE framework.

---

Quoted 13 lines

block/qcow.c static int qcow_open(BlockDriverState *bs, QDict *options, int flags, · line 186

Quoted 9 lines

+++ b/block/qcow.c

block/qcow.c +4 -0
@@ -180,6 +180,14 @@ 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) {
+            if (bdrv_uses_whitelist()) {
+                error_setg(errp,
+                           "Use of AES-CBC encrypted qcow images is no longer "
+                           "supported. Please use the qcow2 LUKS format instead.");

error_setg() should be a single phrase with no trailing punctuation, not two sentences. Use error_append_hint() for the suggestion of the replacement.

Ah, I didn't know that method existed.

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 :|