Skip to contentSkip to conversation

Consolidate crypto APIs & implementations

PATCH Superseded Daniel P. Berrange 5 participants 36 messages May 21, 2015 – Jun 2, 2015

Subsystems (3)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

cover Consolidate crypto APIs & implementations

This small series covers the crypto consolidation patches I previously posted as part of a larger RFC for the TLS work

https://lists.nongnu.org/archive/html/qemu-devel/2015-04/msg02038.html

Currently there are a 5 main places in QEMU which use some form of cryptographic hash or cipher algorithm. These are the quorum block driver (hash), qcow[2] block driver (cipher), VNC password auth (cipher), VNC websockets (hash) and some of the CPU instruction emulation (cipher).

For ciphers the code is using the in-tree implementations of AES and/or the RFB cripple-DES. While there is nothing broken about these implementations, it is none the less desirable to be able to use the GNUTLS provided impls in cases whre we are already linking to GNUTLS. This will allow QEMU to use FIPS certified implementations, which have been well audited, have some protection against side-channel leakage and are generally actively maintained by people knowledgable about encryption.

For hash digests the code is already using GNUTLS APIs.

With the TLS work, and possible future improved block device encryption, there will be more general purpose crypto APIs needed in QEMU.

It is undesirable to continue to litter the code with countless #ifdef WITH_GNUTLS conditionals, as it makes it increasingly hard to understand the code.

The goal of this series is to thus consolidate all the crypto code into a single logical place in QEMU - the source in $GIT/crypto and heads in $GIT/include/crypto The code in this location will provide QEMU internal APIs for hash digests, ciphers, and later TLS and block encryption primitives. The implementations will be backed by GNUTLS, and either libgcrypt or nettle depending on which of these GNUTLS is linking to. In the case where GNUTLS is disabled at build time, we'll still keep the built-in AES & RFB-cripple-DES implementations available so we have no regression vs today's level of support.

The callers of the crypto code can now be unconditionally compiled and, if needed, they can check the availability of algorithms they want at runtime and report clear errors to the CLI or QMP if not available. This is a minor difference in behaviour for the quorum block driver which would previously be disabled at compile time if gnutls was not available.

A future posting will include the TLS crypto APIs.

I have not attempted to convert the CPU emulation code to use the new crypto APIs, since that code appears to have quite specific need for access to the low level internal stages of the AES algorithm. So I've left it using the QEMU built-in AES code.

I've added myself in the MAINTAINERS file for the new directories, since it was't clear if anyone else on the existing QEMU maintainer list had any interest / knowledge in maintaining the crypto related pieces.

Daniel P. Berrange (10):
crypto: introduce new module for computing hash digests
crypto: move built-in AES implementation into crypto/
crypto: move built-in D3DES implementation into crypto/
crypto: introduce generic cipher API & built-in implementation
crypto: add a gcrypt cipher implementation
crypto: add a nettle cipher implementation
block: convert quorum blockdrv to use crypto APIs
ui: convert VNC websockets to use crypto APIs
block: convert qcow/qcow2 to use generic cipher API
ui: convert VNC to use generic cipher API

 MAINTAINERS                           |   7 +
 Makefile.objs                         |   1 +
 block/Makefile.objs                   |   2 +-
 block/qcow.c                          | 100 ++++++---
 block/qcow2-cluster.c                 |  46 +++-
 block/qcow2.c                         |  95 +++++----
 block/qcow2.h                         |  13 +-
 block/quorum.c                        |  38 ++--
 configure                             | 162 +++++++++-----
 crypto/Makefile.objs                  |   5 +
 {util => crypto}/aes.c                |   2 +-
 crypto/cipher-builtin.c               | 391 ++++++++++++++++++++++++++++++++++
 crypto/cipher-gcrypt.c                | 203 ++++++++++++++++++
 crypto/cipher-nettle.c                | 226 ++++++++++++++++++++
 crypto/cipher.c                       |  31 +++
 ui/d3des.c => crypto/desrfb.c         |   2 +-
 crypto/hash.c                         | 202 ++++++++++++++++++
 crypto/init.c                         | 152 +++++++++++++
 include/{qemu => crypto}/aes.h        |   0
 include/crypto/cipher.h               | 208 ++++++++++++++++++
 ui/d3des.h => include/crypto/desrfb.h |   0
 include/crypto/hash.h                 | 189 ++++++++++++++++
 include/crypto/init.h                 |  29 +++
 target-arm/crypto_helper.c            |   2 +-
 target-i386/fpu_helper.c              |   1 -
 target-i386/ops_sse.h                 |   2 +-
 target-ppc/int_helper.c               |   2 +-
 tests/.gitignore                      |   2 +
 tests/Makefile                        |   4 +
 tests/test-crypto-cipher.c            | 290 +++++++++++++++++++++++++
 tests/test-crypto-hash.c              | 209 ++++++++++++++++++
 ui/Makefile.objs                      |   4 +-
 ui/vnc-ws.c                           |  22 +-
 ui/vnc-ws.h                           |   2 -
 ui/vnc.c                              | 122 +++++------
 ui/vnc.h                              |   8 -
 util/Makefile.objs                    |   2 +-
 vl.c                                  |   8 +
 38 files changed, 2517 insertions(+), 267 deletions(-)
 create mode 100644 crypto/Makefile.objs
 rename {util => crypto}/aes.c (99%)
 create mode 100644 crypto/cipher-builtin.c
 create mode 100644 crypto/cipher-gcrypt.c
 create mode 100644 crypto/cipher-nettle.c
 create mode 100644 crypto/cipher.c
 rename ui/d3des.c => crypto/desrfb.c (99%)
 create mode 100644 crypto/hash.c
 create mode 100644 crypto/init.c
 rename include/{qemu => crypto}/aes.h (100%)
 create mode 100644 include/crypto/cipher.h
 rename ui/d3des.h => include/crypto/desrfb.h (100%)
 create mode 100644 include/crypto/hash.h
 create mode 100644 include/crypto/init.h
 create mode 100644 tests/test-crypto-cipher.c
 create mode 100644 tests/test-crypto-hash.c
Signature · 1 line
2.1.0
#1 lore raw

PATCH 1/10 crypto: introduce new module for computing hash digests

Introduce a new crypto/ directory that will (eventually) contain all the cryptographic related code. This initially defines a wrapper for initializing gnutls and for computing hashes with gnutls. The former ensures that gnutls is guaranteed to be initialized exactly once in QEMU regardless of CLI args. The block quorum code currently fails to initialize gnutls so it only works by luck, if VNC server TLS is not requested. The hash APIs avoids the need to litter the rest of the code with preprocessor checks and simplifies callers by allocating the correct amount of memory for the requested hash.

---
 MAINTAINERS              |   7 ++
 Makefile.objs            |   1 +
 configure                |  46 +++++++++++
 crypto/Makefile.objs     |   2 +
 crypto/hash.c            | 202 +++++++++++++++++++++++++++++++++++++++++++++
 crypto/init.c            |  62 ++++++++++++++
 include/crypto/hash.h    | 189 ++++++++++++++++++++++++++++++++++++++++++
 include/crypto/init.h    |  29 +++++++
 tests/.gitignore         |   1 +
 tests/Makefile           |   2 +
 tests/test-crypto-hash.c | 209 +++++++++++++++++++++++++++++++++++++++++++++++
 vl.c                     |   8 ++
 12 files changed, 758 insertions(+)
 create mode 100644 crypto/Makefile.objs
 create mode 100644 crypto/hash.c
 create mode 100644 crypto/init.c
 create mode 100644 include/crypto/hash.h
 create mode 100644 include/crypto/init.h
 create mode 100644 tests/test-crypto-hash.c
MAINTAINERS +7 -0
index b3552b2..3dde9b6 100644
@@ -1015,6 +1015,13 @@ S: Supported
 F: qemu-seccomp.c
 F: include/sysemu/seccomp.h
 
+Cryptography
+M: Daniel P. Berrange <[email protected]>
+S: Maintained
+F: crypto/
+F: include/crypto/
+F: tests/test-crypto-*
+
 Usermode Emulation
 ------------------
 Overall
Makefile.objs +1 -0
index 28999d3..0f4dd84 100644
@@ -2,6 +2,7 @@
 # Common libraries for tools and emulators
 stub-obj-y = stubs/
 util-obj-y = util/ qobject/ qapi/ qapi-types.o qapi-visit.o qapi-event.o
+util-obj-y += crypto/
 
 #######################################################################
 # block-obj-y is code used by both qemu system emulation and qemu-img
configure +46 -0

82 lines not on this page · raw message

crypto/Makefile.objs new file +2 -0
new file mode 100644
index 0000000..03cc1b2
@@ -0,0 +1,2 @@
+util-obj-y += init.o
+util-obj-y += hash.o
crypto/hash.c new file +202 -0

202 lines not on this page · raw message

crypto/init.c new file +62 -0

62 lines not on this page · raw message

include/crypto/hash.h new file +189 -0

189 lines not on this page · raw message

include/crypto/init.h new file +29 -0
new file mode 100644
index 0000000..5fc510c
@@ -0,0 +1,29 @@
+/*
+ * QEMU Crypto initialization
+ *
+ * Copyright (c) 2015 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_INIT_H__
+#define QCRYPTO_INIT_H__
+
+#include "qemu-common.h"
+#include "qapi/error.h"
+
+int qcrypto_init(Error **errp);
+
+#endif /* QCRYPTO_INIT_H__ */
tests/.gitignore +1 -0
index 0dcb618..12d2373 100644
@@ -9,6 +9,7 @@ rcutorture
 test-aio
 test-bitops
 test-coroutine
+test-crypto-hash
 test-cutils
 test-hbitmap
 test-int128
tests/Makefile +2 -0
index 729b969..05f1dff 100644
@@ -72,6 +72,7 @@ check-unit-y += tests/test-qemu-opts$(EXESUF)
 gcov-files-test-qemu-opts-y = qom/test-qemu-opts.c
 check-unit-y += tests/test-write-threshold$(EXESUF)
 gcov-files-test-write-threshold-y = block/write-threshold.c
+check-unit-$(CONFIG_GNUTLS_HASH) += tests/test-crypto-hash$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -333,6 +334,7 @@ tests/test-opts-visitor$(EXESUF): tests/test-opts-visitor.o $(test-qapi-obj-y) l
 
 tests/test-mul64$(EXESUF): tests/test-mul64.o libqemuutil.a
 tests/test-bitops$(EXESUF): tests/test-bitops.o libqemuutil.a
+tests/test-crypto-hash$(EXESUF): tests/test-crypto-hash.o libqemuutil.a libqemustub.a
 
 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-hash.c new file +209 -0

209 lines not on this page · raw message

vl.c +8 -0
index 15bccc4..72313a4 100644
@@ -119,6 +119,7 @@ int main(int argc, char **argv)
 #include "qapi/opts-visitor.h"
 #include "qom/object_interfaces.h"
 #include "qapi-event.h"
+#include "crypto/init.h"
 
 #define DEFAULT_RAM_SIZE 128
 
@@ -2777,6 +2778,7 @@ int main(int argc, char **argv, char **envp)
     uint64_t ram_slots = 0;
     FILE *vmstate_dump_file = NULL;
     Error *main_loop_err = NULL;
+    Error *err = NULL;
 
     qemu_init_cpu_loop();
     qemu_mutex_lock_iothread();
@@ -2819,6 +2821,12 @@ int main(int argc, char **argv, char **envp)
 
     runstate_init();
 
+    if (qcrypto_init(&err) < 0) {
+        fprintf(stderr, "Cannot initialize crypto: %s\n",
+                error_get_pretty(err));
+        error_free(err);
+        exit(1);
+    }
     rtc_clock = QEMU_CLOCK_HOST;
 
     QLIST_INIT (&vm_change_state_head);
Signature · 1 line
2.1.0
#2 lore raw

Re: [Qemu-devel] [PATCH 01/10] crypto: introduce new module for computing hash digests

Quoted 104 lines · Daniel P. Berrange

Introduce a new crypto/ directory that will (eventually) contain all the cryptographic related code. This initially defines a wrapper for initializing gnutls and for computing hashes with gnutls. The former ensures that gnutls is guaranteed to be initialized exactly once in QEMU regardless of CLI args. The block quorum code currently fails to initialize gnutls so it only works by luck, if VNC server TLS is not requested. The hash APIs avoids the need to litter the rest of the code with preprocessor checks and simplifies callers by allocating the correct amount of memory for the requested hash.

---
 MAINTAINERS              |   7 ++
 Makefile.objs            |   1 +
 configure                |  46 +++++++++++
 crypto/Makefile.objs     |   2 +
 crypto/hash.c            | 202 +++++++++++++++++++++++++++++++++++++++++++++
 crypto/init.c            |  62 ++++++++++++++
 include/crypto/hash.h    | 189 ++++++++++++++++++++++++++++++++++++++++++
 include/crypto/init.h    |  29 +++++++
 tests/.gitignore         |   1 +
 tests/Makefile           |   2 +
 tests/test-crypto-hash.c | 209 +++++++++++++++++++++++++++++++++++++++++++++++
 vl.c                     |   8 ++
 12 files changed, 758 insertions(+)
 create mode 100644 crypto/Makefile.objs
 create mode 100644 crypto/hash.c
 create mode 100644 crypto/init.c
 create mode 100644 include/crypto/hash.h
 create mode 100644 include/crypto/init.h
 create mode 100644 tests/test-crypto-hash.c
MAINTAINERS +7 -0
index b3552b2..3dde9b6 100644
@@ -1015,6 +1015,13 @@ S: Supported
 F: qemu-seccomp.c
 F: include/sysemu/seccomp.h
 
+Cryptography
+M: Daniel P. Berrange <[email protected]>
+S: Maintained
+F: crypto/
+F: include/crypto/
+F: tests/test-crypto-*
+
 Usermode Emulation
 ------------------
 Overall
Makefile.objs +1 -0
index 28999d3..0f4dd84 100644
@@ -2,6 +2,7 @@
 # Common libraries for tools and emulators
 stub-obj-y = stubs/
 util-obj-y = util/ qobject/ qapi/ qapi-types.o qapi-visit.o qapi-event.o
+util-obj-y += crypto/
 
 #######################################################################
 # block-obj-y is code used by both qemu system emulation and qemu-img
configure +12 -0
index 1f0f485..6530e7a 100755
@@ -330,6 +330,8 @@ glusterfs_zerofill="no"
 archipelago="no"
 gtk=""
 gtkabi=""
+gnutls=""
+gnutls_hash=""
 vte=""
 tpm="yes"
 libssh2=""
@@ -1105,6 +1107,10 @@ for opt do
   ;;
   --enable-gtk) gtk="yes"
   ;;
+  --disable-gnutls) gnutls="no"
+  ;;
+  --enable-gnutls) gnutls="yes"
+  ;;
   --enable-rdma) rdma="yes"
   ;;
   --disable-rdma) rdma="no"
@@ -1286,6 +1292,8 @@ Advanced options (experts only):
   --disable-gtk            disable gtk UI
   --enable-gtk             enable gtk UI
   --with-gtkabi            select preferred GTK ABI 2.0 or 3.0
+  --disable-gnutls         disable gnutls crypto features
+  --enable-gnutls          enable gnutls crypto features
   --disable-virtfs         disable VirtFS
   --enable-virtfs          enable VirtFS
   --disable-vnc            disable VNC
@@ -2150,6 +2158,36 @@ if test "$gtk" != "no"; then
     fi
 fi
 
+
+##########################################
+# GNUTLS probe
+

configure if test "$gtk" != "no"; then · line 2174

Quoted 10 lines
configure +10 -0
+if test "$gnutls" != "no"; then
+    if $pkg_config --exists "gnutls"; then
+        gnutls_cflags=`$pkg_config --cflags gnutls`
+        gnutls_libs=`$pkg_config --libs gnutls`
+        libs_softmmu="$gnutls_libs $libs_softmmu"
+        libs_tools="$gnutls_libs $libs_tools"
+	QEMU_CFLAGS="$QEMU_CFLAGS $gnutls_cflags"
+        gnutls="yes"
+
+	# gnutls_hash_init requires >= 2.9.10

why 2.9.10 ? Isn't since 2.10.0 ?

Quoted 823 lines
configure +24 -0
+	if $pkg_config --exists "gnutls >= 2.9.10"; then
+            gnutls_hash="yes"
+	else
+	    gnutls_hash="no"
+	fi
+    elif test "$gnutls" = "yes"; then
+	feature_not_found "gnutls" "Install gnutls devel"
+    else
+        gnutls="no"
+        gnutls_hash="no"
+    fi
+else
+    gnutls_hash="no"
+fi
+
+
 ##########################################
 # VTE probe
 
@@ -4393,6 +4431,8 @@ fi
 echo "pixman            $pixman"
 echo "SDL support       $sdl"
 echo "GTK support       $gtk"
+echo "GNUTLS support    $gnutls"
+echo "GNUTLS hash       $gnutls_hash"
 echo "VTE support       $vte"
 echo "curses support    $curses"
 echo "curl support      $curl"
@@ -4745,6 +4785,12 @@ if test "$gtk" = "yes" ; then
   echo "CONFIG_GTKABI=$gtkabi" >> $config_host_mak
   echo "GTK_CFLAGS=$gtk_cflags" >> $config_host_mak
 fi
+if test "$gnutls" = "yes" ; then
+  echo "CONFIG_GNUTLS=y" >> $config_host_mak
+fi
+if test "$gnutls_hash" = "yes" ; then
+  echo "CONFIG_GNUTLS_HASH=y" >> $config_host_mak
+fi
 if test "$vte" = "yes" ; then
   echo "CONFIG_VTE=y" >> $config_host_mak
   echo "VTE_CFLAGS=$vte_cflags" >> $config_host_mak
crypto/Makefile.objs new file +2 -0
new file mode 100644
index 0000000..03cc1b2
@@ -0,0 +1,2 @@
+util-obj-y += init.o
+util-obj-y += hash.o
crypto/hash.c new file +202 -0
new file mode 100644
index 0000000..044a0a5
@@ -0,0 +1,202 @@
+/*
+ * QEMU Crypto hash algorithms
+ *
+ * Copyright (c) 2015 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/hash.h"
+
+#include <glib/gi18n.h>
+
+#ifdef CONFIG_GNUTLS_HASH
+#include <gnutls/gnutls.h>
+#include <gnutls/crypto.h>
+
+static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG_LAST] = {
+    [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,
+                        uint8_t **result,
+                        size_t *resultlen,
+                        Error **errp)
+{
+    int i, ret;
+    gnutls_hash_hd_t dig;
+
+    if (alg > G_N_ELEMENTS(qcrypto_hash_alg_map)) {
+        error_setg(errp,
+                   _("Unknown hash algorithm %d"),
+                   alg);
+        return -1;
+    }
+
+    ret = gnutls_hash_init(&dig, qcrypto_hash_alg_map[alg]);
+
+    if (ret < 0) {
+        error_setg(errp,
+                   _("Unable to initialize hash algorithm: %s"),
+                   gnutls_strerror(ret));
+        return -1;
+    }
+
+    for (i = 0; i < niov; i++) {
+        ret = gnutls_hash(dig, iov[i].iov_base, iov[i].iov_len);
+        if (ret < 0) {
+            error_setg(errp,
+                       _("Unable process hash data: %s"),
+                       gnutls_strerror(ret));
+            goto error;
+        }
+    }
+
+    ret = gnutls_hash_get_len(qcrypto_hash_alg_map[alg]);
+    if (ret <= 0) {
+        error_setg(errp,
+                   _("Unable to get hash length: %s"),
+                   gnutls_strerror(ret));
+        goto error;
+    }
+    if (*resultlen == 0) {
+        *resultlen = ret;
+        *result = g_new0(uint8_t, *resultlen);
+    } else if (*resultlen != ret) {
+        error_setg(errp,
+                   _("Result buffer size %zu is smaller than hash %d"),
+                   *resultlen, ret);
+        goto error;
+    }
+
+    gnutls_hash_deinit(dig, *result);
+    return 0;
+
+ error:
+    gnutls_hash_deinit(dig, NULL);
+    return -1;
+}
+
+#else /* ! CONFIG_GNUTLS_HASH */
+
+gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg G_GNUC_UNUSED)
+{
+    return false;
+}
+
+int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
+                        const struct iovec *iov G_GNUC_UNUSED,
+                        size_t niov G_GNUC_UNUSED,
+                        uint8_t **result G_GNUC_UNUSED,
+                        size_t *resultlen G_GNUC_UNUSED,
+                        Error **errp)
+{
+    error_setg(errp,
+               _("Hash algorithm %d not supported without GNUTLS"),
+               alg);
+    return -1;
+}
+
+#endif /* ! CONFIG_GNUTLS_HASH */
+
+int qcrypto_hash_bytes(QCryptoHashAlgorithm alg,
+                       const char *buf,
+                       size_t len,
+                       uint8_t **result,
+                       size_t *resultlen,
+                       Error **errp)
+{
+    struct iovec iov = { .iov_base = (char *)buf,
+                         .iov_len = len };
+    return qcrypto_hash_bytesv(alg, &iov, 1, result, resultlen, errp);
+}
+
+static const char hex[] = "0123456789abcdef";
+
+int qcrypto_hash_digestv(QCryptoHashAlgorithm alg,
+                         const struct iovec *iov,
+                         size_t niov,
+                         char **digest,
+                         Error **errp)
+{
+    uint8_t *result = NULL;
+    size_t resultlen = 0;
+    size_t i;
+
+    if (qcrypto_hash_bytesv(alg, iov, niov, &result, &resultlen, errp) < 0) {
+        return -1;
+    }
+
+    *digest = g_new0(char, (resultlen * 2) + 1);
+    for (i = 0 ; i < resultlen ; i++) {
+        (*digest)[(i * 2)] = hex[(result[i] >> 4) & 0xf];
+        (*digest)[(i * 2) + 1] = hex[result[i] & 0xf];
+    }
+    (*digest)[resultlen * 2] = '\0';
+    g_free(result);
+    return 0;
+}
+
+int qcrypto_hash_digest(QCryptoHashAlgorithm alg,
+                        const char *buf,
+                        size_t len,
+                        char **digest,
+                        Error **errp)
+{
+    struct iovec iov = { .iov_base = (char *)buf, .iov_len = len };
+
+    return qcrypto_hash_digestv(alg, &iov, 1, digest, errp);
+}
+
+int qcrypto_hash_base64v(QCryptoHashAlgorithm alg,
+                         const struct iovec *iov,
+                         size_t niov,
+                         char **base64,
+                         Error **errp)
+{
+    uint8_t *result = NULL;
+    size_t resultlen = 0;
+
+    if (qcrypto_hash_bytesv(alg, iov, niov, &result, &resultlen, errp) < 0) {
+        return -1;
+    }
+
+    *base64 = g_base64_encode(result, resultlen);
+    g_free(result);
+    return 0;
+}
+
+int qcrypto_hash_base64(QCryptoHashAlgorithm alg,
+                        const char *buf,
+                        size_t len,
+                        char **base64,
+                        Error **errp)
+{
+    struct iovec iov = { .iov_base = (char *)buf, .iov_len = len };
+
+    return qcrypto_hash_base64v(alg, &iov, 1, base64, errp);
+}
crypto/init.c new file +62 -0
new file mode 100644
index 0000000..8fd66d4
@@ -0,0 +1,62 @@
+/*
+ * QEMU Crypto initialization
+ *
+ * Copyright (c) 2015 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/init.h"
+
+#include <glib/gi18n.h>
+
+#ifdef CONFIG_GNUTLS
+#include <gnutls/gnutls.h>
+#include <gnutls/crypto.h>
+
+/* #define DEBUG_GNUTLS */
+
+#ifdef DEBUG_GNUTLS
+static void qcrypto_gnutls_log(int level, const char *str)
+{
+    fprintf(stderr, "%d: %s", level, str);
+}
+#endif
+
+int qcrypto_init(Error **errp)
+{
+    int ret;
+    ret = gnutls_global_init();
+    if (ret < 0) {
+        error_setg(errp,
+                   _("Unable to initialize GNUTLS library: %s"),
+                   gnutls_strerror(ret));
+        return -1;
+    }
+#ifdef DEBUG_GNUTLS
+    gnutls_global_set_log_level(10);
+    gnutls_global_set_log_function(qcrypto_gnutls_log);
+#endif
+    return 0;
+}
+
+#else /* ! CONFIG_GNUTLS */
+
+int qcrypto_init(Error **errp G_GNUC_UNUSED)
+{
+    return 0;
+}
+
+#endif /* ! CONFIG_GNUTLS */
include/crypto/hash.h new file +189 -0
new file mode 100644
index 0000000..b5acbf6
@@ -0,0 +1,189 @@
+/*
+ * QEMU Crypto hash algorithms
+ *
+ * Copyright (c) 2015 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_HASH_H__
+#define QCRYPTO_HASH_H__
+
+#include "qemu-common.h"
+#include "qapi/error.h"
+
+typedef enum {
+    QCRYPTO_HASH_ALG_MD5,
+    QCRYPTO_HASH_ALG_SHA1,
+    QCRYPTO_HASH_ALG_SHA256,
+
+    QCRYPTO_HASH_ALG_LAST
+} QCryptoHashAlgorithm;
+
+
+/**
+ * qcrypto_hash_supports:
+ * @alg: the hash algorithm
+ *
+ * Determine if @alg hash algorithm is supported by the
+ * current configured build.
+ *
+ * Returns: true if the algorithm is supported, false otherwise
+ */
+gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg);
+
+/**
+ * qcrypto_hash_bytesv:
+ * @alg: the hash algorithm
+ * @iov: the array of memory regions to hash
+ * @niov: the length of @iov
+ * @result: pointer to hold output hash
+ * @resultlen: pointer to hold length of @result
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory regions
+ * present in @iov. The @result pointer will be
+ * filled with raw bytes representing the computed
+ * hash, which will have length @resultlen. The
+ * memory pointer in @result must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
+                        const struct iovec *iov,
+                        size_t niov,
+                        uint8_t **result,
+                        size_t *resultlen,
+                        Error **errp);
+
+/**
+ * qcrypto_hash_bytes:
+ * @alg: the hash algorithm
+ * @buf: the memory region to hash
+ * @len: the length of @buf
+ * @result: pointer to hold output hash
+ * @resultlen: pointer to hold length of @result
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory region
+ * @buf of length @len. The @result pointer will be
+ * filled with raw bytes representing the computed
+ * hash, which will have length @resultlen. The
+ * memory pointer in @result must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_bytes(QCryptoHashAlgorithm alg,
+                       const char *buf,
+                       size_t len,
+                       uint8_t **result,
+                       size_t *resultlen,
+                       Error **errp);
+
+/**
+ * qcrypto_hash_digestv:
+ * @alg: the hash algorithm
+ * @iov: the array of memory regions to hash
+ * @niov: the length of @iov
+ * @digest: pointer to hold output hash
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory regions
+ * present in @iov. The @digest pointer will be
+ * filled with the printable hex digest of the computed
+ * hash, which will be terminated by '\0'. The
+ * memory pointer in @digest must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_digestv(QCryptoHashAlgorithm alg,
+                         const struct iovec *iov,
+                         size_t niov,
+                         char **digest,
+                         Error **errp);
+
+/**
+ * qcrypto_hash_digest:
+ * @alg: the hash algorithm
+ * @buf: the memory region to hash
+ * @len: the length of @buf
+ * @digest: pointer to hold output hash
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory region
+ * @buf of length @len. The @digest pointer will be
+ * filled with the printable hex digest of the computed
+ * hash, which will be terminated by '\0'. The
+ * memory pointer in @digest must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_digest(QCryptoHashAlgorithm alg,
+                        const char *buf,
+                        size_t len,
+                        char **digest,
+                        Error **errp);
+
+/**
+ * qcrypto_hash_base64v:
+ * @alg: the hash algorithm
+ * @iov: the array of memory regions to hash
+ * @niov: the length of @iov
+ * @base64: pointer to hold output hash
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory regions
+ * present in @iov. The @base64 pointer will be
+ * filled with the base64 encoding of the computed
+ * hash, which will be terminated by '\0'. The
+ * memory pointer in @base64 must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_base64v(QCryptoHashAlgorithm alg,
+                         const struct iovec *iov,
+                         size_t niov,
+                         char **base64,
+                         Error **errp);
+
+/**
+ * qcrypto_hash_base64:
+ * @alg: the hash algorithm
+ * @buf: the memory region to hash
+ * @len: the length of @buf
+ * @base64: pointer to hold output hash
+ * @errp: pointer to uninitialized error object
+ *
+ * Computes the hash across all the memory region
+ * @buf of length @len. The @base64 pointer will be
+ * filled with the base64 encoding of the computed
+ * hash, which will be terminated by '\0'. The
+ * memory pointer in @base64 must be released
+ * with a call to g_free() when no longer required.
+ *
+ * Returns: 0 on success, -1 on error
+ */
+int qcrypto_hash_base64(QCryptoHashAlgorithm alg,
+                        const char *buf,
+                        size_t len,
+                        char **base64,
+                        Error **errp);
+
+#endif /* QCRYPTO_HASH_H__ */
include/crypto/init.h new file +29 -0
new file mode 100644
index 0000000..5fc510c
@@ -0,0 +1,29 @@
+/*
+ * QEMU Crypto initialization
+ *
+ * Copyright (c) 2015 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_INIT_H__
+#define QCRYPTO_INIT_H__
+
+#include "qemu-common.h"
+#include "qapi/error.h"
+
+int qcrypto_init(Error **errp);
+
+#endif /* QCRYPTO_INIT_H__ */
tests/.gitignore +1 -0
index 0dcb618..12d2373 100644
@@ -9,6 +9,7 @@ rcutorture
 test-aio
 test-bitops
 test-coroutine
+test-crypto-hash
 test-cutils
 test-hbitmap
 test-int128
tests/Makefile +2 -0
index 729b969..05f1dff 100644
@@ -72,6 +72,7 @@ check-unit-y += tests/test-qemu-opts$(EXESUF)
 gcov-files-test-qemu-opts-y = qom/test-qemu-opts.c
 check-unit-y += tests/test-write-threshold$(EXESUF)
 gcov-files-test-write-threshold-y = block/write-threshold.c
+check-unit-$(CONFIG_GNUTLS_HASH) += tests/test-crypto-hash$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -333,6 +334,7 @@ tests/test-opts-visitor$(EXESUF): tests/test-opts-visitor.o $(test-qapi-obj-y) l
 
 tests/test-mul64$(EXESUF): tests/test-mul64.o libqemuutil.a
 tests/test-bitops$(EXESUF): tests/test-bitops.o libqemuutil.a
+tests/test-crypto-hash$(EXESUF): tests/test-crypto-hash.o libqemuutil.a libqemustub.a
 
 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-hash.c new file +209 -0
new file mode 100644
index 0000000..911437e
@@ -0,0 +1,209 @@
+/*
+ * QEMU Crypto hash algorithms
+ *
+ * Copyright (c) 2015 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 <glib.h>
+
+#include "crypto/init.h"
+#include "crypto/hash.h"
+
+#define INPUT_TEXT "Hiss hisss Hissss hiss Hiss hisss Hiss hiss"
+#define INPUT_TEXT1 "Hiss hisss "
+#define INPUT_TEXT2 "Hissss hiss "
+#define INPUT_TEXT3 "Hiss hisss Hiss hiss"
+
+#define OUTPUT_MD5 "628d206371563035ab8ef62f492bdec9"
+#define OUTPUT_SHA1 "b2e74f26758a3a421e509cee045244b78753cc02"
+#define OUTPUT_SHA256 "bc757abb0436586f392b437e5dd24096" \
+                      "f7f224de6b74d4d86e2abc6121b160d0"
+
+#define OUTPUT_MD5_B64 "Yo0gY3FWMDWrjvYvSSveyQ=="
+#define OUTPUT_SHA1_B64 "sudPJnWKOkIeUJzuBFJEt4dTzAI="
+#define OUTPUT_SHA256_B64 "vHV6uwQ2WG85K0N+XdJAlvfyJN5rdNTYbiq8YSGxYNA="
+
+static const char *expected_outputs[] = {
+    [QCRYPTO_HASH_ALG_MD5] = OUTPUT_MD5,
+    [QCRYPTO_HASH_ALG_SHA1] = OUTPUT_SHA1,
+    [QCRYPTO_HASH_ALG_SHA256] = OUTPUT_SHA256,
+};
+static const char *expected_outputs_b64[] = {
+    [QCRYPTO_HASH_ALG_MD5] = OUTPUT_MD5_B64,
+    [QCRYPTO_HASH_ALG_SHA1] = OUTPUT_SHA1_B64,
+    [QCRYPTO_HASH_ALG_SHA256] = OUTPUT_SHA256_B64,
+};
+static const int expected_lens[] = {
+    [QCRYPTO_HASH_ALG_MD5] = 16,
+    [QCRYPTO_HASH_ALG_SHA1] = 20,
+    [QCRYPTO_HASH_ALG_SHA256] = 32,
+};
+
+static const char hex[] = "0123456789abcdef";
+
+/* Test with dynamic allocation */
+static void test_hash_alloc(void)
+{
+    size_t i;
+
+    g_assert(qcrypto_init(NULL) == 0);
+
+    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
+        uint8_t *result = NULL;
+        size_t resultlen = 0;
+        int ret;
+        size_t j;
+
+        ret = qcrypto_hash_bytes(i,
+                                 INPUT_TEXT,
+                                 strlen(INPUT_TEXT),
+                                 &result,
+                                 &resultlen,
+                                 NULL);
+        g_assert(ret == 0);
+        g_assert(resultlen == expected_lens[i]);
+
+        for (j = 0; j < resultlen; j++) {
+            g_assert(expected_outputs[i][j * 2] == hex[(result[j] >> 4) & 0xf]);
+            g_assert(expected_outputs[i][j * 2 + 1] == hex[result[j] & 0xf]);
+        }
+        g_free(result);
+    }
+}
+
+/* Test with caller preallocating */
+static void test_hash_prealloc(void)
+{
+    size_t i;
+
+    g_assert(qcrypto_init(NULL) == 0);
+
+    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
+        uint8_t *result;
+        size_t resultlen;
+        int ret;
+        size_t j;
+
+        resultlen = expected_lens[i];
+        result = g_new0(uint8_t, resultlen);
+
+        ret = qcrypto_hash_bytes(i,
+                                 INPUT_TEXT,
+                                 strlen(INPUT_TEXT),
+                                 &result,
+                                 &resultlen,
+                                 NULL);
+        g_assert(ret == 0);
+
+        g_assert(resultlen == expected_lens[i]);
+        for (j = 0; j < resultlen; j++) {
+            g_assert(expected_outputs[i][j * 2] == hex[(result[j] >> 4) & 0xf]);
+            g_assert(expected_outputs[i][j * 2 + 1] == hex[result[j] & 0xf]);
+        }
+        g_free(result);
+    }
+}
+
+
+/* Test with dynamic allocation */
+static void test_hash_iov(void)
+{
+    size_t i;
+
+    g_assert(qcrypto_init(NULL) == 0);
+
+    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
+        struct iovec iov[3] = {
+            { .iov_base = (char *)INPUT_TEXT1, .iov_len = strlen(INPUT_TEXT1) },
+            { .iov_base = (char *)INPUT_TEXT2, .iov_len = strlen(INPUT_TEXT2) },
+            { .iov_base = (char *)INPUT_TEXT3, .iov_len = strlen(INPUT_TEXT3) },
+        };
+        uint8_t *result = NULL;
+        size_t resultlen = 0;
+        int ret;
+        size_t j;
+
+        ret = qcrypto_hash_bytesv(i,
+                                  iov, 3,
+                                  &result,
+                                  &resultlen,
+                                  NULL);
+        g_assert(ret == 0);
+        g_assert(resultlen == expected_lens[i]);
+        for (j = 0; j < resultlen; j++) {
+            g_assert(expected_outputs[i][j * 2] == hex[(result[j] >> 4) & 0xf]);
+            g_assert(expected_outputs[i][j * 2 + 1] == hex[result[j] & 0xf]);
+        }
+        g_free(result);
+    }
+}
+
+
+/* Test with printable hashing */
+static void test_hash_digest(void)
+{
+    size_t i;
+
+    g_assert(qcrypto_init(NULL) == 0);
+
+    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
+        int ret;
+        char *digest;
+
+        ret = qcrypto_hash_digest(i,
+                                  INPUT_TEXT,
+                                  strlen(INPUT_TEXT),
+                                  &digest,
+                                  NULL);
+        g_assert(ret == 0);
+        g_assert(g_str_equal(digest, expected_outputs[i]));
+        g_free(digest);
+    }
+}
+
+/* Test with base64 encoding */
+static void test_hash_base64(void)
+{
+    size_t i;
+
+    g_assert(qcrypto_init(NULL) == 0);
+
+    for (i = 0; i < G_N_ELEMENTS(expected_outputs) ; i++) {
+        int ret;
+        char *digest;
+
+        ret = qcrypto_hash_base64(i,
+                                  INPUT_TEXT,
+                                  strlen(INPUT_TEXT),
+                                  &digest,
+                                  NULL);
+        g_assert(ret == 0);
+        g_assert(g_str_equal(digest, expected_outputs_b64[i]));
+        g_free(digest);
+    }
+}
+
+int main(int argc, char **argv)
+{
+    g_test_init(&argc, &argv, NULL);
+    g_test_add_func("/crypto/hash/iov", test_hash_iov);
+    g_test_add_func("/crypto/hash/alloc", test_hash_alloc);
+    g_test_add_func("/crypto/hash/prealloc", test_hash_prealloc);
+    g_test_add_func("/crypto/hash/digest", test_hash_digest);
+    g_test_add_func("/crypto/hash/base64", test_hash_base64);
+    return g_test_run();
+}
vl.c +2 -0
index 15bccc4..72313a4 100644
@@ -119,6 +119,7 @@ int main(int argc, char **argv)
 #include "qapi/opts-visitor.h"
 #include "qom/object_interfaces.h"
 #include "qapi-event.h"
+#include "crypto/init.h"
 
 #define DEFAULT_RAM_SIZE 128
 
@@ -2777,6 +2778,7 @@ int main(int argc, char **argv, char **envp)
     uint64_t ram_slots = 0;
     FILE *vmstate_dump_file = NULL;
     Error *main_loop_err = NULL;
+    Error *err = NULL;
 
     qemu_init_cpu_loop();
     qemu_mutex_lock_iothread();

vl.c int main(int argc, char **argv, char **envp) · line 2827

Quoted 7 lines
vl.c +4 -0
@@ -2819,6 +2821,12 @@ int main(int argc, char **argv, char **envp)
 
     runstate_init();
 
+    if (qcrypto_init(&err) < 0) {
+        fprintf(stderr, "Cannot initialize crypto: %s\n",
+                error_get_pretty(err));
+        error_free(err);

This free is superflous (before exit) IMO.

Regards,
-Gonglei

Quoted 6 lines
vl.c +2 -0
+        exit(1);
+    }
     rtc_clock = QEMU_CLOCK_HOST;
 
     QLIST_INIT (&vm_change_state_head);
#3 lore raw

Re: [Qemu-devel] [PATCH 01/10] crypto: introduce new module for computing hash digests

Quoted 14 lines · Gonglei
Quoted 12 lines · Daniel P. Berrange

Introduce a new crypto/ directory that will (eventually) contain all the cryptographic related code. This initially defines a wrapper for initializing gnutls and for computing hashes with gnutls. The former ensures that gnutls is guaranteed to be initialized exactly once in QEMU regardless of CLI args. The block quorum code currently fails to initialize gnutls so it only works by luck, if VNC server TLS is not requested. The hash APIs avoids the need to litter the rest of the code with preprocessor checks and simplifies callers by allocating the correct amount of memory for the requested hash.

Quoted 15 lines

configure if test "$gtk" != "no"; then · line 2174

Quoted 13 lines
configure +13 -0
+##########################################
+# GNUTLS probe
+
+if test "$gnutls" != "no"; then
+    if $pkg_config --exists "gnutls"; then
+        gnutls_cflags=`$pkg_config --cflags gnutls`
+        gnutls_libs=`$pkg_config --libs gnutls`
+        libs_softmmu="$gnutls_libs $libs_softmmu"
+        libs_tools="$gnutls_libs $libs_tools"
+	QEMU_CFLAGS="$QEMU_CFLAGS $gnutls_cflags"
+        gnutls="yes"
+
+	# gnutls_hash_init requires >= 2.9.10

why 2.9.10 ? Isn't since 2.10.0 ?

I've double checked and 2.9.10 is correct according to the gnutls NEWS file

[quote]
* Version 2.9.10 (released 2010-04-22)
...
** libgnutls: Exported API to access encryption and hash algorithms. The new API functions are gnutls_cipher_decrypt, gnutls_cipher_deinit, gnutls_cipher_encrypt, gnutls_cipher_get_block_size, gnutls_cipher_init, gnutls_hash, gnutls_hash_deinit, gnutls_hash_fast, gnutls_hash_get_len, gnutls_hash_init, gnutls_hash_output, gnutls_hmac, gnutls_hmac_deinit, gnutls_hmac_fast, gnutls_hmac_get_len, gnutls_hmac_init, gnutls_hmac_output. New API constants are GNUTLS_MAC_SHA224 and GNUTLS_DIG_SHA224. [/quote]

Quoted 22 lines
Quoted 22 lines
vl.c +2 -0
index 15bccc4..72313a4 100644
@@ -119,6 +119,7 @@ int main(int argc, char **argv)
 #include "qapi/opts-visitor.h"
 #include "qom/object_interfaces.h"
 #include "qapi-event.h"
+#include "crypto/init.h"
 
 #define DEFAULT_RAM_SIZE 128
 
@@ -2777,6 +2778,7 @@ int main(int argc, char **argv, char **envp)
     uint64_t ram_slots = 0;
     FILE *vmstate_dump_file = NULL;
     Error *main_loop_err = NULL;
+    Error *err = NULL;
 
     qemu_init_cpu_loop();
     qemu_mutex_lock_iothread();
@@ -2819,6 +2821,12 @@ int main(int argc, char **argv, char **envp)
 
Quoted 8 lines

vl.c int main(int argc, char **argv, char **envp) · line 2827

Quoted 6 lines
vl.c +4 -0
     runstate_init();
 
+    if (qcrypto_init(&err) < 0) {
+        fprintf(stderr, "Cannot initialize crypto: %s\n",
+                error_get_pretty(err));
+        error_free(err);

This free is superflous (before exit) IMO.

Personally I always free variables like this so valgrind doesn't complain about leaks.

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

Re: [Qemu-devel] [PATCH 01/10] crypto: introduce new module for computing hash digests

Quoted 14 lines · Daniel P. Berrange
Quoted 13 lines · Gonglei
Quoted 12 lines · Daniel P. Berrange

Introduce a new crypto/ directory that will (eventually) contain all the cryptographic related code. This initially defines a wrapper for initializing gnutls and for computing hashes with gnutls. The former ensures that gnutls is guaranteed to be initialized exactly once in QEMU regardless of CLI args. The block quorum code currently fails to initialize gnutls so it only works by luck, if VNC server TLS is not requested. The hash APIs avoids the need to litter the rest of the code with preprocessor checks and simplifies callers by allocating the correct amount of memory for the requested hash.

[...]

Quoted 31 lines
Quoted 22 lines
Quoted 22 lines
vl.c +2 -0
index 15bccc4..72313a4 100644
@@ -119,6 +119,7 @@ int main(int argc, char **argv)
 #include "qapi/opts-visitor.h"
 #include "qom/object_interfaces.h"
 #include "qapi-event.h"
+#include "crypto/init.h"
 
 #define DEFAULT_RAM_SIZE 128
 
@@ -2777,6 +2778,7 @@ int main(int argc, char **argv, char **envp)
     uint64_t ram_slots = 0;
     FILE *vmstate_dump_file = NULL;
     Error *main_loop_err = NULL;
+    Error *err = NULL;
 
     qemu_init_cpu_loop();
     qemu_mutex_lock_iothread();
@@ -2819,6 +2821,12 @@ int main(int argc, char **argv, char **envp)
 
Quoted 8 lines

vl.c int main(int argc, char **argv, char **envp) · line 2827

Quoted 6 lines
vl.c +4 -0
     runstate_init();
 
+    if (qcrypto_init(&err) < 0) {
+        fprintf(stderr, "Cannot initialize crypto: %s\n",
+                error_get_pretty(err));
+        error_free(err);

This free is superflous (before exit) IMO.

Quoted 2 lines

Personally I always free variables like this so valgrind doesn't complain about leaks.

Marginally useful when you do it for the complete program. QEMU doesn't, and making all of QEMU do it would be a fool's errand.

#5 lore raw

Re: [Qemu-devel] [PATCH 01/10] crypto: introduce new module for computing hash digests

Quoted 48 lines · Markus Armbruster
Quoted 14 lines · Daniel P. Berrange
Quoted 13 lines · Gonglei
Quoted 12 lines · Daniel P. Berrange

Introduce a new crypto/ directory that will (eventually) contain all the cryptographic related code. This initially defines a wrapper for initializing gnutls and for computing hashes with gnutls. The former ensures that gnutls is guaranteed to be initialized exactly once in QEMU regardless of CLI args. The block quorum code currently fails to initialize gnutls so it only works by luck, if VNC server TLS is not requested. The hash APIs avoids the need to litter the rest of the code with preprocessor checks and simplifies callers by allocating the correct amount of memory for the requested hash.

[...]

Quoted 31 lines
Quoted 30 lines
Quoted 21 lines
vl.c +2 -0
index 15bccc4..72313a4 100644
@@ -119,6 +119,7 @@ int main(int argc, char **argv)
 #include "qapi/opts-visitor.h"
 #include "qom/object_interfaces.h"
 #include "qapi-event.h"
+#include "crypto/init.h"
 
 #define DEFAULT_RAM_SIZE 128
 
@@ -2777,6 +2778,7 @@ int main(int argc, char **argv, char **envp)
     uint64_t ram_slots = 0;
     FILE *vmstate_dump_file = NULL;
     Error *main_loop_err = NULL;
+    Error *err = NULL;
 
     qemu_init_cpu_loop();
     qemu_mutex_lock_iothread();

vl.c int main(int argc, char **argv, char **envp) · line 2827

Quoted 7 lines
vl.c +4 -0
@@ -2819,6 +2821,12 @@ int main(int argc, char **argv, char **envp)
 
     runstate_init();
 
+    if (qcrypto_init(&err) < 0) {
+        fprintf(stderr, "Cannot initialize crypto: %s\n",
+                error_get_pretty(err));
+        error_free(err);

This free is superflous (before exit) IMO.

Quoted 5 lines
Quoted 2 lines

Personally I always free variables like this so valgrind doesn't complain about leaks.

Marginally useful when you do it for the complete program. QEMU doesn't, and making all of QEMU do it would be a fool's errand.

Ok, i'll remove 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 :|
#6 lore raw

PATCH 2/10 crypto: move built-in AES implementation into crypto/

In reply to Daniel P. Berrange

To prepare for a generic internal cipher API, move the built-in AES implementation into the crypto/ directory

---
 block/qcow.c                   | 2 +-
 block/qcow2.c                  | 1 -
 block/qcow2.h                  | 2 +-
 crypto/Makefile.objs           | 1 +
 {util => crypto}/aes.c         | 2 +-
 include/{qemu => crypto}/aes.h | 0
 target-arm/crypto_helper.c     | 2 +-
 target-i386/fpu_helper.c       | 1 -
 target-i386/ops_sse.h          | 2 +-
 target-ppc/int_helper.c        | 2 +-
 util/Makefile.objs             | 2 +-
 11 files changed, 8 insertions(+), 9 deletions(-)
 rename {util => crypto}/aes.c (99%)
 rename include/{qemu => crypto}/aes.h (100%)
block/qcow.c +1 -1
index ab89328..50dbcee 100644
@@ -25,7 +25,7 @@
 #include "block/block_int.h"
 #include "qemu/module.h"
 #include <zlib.h>
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 #include "migration/migration.h"
 
 /**************************************************************/
block/qcow2.c +0 -1
index b9a72e3..83e5ec9 100644
@@ -25,7 +25,6 @@
 #include "block/block_int.h"
 #include "qemu/module.h"
 #include <zlib.h>
-#include "qemu/aes.h"
 #include "block/qcow2.h"
 #include "qemu/error-report.h"
 #include "qapi/qmp/qerror.h"
block/qcow2.h +1 -1
index 422b825..3cf5318 100644
@@ -25,7 +25,7 @@
 #ifndef BLOCK_QCOW2_H
 #define BLOCK_QCOW2_H
 
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 #include "block/coroutine.h"
 
 //#define DEBUG_ALLOC
crypto/Makefile.objs +1 -0
index 03cc1b2..9efc9b4 100644
@@ -1,2 +1,3 @@
 util-obj-y += init.o
 util-obj-y += hash.o
+util-obj-y += aes.o
crypto/aes.c renamed from util/aes.c +1 -1
similarity index 99%
rename from util/aes.c
rename to crypto/aes.c
index 3d7c4be..244a388 100644
@@ -28,7 +28,7 @@
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include "qemu-common.h"
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 
 typedef uint32_t u32;
 typedef uint8_t u8;
include/crypto/aes.h renamed from include/qemu/aes.h +0 -0
similarity index 100%
rename from include/qemu/aes.h
rename to include/crypto/aes.h
target-arm/crypto_helper.c +1 -1
index 1fe975d..5d22838 100644
@@ -14,7 +14,7 @@
 #include "cpu.h"
 #include "exec/exec-all.h"
 #include "exec/helper-proto.h"
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 
 union CRYPTO_STATE {
     uint8_t    bytes[16];
target-i386/fpu_helper.c +0 -1
index 30d34d5..280adba 100644
@@ -20,7 +20,6 @@
 #include <math.h>
 #include "cpu.h"
 #include "exec/helper-proto.h"
-#include "qemu/aes.h"
 #include "qemu/host-utils.h"
 #include "exec/cpu_ldst.h"
 
target-i386/ops_sse.h +1 -1
index 0765073..bee134b 100644
@@ -18,7 +18,7 @@
  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  */
 
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 
 #if SHIFT == 0
 #define Reg MMXReg
target-ppc/int_helper.c +1 -1
index 4c2b71c..0a55d5e 100644
@@ -19,7 +19,7 @@
 #include "cpu.h"
 #include "qemu/host-utils.h"
 #include "exec/helper-proto.h"
-#include "qemu/aes.h"
+#include "crypto/aes.h"
 
 #include "helper_regs.h"
 /*****************************************************************************/
util/Makefile.objs +1 -1
index ceaba30..114d657 100644
@@ -9,7 +9,7 @@ util-obj-y += acl.o
 util-obj-y += error.o qemu-error.o
 util-obj-$(CONFIG_POSIX) += compatfd.o
 util-obj-y += id.o
-util-obj-y += iov.o aes.o qemu-config.o qemu-sockets.o uri.o notify.o
+util-obj-y += iov.o qemu-config.o qemu-sockets.o uri.o notify.o
 util-obj-y += qemu-option.o qemu-progress.o
 util-obj-y += hexdump.o
 util-obj-y += crc32c.o
Signature · 1 line
2.1.0
#7 lore raw

PATCH 3/10 crypto: move built-in D3DES implementation into crypto/

In reply to Daniel P. Berrange

To prepare for a generic internal cipher API, move the built-in D3DES implementation into the crypto/ directory.

This is not in fact a normal D3DES implementation, it is D3DES with double & triple length modes removed, and the key bytes in reversed bit order. IOW it is crippled specifically for the "benefit" of RFB, so call the new files desrfb.c instead of d3des.c to make it clear that it isn't a generally useful impl.

---
 crypto/Makefile.objs                  | 1 +
 ui/d3des.c => crypto/desrfb.c         | 2 +-
 ui/d3des.h => include/crypto/desrfb.h | 0
 ui/Makefile.objs                      | 2 +-
 ui/vnc.c                              | 2 +-
 5 files changed, 4 insertions(+), 3 deletions(-)
 rename ui/d3des.c => crypto/desrfb.c (99%)
 rename ui/d3des.h => include/crypto/desrfb.h (100%)
crypto/Makefile.objs +1 -0
index 9efc9b4..9f70294 100644
@@ -1,3 +1,4 @@
 util-obj-y += init.o
 util-obj-y += hash.o
 util-obj-y += aes.o
+util-obj-y += desrfb.o
crypto/desrfb.c renamed from ui/d3des.c +1 -1
similarity index 99%
rename from ui/d3des.c
rename to crypto/desrfb.c
index 5bc99b8..fc20a30 100644
@@ -26,7 +26,7 @@
  * (GEnie : OUTER; CIS : [71755,204]) Graven Imagery, 1992.
  */
 
-#include "d3des.h"
+#include "crypto/desrfb.h"
 
 static void scrunch(unsigned char *, unsigned long *);
 static void unscrun(unsigned long *, unsigned char *);
include/crypto/desrfb.h renamed from ui/d3des.h +0 -0
similarity index 100%
rename from ui/d3des.h
rename to include/crypto/desrfb.h
ui/Makefile.objs +1 -1
index 029a42a..d9796b1 100644
@@ -1,4 +1,4 @@
-vnc-obj-y += vnc.o d3des.o
+vnc-obj-y += vnc.o
 vnc-obj-y += vnc-enc-zlib.o vnc-enc-hextile.o
 vnc-obj-y += vnc-enc-tight.o vnc-palette.o
 vnc-obj-y += vnc-enc-zrle.o
ui/vnc.c +1 -1
index 1013ea5..2b80160 100644
@@ -46,7 +46,7 @@ static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
 
 #include "vnc_keysym.h"
-#include "d3des.h"
+#include "crypto/desrfb.h"
 
 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
     QTAILQ_HEAD_INITIALIZER(vnc_displays);
Signature · 1 line
2.1.0
#8 lore raw

PATCH 4/10 crypto: introduce generic cipher API & built-in implementation

In reply to Daniel P. Berrange

Introduce a generic cipher API and an implementation of it that supports only the built-in AES and DES-RFB algorithms.

The test suite checks the supported algorithms + modes to validate that every backend implementation is actually correctly complying with the specs.

---
 crypto/Makefile.objs       |   1 +
 crypto/cipher-builtin.c    | 391 +++++++++++++++++++++++++++++++++++++++++++++
 crypto/cipher.c            |  23 +++
 include/crypto/cipher.h    | 208 ++++++++++++++++++++++++
 tests/.gitignore           |   1 +
 tests/Makefile             |   2 +
 tests/test-crypto-cipher.c | 290 +++++++++++++++++++++++++++++++++
 7 files changed, 916 insertions(+)
 create mode 100644 crypto/cipher-builtin.c
 create mode 100644 crypto/cipher.c
 create mode 100644 include/crypto/cipher.h
 create mode 100644 tests/test-crypto-cipher.c
crypto/Makefile.objs +1 -0
index 9f70294..b050138 100644
@@ -2,3 +2,4 @@ util-obj-y += init.o
 util-obj-y += hash.o
 util-obj-y += aes.o
 util-obj-y += desrfb.o
+util-obj-y += cipher.o
crypto/cipher-builtin.c new file +391 -0

391 lines not on this page · raw message

crypto/cipher.c new file +23 -0
new file mode 100644
index 0000000..71e9eae
@@ -0,0 +1,23 @@
+/*
+ * QEMU Crypto cipher algorithms
+ *
+ * Copyright (c) 2015 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/cipher.h"
+
+#include "crypto/cipher-builtin.c"
include/crypto/cipher.h new file +208 -0

208 lines not on this page · raw message

tests/.gitignore +1 -0
index 12d2373..e93148e 100644
@@ -9,6 +9,7 @@ rcutorture
 test-aio
 test-bitops
 test-coroutine
+test-crypto-cipher
 test-crypto-hash
 test-cutils
 test-hbitmap
tests/Makefile +2 -0
index 05f1dff..39d3e78 100644
@@ -73,6 +73,7 @@ gcov-files-test-qemu-opts-y = qom/test-qemu-opts.c
 check-unit-y += tests/test-write-threshold$(EXESUF)
 gcov-files-test-write-threshold-y = block/write-threshold.c
 check-unit-$(CONFIG_GNUTLS_HASH) += tests/test-crypto-hash$(EXESUF)
+check-unit-y += tests/test-crypto-cipher$(EXESUF)
 
 check-block-$(CONFIG_POSIX) += tests/qemu-iotests-quick.sh
 
@@ -335,6 +336,7 @@ tests/test-opts-visitor$(EXESUF): tests/test-opts-visitor.o $(test-qapi-obj-y) l
 tests/test-mul64$(EXESUF): tests/test-mul64.o libqemuutil.a
 tests/test-bitops$(EXESUF): tests/test-bitops.o libqemuutil.a
 tests/test-crypto-hash$(EXESUF): tests/test-crypto-hash.o libqemuutil.a libqemustub.a
+tests/test-crypto-cipher$(EXESUF): tests/test-crypto-cipher.o libqemuutil.a libqemustub.a
 
 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-cipher.c new file +290 -0

290 lines not on this page · raw message

Signature · 1 line
2.1.0
#9 lore raw

Re: [Qemu-devel] [PATCH 04/10] crypto: introduce generic cipher API & built-in implementation

Quoted 24 lines · Daniel P. Berrange
crypto/cipher-builtin.c new file +24 -0
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    switch (cipher->alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        if (qcrypto_cipher_init_des_rfb(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (qcrypto_cipher_init_aes(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    default:
+        error_setg(errp,

crypto/cipher-builtin.c line 320

Quoted 10 lines
crypto/cipher-builtin.c new file +10 -0
+                   _("Unsupported cipher algorithm %d"), cipher->alg);
+        goto error;
+    }
+
+    return cipher;
+
+ error:
+    g_free(cipher);
+    return NULL;
+}

Is it really that helpful to have all of these switches, as opposed to having one function per cipher and calling it directly? Similarly for the hashing.

The uses I pulled out of the later patches are like

+ if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,

+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {

+ return -EINVAL;

+ if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,

+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {

+ cipher = qcrypto_cipher_new(

+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);

+ s->cipher = qcrypto_cipher_new(

+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);

This one could have explicitly specified AES128, but you hid that behind G_N_ELEMENTS. Which seems like obfuscation to me, but...

r~

#10 lore raw

Re: [Qemu-devel] [PATCH 04/10] crypto: introduce generic cipher API & built-in implementation

Quoted 30 lines · Richard Henderson
Quoted 29 lines · Daniel P. Berrange
crypto/cipher-builtin.c new file +29 -0
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    switch (cipher->alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        if (qcrypto_cipher_init_des_rfb(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (qcrypto_cipher_init_aes(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    default:
+        error_setg(errp,
+                   _("Unsupported cipher algorithm %d"), cipher->alg);
+        goto error;
+    }
+
+    return cipher;
Quoted 8 lines

crypto/cipher-builtin.c line 320

Quoted 5 lines
crypto/cipher-builtin.c new file +5 -0
+
+ error:
+    g_free(cipher);
+    return NULL;
+}

Is it really that helpful to have all of these switches, as opposed to having one function per cipher and calling it directly? Similarly for the hashing.

These switches are just an artifact of this default built-in implementation where we're jumping off to one or our two built-in crypto algorithsm. The gcrypt backend of these APIs has no such switch, since there is just a similar looking gcrypt API we directly pass through to.

Similarly, if we add a backend that delegates to the Linux kernel crypto API, then we'd just be doing a more or less straight passthrough with none of these switches.

Quoted 27 lines

The uses I pulled out of the later patches are like

(quoted diff) +20 -0
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {
+        return -EINVAL;
 
+    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,
+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {
 
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);
 
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
Quoted 2 lines

This one could have explicitly specified AES128, but you hid that behind G_N_ELEMENTS. Which seems like obfuscation to me, but...

In designing the APIs I was looking forward to uses beyond those shown in this current patch series. In particular with full disk encryption there will be a wide selection of algorithms that can be used with the implementation, so the caller of the APIs will not be passing in a fixed algorithm constant, but instead have it vary according to the data format. So on balance I think this current design is more future proof than what you suggest

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

Re: [Qemu-devel] [PATCH 04/10] crypto: introduce generic cipher API & built-in implementation

Quoted 79 lines · Daniel P. Berrange
Quoted 30 lines · Richard Henderson
Quoted 29 lines · Daniel P. Berrange
crypto/cipher-builtin.c new file +29 -0
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    switch (cipher->alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        if (qcrypto_cipher_init_des_rfb(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (qcrypto_cipher_init_aes(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    default:
+        error_setg(errp,
+                   _("Unsupported cipher algorithm %d"), cipher->alg);
+        goto error;
+    }
+
+    return cipher;
Quoted 8 lines

crypto/cipher-builtin.c line 320

Quoted 5 lines
crypto/cipher-builtin.c new file +5 -0
+
+ error:
+    g_free(cipher);
+    return NULL;
+}

Is it really that helpful to have all of these switches, as opposed to having one function per cipher and calling it directly? Similarly for the hashing.

These switches are just an artifact of this default built-in implementation where we're jumping off to one or our two built-in crypto algorithsm. The gcrypt backend of these APIs has no such switch, since there is just a similar looking gcrypt API we directly pass through to.

Similarly, if we add a backend that delegates to the Linux kernel crypto API, then we'd just be doing a more or less straight passthrough with none of these switches.

Quoted 27 lines

The uses I pulled out of the later patches are like

(quoted diff) +20 -0
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {
+        return -EINVAL;
 
+    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,
+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {
 
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);
 
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
Quoted 2 lines

This one could have explicitly specified AES128, but you hid that behind G_N_ELEMENTS. Which seems like obfuscation to me, but...

Quoted 8 lines

In designing the APIs I was looking forward to uses beyond those shown in this current patch series. In particular with full disk encryption there will be a wide selection of algorithms that can be used with the implementation, so the caller of the APIs will not be passing in a fixed algorithm constant, but instead have it vary according to the data format. So on balance I think this current design is more future proof than what you suggest

Form your code, we can see that exists many duplicate code about encryption and decryption, which have the same arguments, such as qcrypto_cipher_encrypt() and qcrypto_cipher_decrypt(). Can we just use an argument to check the operation is encryption or decryption, then invoke corresponding functions? In this way, it will decrease lots of duplicate code. IIRC OpenSSL EVP api do this work using this way.

Regards,
-Gonglei

#12 lore raw

Re: [Qemu-devel] [PATCH 04/10] crypto: introduce generic cipher API & built-in implementation

Quoted 89 lines · Gonglei
Quoted 79 lines · Daniel P. Berrange
Quoted 30 lines · Richard Henderson
Quoted 29 lines · Daniel P. Berrange
crypto/cipher-builtin.c new file +29 -0
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    switch (cipher->alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        if (qcrypto_cipher_init_des_rfb(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (qcrypto_cipher_init_aes(cipher, key, nkey, errp) < 0) {
+            goto error;
+        }
+        break;
+    default:
+        error_setg(errp,
+                   _("Unsupported cipher algorithm %d"), cipher->alg);
+        goto error;
+    }
+
+    return cipher;
Quoted 8 lines

crypto/cipher-builtin.c line 320

Quoted 5 lines
crypto/cipher-builtin.c new file +5 -0
+
+ error:
+    g_free(cipher);
+    return NULL;
+}

Is it really that helpful to have all of these switches, as opposed to having one function per cipher and calling it directly? Similarly for the hashing.

These switches are just an artifact of this default built-in implementation where we're jumping off to one or our two built-in crypto algorithsm. The gcrypt backend of these APIs has no such switch, since there is just a similar looking gcrypt API we directly pass through to.

Similarly, if we add a backend that delegates to the Linux kernel crypto API, then we'd just be doing a more or less straight passthrough with none of these switches.

Quoted 27 lines

The uses I pulled out of the later patches are like

(quoted diff) +20 -0
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {
+        return -EINVAL;
 
+    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,
+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {
 
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);
 
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
Quoted 2 lines

This one could have explicitly specified AES128, but you hid that behind G_N_ELEMENTS. Which seems like obfuscation to me, but...

Quoted 8 lines

In designing the APIs I was looking forward to uses beyond those shown in this current patch series. In particular with full disk encryption there will be a wide selection of algorithms that can be used with the implementation, so the caller of the APIs will not be passing in a fixed algorithm constant, but instead have it vary according to the data format. So on balance I think this current design is more future proof than what you suggest

Quoted 6 lines

Form your code, we can see that exists many duplicate code about encryption and decryption, which have the same arguments, such as qcrypto_cipher_encrypt() and qcrypto_cipher_decrypt(). Can we just use an argument to check the operation is encryption or decryption, then invoke corresponding functions? In this way, it will decrease lots of duplicate code. IIRC OpenSSL EVP api do this work using this way.

What you describe was done with the qcow2_encrypt_sectors() method, where it accepts an 'int enc' parameter to indicate whether it does encryption or decryption. In looking at the qcow2 code for encryption this is one of the things that I found rather unhelpful, as it makes it less obvious to the casual reader what is going on. Having the explicitly _encrypt() and _decrypt() APIs makes the code clearer to follow IMHO, and I don't think size difference in code is appreciable enough to counteract this benefit.

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 5/10 crypto: add a gcrypt cipher implementation

In reply to Daniel P. Berrange

If we are linking to gnutls already and gnutls is built against gcrypt, then we should use gcrypt as a cipher backend in preference to our built-in backend.

This will be used when linking against GNUTLS 1.x and many GNUTLS 2.x versions.

---
 configure              |  29 +++++++
 crypto/cipher-gcrypt.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++
 crypto/cipher.c        |   4 +
 crypto/init.c          |  90 ++++++++++++++++++++++
 4 files changed, 326 insertions(+)
 create mode 100644 crypto/cipher-gcrypt.c
configure +29 -0
index 6530e7a..6629346 100755
@@ -2162,6 +2162,7 @@ fi
 ##########################################
 # GNUTLS probe
 
+gnutls_gcrypt=no
 if test "$gnutls" != "no"; then
     if $pkg_config --exists "gnutls"; then
         gnutls_cflags=`$pkg_config --cflags gnutls`
@@ -2177,6 +2178,18 @@ if test "$gnutls" != "no"; then
 	else
 	    gnutls_hash="no"
 	fi
+
+	if $pkg_config --exists 'gnutls >= 3.0'; then
+	    gnutls_gcrypt=no
+	elif $pkg_config --exists 'gnutls >= 2.12'; then
+	    case `$pkg_config --libs --static gnutls` in
+		*gcrypt*) gnutls_gcrypt=yes     ;;
+		*nettle*) gnutls_gcrypt=no      ;;
+		*)        gnutls_gcrypt=yes     ;;
+	    esac
+	else
+	    gnutls_gcrypt=yes
+	fi
     elif test "$gnutls" = "yes"; then
 	feature_not_found "gnutls" "Install gnutls devel"
     else
@@ -2187,6 +2200,18 @@ else
     gnutls_hash="no"
 fi
 
+if test "$gnutls_gcrypt" != "no"; then
+    if has "libgcrypt-config"; then
+        gcrypt_cflags=`libgcrypt-config --cflags`
+        gcrypt_libs=`libgcrypt-config --libs`
+        libs_softmmu="$gcrypt_libs $libs_softmmu"
+        libs_tools="$gcrypt_libs $libs_tools"
+        QEMU_CFLAGS="$QEMU_CFLAGS $gcrypt_cflags"
+    else
+        feature_not_found "gcrypt" "Install gcrypt devel"
+    fi
+fi
+
 
 ##########################################
 # VTE probe
@@ -4433,6 +4458,7 @@ echo "SDL support       $sdl"
 echo "GTK support       $gtk"
 echo "GNUTLS support    $gnutls"
 echo "GNUTLS hash       $gnutls_hash"
+echo "GNUTLS gcrypt     $gnutls_gcrypt"
 echo "VTE support       $vte"
 echo "curses support    $curses"
 echo "curl support      $curl"
@@ -4791,6 +4817,9 @@ fi
 if test "$gnutls_hash" = "yes" ; then
   echo "CONFIG_GNUTLS_HASH=y" >> $config_host_mak
 fi
+if test "$gnutls_gcrypt" = "yes" ; then
+  echo "CONFIG_GNUTLS_GCRYPT=y" >> $config_host_mak
+fi
 if test "$vte" = "yes" ; then
   echo "CONFIG_VTE=y" >> $config_host_mak
   echo "VTE_CFLAGS=$vte_cflags" >> $config_host_mak
crypto/cipher-gcrypt.c new file +203 -0

203 lines not on this page · raw message

crypto/cipher.c +4 -0
index 71e9eae..dc140fb 100644
@@ -20,4 +20,8 @@
 
 #include "crypto/cipher.h"
 
+#ifdef CONFIG_GNUTLS_GCRYPT
+#include "crypto/cipher-gcrypt.c"
+#else
 #include "crypto/cipher-builtin.c"
+#endif
crypto/init.c +90 -0

116 lines not on this page · raw message

Signature · 1 line
2.1.0
#14 lore raw

Re: [Qemu-devel] [PATCH 05/10] crypto: add a gcrypt cipher implementation

Quoted 219 lines · Daniel P. Berrange

If we are linking to gnutls already and gnutls is built against gcrypt, then we should use gcrypt as a cipher backend in preference to our built-in backend.

This will be used when linking against GNUTLS 1.x and many GNUTLS 2.x versions.

---
 configure              |  29 +++++++
 crypto/cipher-gcrypt.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++
 crypto/cipher.c        |   4 +
 crypto/init.c          |  90 ++++++++++++++++++++++
 4 files changed, 326 insertions(+)
 create mode 100644 crypto/cipher-gcrypt.c
configure +29 -0
index 6530e7a..6629346 100755
@@ -2162,6 +2162,7 @@ fi
 ##########################################
 # GNUTLS probe
 
+gnutls_gcrypt=no
 if test "$gnutls" != "no"; then
     if $pkg_config --exists "gnutls"; then
         gnutls_cflags=`$pkg_config --cflags gnutls`
@@ -2177,6 +2178,18 @@ if test "$gnutls" != "no"; then
 	else
 	    gnutls_hash="no"
 	fi
+
+	if $pkg_config --exists 'gnutls >= 3.0'; then
+	    gnutls_gcrypt=no
+	elif $pkg_config --exists 'gnutls >= 2.12'; then
+	    case `$pkg_config --libs --static gnutls` in
+		*gcrypt*) gnutls_gcrypt=yes     ;;
+		*nettle*) gnutls_gcrypt=no      ;;
+		*)        gnutls_gcrypt=yes     ;;
+	    esac
+	else
+	    gnutls_gcrypt=yes
+	fi
     elif test "$gnutls" = "yes"; then
 	feature_not_found "gnutls" "Install gnutls devel"
     else
@@ -2187,6 +2200,18 @@ else
     gnutls_hash="no"
 fi
 
+if test "$gnutls_gcrypt" != "no"; then
+    if has "libgcrypt-config"; then
+        gcrypt_cflags=`libgcrypt-config --cflags`
+        gcrypt_libs=`libgcrypt-config --libs`
+        libs_softmmu="$gcrypt_libs $libs_softmmu"
+        libs_tools="$gcrypt_libs $libs_tools"
+        QEMU_CFLAGS="$QEMU_CFLAGS $gcrypt_cflags"
+    else
+        feature_not_found "gcrypt" "Install gcrypt devel"
+    fi
+fi
+
 
 ##########################################
 # VTE probe
@@ -4433,6 +4458,7 @@ echo "SDL support       $sdl"
 echo "GTK support       $gtk"
 echo "GNUTLS support    $gnutls"
 echo "GNUTLS hash       $gnutls_hash"
+echo "GNUTLS gcrypt     $gnutls_gcrypt"
 echo "VTE support       $vte"
 echo "curses support    $curses"
 echo "curl support      $curl"
@@ -4791,6 +4817,9 @@ fi
 if test "$gnutls_hash" = "yes" ; then
   echo "CONFIG_GNUTLS_HASH=y" >> $config_host_mak
 fi
+if test "$gnutls_gcrypt" = "yes" ; then
+  echo "CONFIG_GNUTLS_GCRYPT=y" >> $config_host_mak
+fi
 if test "$vte" = "yes" ; then
   echo "CONFIG_VTE=y" >> $config_host_mak
   echo "VTE_CFLAGS=$vte_cflags" >> $config_host_mak
crypto/cipher-gcrypt.c new file +129 -0
new file mode 100644
index 0000000..624a4f8
@@ -0,0 +1,203 @@
+/*
+ * QEMU Crypto cipher libgcrypt algorithms
+ *
+ * Copyright (c) 2015 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 <glib/gi18n.h>
+#include <gcrypt.h>
+
+
+static uint8_t *qcrypto_cipher_munge_des_rfb_key(const uint8_t *key,
+                                                 size_t nkey)
+{
+    uint8_t *ret = g_new0(uint8_t, nkey);
+    size_t i;
+    for (i = 0; i < nkey; i++) {
+        uint8_t r = key[i];
+        r = (r & 0xf0) >> 4 | (r & 0x0f) << 4;
+        r = (r & 0xcc) >> 2 | (r & 0x33) << 2;
+        r = (r & 0xaa) >> 1 | (r & 0x55) << 1;
+        ret[i] = r;
+    }
+    return ret;
+}
+
+bool qcrypto_cipher_supports(QCryptoCipherAlgorithm alg)
+{
+    if (alg == QCRYPTO_CIPHER_ALG_DES_RFB ||
+        alg == QCRYPTO_CIPHER_ALG_AES) {
+        return true;
+    }
+    return false;
+}
+
+
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+    gcry_cipher_hd_t handle;
+    gcry_error_t err;
+    int gcryalg, gcrymode;
+
+    switch (mode) {
+    case QCRYPTO_CIPHER_MODE_ECB:
+        gcrymode = GCRY_CIPHER_MODE_ECB;
+        break;
+    case QCRYPTO_CIPHER_MODE_CBC:
+        gcrymode = GCRY_CIPHER_MODE_CBC;
+        break;
+    default:
+        error_setg(errp, _("Unsupported cipher mode %d"), mode);
+        return NULL;
+    }
+
+    switch (alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        gcryalg = GCRY_CIPHER_DES;
+        break;
+
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (nkey == 16) {
+            gcryalg = GCRY_CIPHER_AES128;
+        } else if (nkey == 24) {
+            gcryalg = GCRY_CIPHER_AES192;
+        } else if (nkey == 32) {
+            gcryalg = GCRY_CIPHER_AES256;
+        } else {
+            error_setg(errp, _("Expected key size 16, 24 or 32 not %zu"),
+                       nkey);
+            return NULL;
+        }
+        break;
+
+    default:
+        error_setg(errp, _("Unsupported cipher algorithm %d"), alg);
+        return NULL;
+    }
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    err = gcry_cipher_open(&handle, gcryalg, gcrymode, 0);
+    if (err != 0) {
+        error_setg(errp, _("Cannot initialize cipher: %s"),
+                   gcry_strerror(err));
+        goto error;
+    }
+
+    if (cipher->alg == QCRYPTO_CIPHER_ALG_DES_RFB) {
+        /* We're using standard DES cipher from gcrypt, so we need
+         * to munge the key so that the results are the same as the
+         * bizarre RFB variant of DES :-)
+         */
+        uint8_t *rfbkey = qcrypto_cipher_munge_des_rfb_key(key, nkey);
+        err = gcry_cipher_setkey(handle, rfbkey, nkey);
+        g_free(rfbkey);
+    } else {
+        err = gcry_cipher_setkey(handle, key, nkey);
+    }
+    if (err != 0) {
+        error_setg(errp, _("Cannot set key: %s"),
+                   gcry_strerror(err));
+        goto error;
+    }
+
+    cipher->opaque = handle;
+    return cipher;
+
+ error:
+    gcry_cipher_close(handle);
+    g_free(cipher);

crypto/cipher-gcrypt.c line 139

Quoted 10 lines
crypto/cipher-gcrypt.c new file +10 -0
+    return NULL;
+}
+
+
+void qcrypto_cipher_free(QCryptoCipher *cipher)
+{
+    if (!cipher) {
+        return;
+    }
+    gcry_cipher_close(cipher->opaque);

Maybe it's better cast cipher->opaque to gcry_cipher_hd_t like other free functions.

gcry_cipher_hd_t handle = cipher->opaque;

Quoted 183 lines
crypto/cipher-gcrypt.c new file +64 -0
+    g_free(cipher);
+}
+
+
+int qcrypto_cipher_encrypt(QCryptoCipher *cipher,
+                           const void *in,
+                           void *out,
+                           size_t len,
+                           Error **errp)
+{
+    gcry_cipher_hd_t handle = cipher->opaque;
+    gcry_error_t err;
+
+    err = gcry_cipher_encrypt(handle,
+                              out, len,
+                              in, len);
+    if (err != 0) {
+        error_setg(errp, _("Cannot encrypt data: %s"),
+                   gcry_strerror(err));
+        return -1;
+    }
+
+    return 0;
+}
+
+
+int qcrypto_cipher_decrypt(QCryptoCipher *cipher,
+                           const void *in,
+                           void *out,
+                           size_t len,
+                           Error **errp)
+{
+    gcry_cipher_hd_t handle = cipher->opaque;
+    gcry_error_t err;
+
+    err = gcry_cipher_decrypt(handle,
+                              out, len,
+                              in, len);
+    if (err != 0) {
+        error_setg(errp, _("Cannot decrypt data: %s"),
+                   gcry_strerror(err));
+        return -1;
+    }
+
+    return 0;
+}
+
+int qcrypto_cipher_setiv(QCryptoCipher *cipher,
+                         const uint8_t *iv, size_t niv,
+                         Error **errp)
+{
+    gcry_cipher_hd_t handle = cipher->opaque;
+    gcry_error_t err;
+
+    gcry_cipher_reset(handle);
+    err = gcry_cipher_setiv(handle, iv, niv);
+    if (err != 0) {
+        error_setg(errp, _("Cannot set IV: %s"),
+                   gcry_strerror(err));
+        return -1;
+    }
+
+    return 0;
+}
crypto/cipher.c +4 -0
index 71e9eae..dc140fb 100644
@@ -20,4 +20,8 @@
 
 #include "crypto/cipher.h"
 
+#ifdef CONFIG_GNUTLS_GCRYPT
+#include "crypto/cipher-gcrypt.c"
+#else
 #include "crypto/cipher-builtin.c"
+#endif
crypto/init.c +78 -0
index 8fd66d4..486af37 100644
@@ -19,6 +19,7 @@
  */
 
 #include "crypto/init.h"
+#include "qemu/thread.h"
 
 #include <glib/gi18n.h>
 
@@ -26,8 +27,42 @@
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
 
+#ifdef CONFIG_GNUTLS_GCRYPT
+#include <gcrypt.h>
+#endif
+
 /* #define DEBUG_GNUTLS */
 
+/*
+ * If GNUTLS is built against GCrypt then
+ *
+ *  - When GNUTLS >= 2.12, we must not initialize gcrypt threading
+ *    because GNUTLS will do that itself
+ *  - When GNUTLS < 2.12 we must always initialize gcrypt threading
+ *
+ * But....
+ *
+ *    When gcrypt >= 1.6.0 we must not initialize gcrypt threading
+ *    because gcrypt will do that itself.
+ *
+ * So we need to init gcrypt threading if
+ *
+ *   - gcrypt < 1.6.0
+ * AND
+ *   - gnutls < 2.12
+ *
+ */
+
+#if (defined(CONFIG_GNUTLS_GCRYPT) &&           \
+     (!defined(GNUTLS_VERSION_NUMBER) ||        \
+      (GNUTLS_VERSION_NUMBER < 0x020c00)) &&    \
+     (!defined(GCRYPT_VERSION_NUMBER) ||        \
+      (GCRYPT_VERSION_NUMBER < 0x010600)))
+#define QCRYPTO_INIT_GCRYPT_THREADS
+#else
+#undef QCRYPTO_INIT_GCRYPT_THREADS
+#endif
+
 #ifdef DEBUG_GNUTLS
 static void qcrypto_gnutls_log(int level, const char *str)
 {
@@ -35,6 +70,49 @@ static void qcrypto_gnutls_log(int level, const char *str)
 }
 #endif
 
+#ifdef QCRYPTO_INIT_GCRYPT_THREADS
+static int qcrypto_gcrypt_mutex_init(void **priv)
+{                                                                             \
+    QemuMutex *lock = NULL;
+    lock = g_new0(QemuMutex, 1);
+    qemu_mutex_init(lock);
+    *priv = lock;
+    return 0;
+}
+
+static int qcrypto_gcrypt_mutex_destroy(void **priv)
+{
+    QemuMutex *lock = *priv;
+    qemu_mutex_destroy(lock);
+    g_free(lock);
+    return 0;
+}
+
+static int qcrypto_gcrypt_mutex_lock(void **priv)
+{
+    QemuMutex *lock = *priv;
+    qemu_mutex_lock(lock);
+    return 0;
+}
+
+static int qcrypto_gcrypt_mutex_unlock(void **priv)
+{
+    QemuMutex *lock = *priv;
+    qemu_mutex_unlock(lock);
+    return 0;
+}
+
+static struct gcry_thread_cbs qcrypto_gcrypt_thread_impl = {
+    (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
+    NULL,
+    qcrypto_gcrypt_mutex_init,
+    qcrypto_gcrypt_mutex_destroy,
+    qcrypto_gcrypt_mutex_lock,
+    qcrypto_gcrypt_mutex_unlock,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+};
+#endif /* QCRYPTO_INIT_GCRYPT */
+
 int qcrypto_init(Error **errp)
 {
     int ret;

crypto/init.c int qcrypto_init(Error **errp) · line 134

Quoted 8 lines
crypto/init.c +5 -0
@@ -49,6 +127,18 @@ int qcrypto_init(Error **errp)
     gnutls_global_set_log_level(10);
     gnutls_global_set_log_function(qcrypto_gnutls_log);
 #endif
+
+#ifdef CONFIG_GNUTLS_GCRYPT
+    if (!gcry_check_version(GCRYPT_VERSION)) {
+        error_setg(errp, "%s", _("Unable to initialize gcrypt"));
+        return -1;

Missing to call gnutls_global_deinit().

Regards,
-Gonglei

Quoted 11 lines
crypto/init.c +7 -0
+    }
+#ifdef QCRYPTO_INIT_GCRYPT_THREADS
+    gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);
+#endif /* QCRYPTO_INIT_GCRYPT_THREADS */
+    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
+#endif
+
     return 0;
 }
 
#15 lore raw

Re: [Qemu-devel] [PATCH 05/10] crypto: add a gcrypt cipher implementation

Quoted 104 lines · Gonglei
Quoted 90 lines · Daniel P. Berrange

If we are linking to gnutls already and gnutls is built against gcrypt, then we should use gcrypt as a cipher backend in preference to our built-in backend.

This will be used when linking against GNUTLS 1.x and many GNUTLS 2.x versions.

crypto/cipher-gcrypt.c new file +80 -0
+QCryptoCipher *qcrypto_cipher_new(QCryptoCipherAlgorithm alg,
+                                  QCryptoCipherMode mode,
+                                  const uint8_t *key, size_t nkey,
+                                  Error **errp)
+{
+    QCryptoCipher *cipher;
+    gcry_cipher_hd_t handle;
+    gcry_error_t err;
+    int gcryalg, gcrymode;
+
+    switch (mode) {
+    case QCRYPTO_CIPHER_MODE_ECB:
+        gcrymode = GCRY_CIPHER_MODE_ECB;
+        break;
+    case QCRYPTO_CIPHER_MODE_CBC:
+        gcrymode = GCRY_CIPHER_MODE_CBC;
+        break;
+    default:
+        error_setg(errp, _("Unsupported cipher mode %d"), mode);
+        return NULL;
+    }
+
+    switch (alg) {
+    case QCRYPTO_CIPHER_ALG_DES_RFB:
+        gcryalg = GCRY_CIPHER_DES;
+        break;
+
+    case QCRYPTO_CIPHER_ALG_AES:
+        if (nkey == 16) {
+            gcryalg = GCRY_CIPHER_AES128;
+        } else if (nkey == 24) {
+            gcryalg = GCRY_CIPHER_AES192;
+        } else if (nkey == 32) {
+            gcryalg = GCRY_CIPHER_AES256;
+        } else {
+            error_setg(errp, _("Expected key size 16, 24 or 32 not %zu"),
+                       nkey);
+            return NULL;
+        }
+        break;
+
+    default:
+        error_setg(errp, _("Unsupported cipher algorithm %d"), alg);
+        return NULL;
+    }
+
+    cipher = g_new0(QCryptoCipher, 1);
+    cipher->alg = alg;
+    cipher->mode = mode;
+
+    err = gcry_cipher_open(&handle, gcryalg, gcrymode, 0);
+    if (err != 0) {
+        error_setg(errp, _("Cannot initialize cipher: %s"),
+                   gcry_strerror(err));
+        goto error;
+    }
+
+    if (cipher->alg == QCRYPTO_CIPHER_ALG_DES_RFB) {
+        /* We're using standard DES cipher from gcrypt, so we need
+         * to munge the key so that the results are the same as the
+         * bizarre RFB variant of DES :-)
+         */
+        uint8_t *rfbkey = qcrypto_cipher_munge_des_rfb_key(key, nkey);
+        err = gcry_cipher_setkey(handle, rfbkey, nkey);
+        g_free(rfbkey);
+    } else {
+        err = gcry_cipher_setkey(handle, key, nkey);
+    }
+    if (err != 0) {
+        error_setg(errp, _("Cannot set key: %s"),
+                   gcry_strerror(err));
+        goto error;
+    }
+
+    cipher->opaque = handle;
+    return cipher;
+
+ error:
+    gcry_cipher_close(handle);
+    g_free(cipher);

crypto/cipher-gcrypt.c line 139

Quoted 10 lines
crypto/cipher-gcrypt.c new file +10 -0
+    return NULL;
+}
+
+
+void qcrypto_cipher_free(QCryptoCipher *cipher)
+{
+    if (!cipher) {
+        return;
+    }
+    gcry_cipher_close(cipher->opaque);

Maybe it's better cast cipher->opaque to gcry_cipher_hd_t like other free functions.

Quoted 1 line

gcry_cipher_hd_t handle = cipher->opaque;

Yes, that would make it a little clearer to follow.

Quoted 17 lines
Quoted 17 lines
crypto/init.c +11 -0
+static struct gcry_thread_cbs qcrypto_gcrypt_thread_impl = {
+    (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
+    NULL,
+    qcrypto_gcrypt_mutex_init,
+    qcrypto_gcrypt_mutex_destroy,
+    qcrypto_gcrypt_mutex_lock,
+    qcrypto_gcrypt_mutex_unlock,
+    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+};
+#endif /* QCRYPTO_INIT_GCRYPT */
+
 int qcrypto_init(Error **errp)
 {
     int ret;
@@ -49,6 +127,18 @@ int qcrypto_init(Error **errp)
     gnutls_global_set_log_level(10);
     gnutls_global_set_log_function(qcrypto_gnutls_log);
Quoted 8 lines

crypto/init.c int qcrypto_init(Error **errp) · line 134

Quoted 6 lines
crypto/init.c +5 -0
 #endif
+
+#ifdef CONFIG_GNUTLS_GCRYPT
+    if (!gcry_check_version(GCRYPT_VERSION)) {
+        error_setg(errp, "%s", _("Unable to initialize gcrypt"));
+        return -1;

Missing to call gnutls_global_deinit().

The gnutls_global_init/deinit functions are not threadsafe, so although it would be safe todo in this case, as a general rule it is preferrable to avoid ever using the gnutls_global_deinit() function in threaded apps, as you never know what background threads are using gnutls.

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

PATCH 6/10 crypto: add a nettle cipher implementation

In reply to Daniel P. Berrange

If we are linking to gnutls already and gnutls is built against nettle, then we should use nettle as a cipher backend in preference to our built-in backend.

This will be used when linking against some GNUTLS 2.x versions and all GNUTLS 3.x versions.

---
 configure              |  35 +++++++-
 crypto/cipher-nettle.c | 226 +++++++++++++++++++++++++++++++++++++++++++++++++
 crypto/cipher.c        |   4 +
 3 files changed, 262 insertions(+), 3 deletions(-)
 create mode 100644 crypto/cipher-nettle.c
configure +32 -3
index 6629346..a48aa90 100755
@@ -2163,6 +2163,7 @@ fi
 # GNUTLS probe
 
 gnutls_gcrypt=no
+gnutls_nettle=no
 if test "$gnutls" != "no"; then
     if $pkg_config --exists "gnutls"; then
         gnutls_cflags=`$pkg_config --cflags gnutls`
@@ -2181,14 +2182,25 @@ if test "$gnutls" != "no"; then
 
 	if $pkg_config --exists 'gnutls >= 3.0'; then
 	    gnutls_gcrypt=no
+	    gnutls_nettle=yes
 	elif $pkg_config --exists 'gnutls >= 2.12'; then
 	    case `$pkg_config --libs --static gnutls` in
-		*gcrypt*) gnutls_gcrypt=yes     ;;
-		*nettle*) gnutls_gcrypt=no      ;;
-		*)        gnutls_gcrypt=yes     ;;
+		*gcrypt*)
+		    gnutls_gcrypt=yes
+		    gnutls_nettle=no
+		    ;;
+		*nettle*)
+		    gnutls_gcrypt=no
+		    gnutls_nettle=yes
+		    ;;
+		*)
+		    gnutls_gcrypt=yes
+		    gnutls_nettle=no
+		    ;;
 	    esac
 	else
 	    gnutls_gcrypt=yes
+	    gnutls_nettle=no
 	fi
     elif test "$gnutls" = "yes"; then
 	feature_not_found "gnutls" "Install gnutls devel"
@@ -2213,6 +2225,19 @@ if test "$gnutls_gcrypt" != "no"; then
 fi
 
 
+if test "$gnutls_nettle" != "no"; then
+    if $pkg_config --exists "nettle"; then
+        nettle_cflags=`$pkg_config --cflags nettle`
+        nettle_libs=`$pkg_config --libs nettle`
+        libs_softmmu="$nettle_libs $libs_softmmu"
+        libs_tools="$nettle_libs $libs_tools"
+        QEMU_CFLAGS="$QEMU_CFLAGS $nettle_cflags"
+    else
+        feature_not_found "nettle" "Install nettle devel"
+    fi
+fi
+
+
 ##########################################
 # VTE probe
 
@@ -4459,6 +4484,7 @@ echo "GTK support       $gtk"
 echo "GNUTLS support    $gnutls"
 echo "GNUTLS hash       $gnutls_hash"
 echo "GNUTLS gcrypt     $gnutls_gcrypt"
+echo "GNUTLS nettle     $gnutls_nettle"
 echo "VTE support       $vte"
 echo "curses support    $curses"
 echo "curl support      $curl"
@@ -4820,6 +4846,9 @@ fi
 if test "$gnutls_gcrypt" = "yes" ; then
   echo "CONFIG_GNUTLS_GCRYPT=y" >> $config_host_mak
 fi
+if test "$gnutls_nettle" = "yes" ; then
+  echo "CONFIG_GNUTLS_NETTLE=y" >> $config_host_mak
+fi
 if test "$vte" = "yes" ; then
   echo "CONFIG_VTE=y" >> $config_host_mak
   echo "VTE_CFLAGS=$vte_cflags" >> $config_host_mak
crypto/cipher-nettle.c new file +226 -0

226 lines not on this page · raw message

crypto/cipher.c +4 -0
index dc140fb..3299a7a 100644
@@ -23,5 +23,9 @@
 #ifdef CONFIG_GNUTLS_GCRYPT
 #include "crypto/cipher-gcrypt.c"
 #else
+#ifdef CONFIG_GNUTLS_NETTLE
+#include "crypto/cipher-nettle.c"
+#else
 #include "crypto/cipher-builtin.c"
 #endif
+#endif
Signature · 1 line
2.1.0
#17 lore raw

Re: [Qemu-devel] [PATCH 06/10] crypto: add a nettle cipher implementation

crypto/cipher.c line 31

Quoted 9 lines · Daniel P. Berrange

#ifdef CONFIG_GNUTLS_GCRYPT
#include "crypto/cipher-gcrypt.c"
#else

crypto/cipher.c +4 -0
+#ifdef CONFIG_GNUTLS_NETTLE
+#include "crypto/cipher-nettle.c"
+#else
 #include "crypto/cipher-builtin.c"
 #endif
+#endif

#elif, please.

r~

#18 lore raw

Re: [Qemu-devel] [PATCH 06/10] crypto: add a nettle cipher implementation

Quoted 13 lines · Richard Henderson

crypto/cipher.c line 31

Quoted 9 lines · Daniel P. Berrange

#ifdef CONFIG_GNUTLS_GCRYPT
#include "crypto/cipher-gcrypt.c"
#else

crypto/cipher.c +4 -0
+#ifdef CONFIG_GNUTLS_NETTLE
+#include "crypto/cipher-nettle.c"
+#else
 #include "crypto/cipher-builtin.c"
 #endif
+#endif

#elif, please.

Yes, it's better.

Regards,
-Gonglei

#19 lore raw

Re: [Qemu-devel] [PATCH 06/10] crypto: add a nettle cipher implementation

In reply to Daniel P. Berrange
Quoted 5 lines · Daniel P. Berrange
crypto/cipher-nettle.c new file +5 -0
+static uint8_t *qcrypto_cipher_munge_des_rfb_key(const uint8_t *key,
+                                                 size_t nkey)
+{
+    uint8_t *ret = g_new0(uint8_t, nkey);
+    size_t i;

crypto/cipher-nettle.c line 53

Quoted 10 lines
crypto/cipher-nettle.c new file +10 -0
+    for (i = 0; i < nkey; i++) {
+        uint8_t r = key[i];
+        r = (r & 0xf0)>>4 | (r & 0x0f)<<4;
+        r = (r & 0xcc)>>2 | (r & 0x33)<<2;
+        r = (r & 0xaa)>>1 | (r & 0x55)<<1;
+        ret[i] = r;
+    }
+    return ret;
+}
+

Surely you can share this between the gcrypt and nettle files and not duplicate it...

r~

#20 lore raw

Re: [Qemu-devel] [PATCH 06/10] crypto: add a nettle cipher implementation

Quoted 11 lines · Richard Henderson
Quoted 10 lines · Daniel P. Berrange
crypto/cipher-nettle.c new file +10 -0
+static uint8_t *qcrypto_cipher_munge_des_rfb_key(const uint8_t *key,
+                                                 size_t nkey)
+{
+    uint8_t *ret = g_new0(uint8_t, nkey);
+    size_t i;
+    for (i = 0; i < nkey; i++) {
+        uint8_t r = key[i];
+        r = (r & 0xf0)>>4 | (r & 0x0f)<<4;
+        r = (r & 0xcc)>>2 | (r & 0x33)<<2;
+        r = (r & 0xaa)>>1 | (r & 0x55)<<1;
Quoted 8 lines

crypto/cipher-nettle.c line 53

Quoted 5 lines
crypto/cipher-nettle.c new file +5 -0
+        ret[i] = r;
+    }
+    return ret;
+}
+

Surely you can share this between the gcrypt and nettle files and not duplicate it...

Potentially, but it was small enough that I felt it not worth the bother of introducing another file for sharing it. The copyright header on a new file would be larger than the amount of code shared in a new file.

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

PATCH 7/10 block: convert quorum blockdrv to use crypto APIs

In reply to Daniel P. Berrange

Get rid of direct use of gnutls APIs in quorum blockdrv in favour of using the crypto APIs. This avoids the need to do conditional compilation of the quorum driver. It can simply report an error at file open file instead if the required hash algorithm isn't supported by QEMU.

---
 block/Makefile.objs |  2 +-
 block/quorum.c      | 38 +++++++++++++++++++-------------------
 configure           | 39 ---------------------------------------
 3 files changed, 20 insertions(+), 59 deletions(-)
block/Makefile.objs +1 -1
index 0d8c2a4..8f908d9 100644
@@ -3,7 +3,7 @@ block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-c
 block-obj-y += qed.o qed-gencb.o qed-l2-cache.o qed-table.o qed-cluster.o
 block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
-block-obj-$(CONFIG_QUORUM) += quorum.o
+block-obj-y += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
 block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
block/quorum.c +19 -19
index f91ef75..4193f30 100644
@@ -13,8 +13,6 @@
  * See the COPYING file in the top-level directory.
  */
 
-#include <gnutls/gnutls.h>
-#include <gnutls/crypto.h>
 #include "block/block_int.h"
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qdict.h"
@@ -23,6 +21,9 @@
 #include "qapi/qmp/qlist.h"
 #include "qapi/qmp/qstring.h"
 #include "qapi-event.h"
+#include "crypto/hash.h"
+
+#include <glib/gi18n.h>
 
 #define HASH_LENGTH 32
 
@@ -33,7 +34,7 @@
 
 /* This union holds a vote hash value */
 typedef union QuorumVoteValue {
-    char h[HASH_LENGTH];       /* SHA-256 hash */
+    uint8_t h[HASH_LENGTH];    /* SHA-256 hash */
     int64_t l;                 /* simpler 64 bits hash */
 } QuorumVoteValue;
 
@@ -427,25 +428,18 @@ static void quorum_free_vote_list(QuorumVotes *votes)
 
 static int quorum_compute_hash(QuorumAIOCB *acb, int i, QuorumVoteValue *hash)
 {
-    int j, ret;
-    gnutls_hash_hd_t dig;
     QEMUIOVector *qiov = &acb->qcrs[i].qiov;
-
-    ret = gnutls_hash_init(&dig, GNUTLS_DIG_SHA256);
-
-    if (ret < 0) {
-        return ret;
+    size_t len = sizeof(hash->h);
+    uint8_t *data = hash->h;
+
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {
+        return -EINVAL;
     }
 
-    for (j = 0; j < qiov->niov; j++) {
-        ret = gnutls_hash(dig, qiov->iov[j].iov_base, qiov->iov[j].iov_len);
-        if (ret < 0) {
-            break;
-        }
-    }
-
-    gnutls_hash_deinit(dig, (void *) hash);
-    return ret;
+    return 0;
 }
 
 static QuorumVoteVersion *quorum_get_vote_winner(QuorumVotes *votes)
@@ -872,6 +866,12 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
     int i;
     int ret = 0;
 
+    if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA256)) {
+        error_setg(errp, "%s",
+                   _("SHA256 hash support is required for quorum device"));
+        return -EINVAL;
+    }
+
     qdict_flatten(options);
     qdict_extract_subqdict(options, &sub, "children.");
     qdict_array_split(sub, &list);
configure +0 -39
index a48aa90..cc60f0b 100755
@@ -336,7 +336,6 @@ vte=""
 tpm="yes"
 libssh2=""
 vhdx=""
-quorum=""
 numa=""
 tcmalloc="no"
 
@@ -1133,10 +1132,6 @@ for opt do
   ;;
   --disable-vhdx) vhdx="no"
   ;;
-  --disable-quorum) quorum="no"
-  ;;
-  --enable-quorum) quorum="yes"
-  ;;
   --disable-numa) numa="no"
   ;;
   --enable-numa) numa="yes"
@@ -1416,8 +1411,6 @@ Advanced options (experts only):
   --enable-libssh2         enable ssh block device support
   --disable-vhdx           disable support for the Microsoft VHDX image format
   --enable-vhdx            enable support for the Microsoft VHDX image format
-  --disable-quorum         disable quorum block filter support
-  --enable-quorum          enable quorum block filter support
   --disable-numa           disable libnuma support
   --enable-numa            enable libnuma support
   --disable-tcmalloc       disable tcmalloc support
@@ -2414,33 +2407,6 @@ EOF
 fi
 
 ##########################################
-# Quorum probe (check for gnutls)
-if test "$quorum" != "no" ; then
-cat > $TMPC <<EOF
-#include <gnutls/gnutls.h>
-#include <gnutls/crypto.h>
-int main(void) {char data[4096], digest[32];
-gnutls_hash_fast(GNUTLS_DIG_SHA256, data, 4096, digest);
-return 0;
-}
-EOF
-quorum_tls_cflags=`$pkg_config --cflags gnutls 2> /dev/null`
-quorum_tls_libs=`$pkg_config --libs gnutls 2> /dev/null`
-if compile_prog "$quorum_tls_cflags" "$quorum_tls_libs" ; then
-  qcow_tls=yes
-  libs_softmmu="$quorum_tls_libs $libs_softmmu"
-  libs_tools="$quorum_tls_libs $libs_softmmu"
-  QEMU_CFLAGS="$QEMU_CFLAGS $quorum_tls_cflags"
-  quorum="yes"
-else
-  if test "$quorum" = "yes"; then
-    feature_not_found "gnutls" "gnutls > 2.10.0 required to compile Quorum"
-  fi
-  quorum="no"
-fi
-fi
-
-##########################################
 # VNC SASL detection
 if test "$vnc" = "yes" -a "$vnc_sasl" != "no" ; then
   cat > $TMPC <<EOF
@@ -4562,7 +4528,6 @@ echo "libssh2 support   $libssh2"
 echo "TPM passthrough   $tpm_passthrough"
 echo "QOM debugging     $qom_cast_debug"
 echo "vhdx              $vhdx"
-echo "Quorum            $quorum"
 echo "lzo support       $lzo"
 echo "snappy support    $snappy"
 echo "bzip2 support     $bzip2"
@@ -5038,10 +5003,6 @@ if test "$libssh2" = "yes" ; then
   echo "LIBSSH2_LIBS=$libssh2_libs" >> $config_host_mak
 fi
 
-if test "$quorum" = "yes" ; then
-  echo "CONFIG_QUORUM=y" >> $config_host_mak
-fi
-
 if test "$vhdx" = "yes" ; then
   echo "CONFIG_VHDX=y" >> $config_host_mak
 fi
Signature · 1 line
2.1.0
#22 lore raw

Re: [Qemu-devel] [PATCH 07/10] block: convert quorum blockdrv to use crypto APIs

Quoted 67 lines · Daniel P. Berrange

Get rid of direct use of gnutls APIs in quorum blockdrv in favour of using the crypto APIs. This avoids the need to do conditional compilation of the quorum driver. It can simply report an error at file open file instead if the required hash algorithm isn't supported by QEMU.

---
 block/Makefile.objs |  2 +-
 block/quorum.c      | 38 +++++++++++++++++++-------------------
 configure           | 39 ---------------------------------------
 3 files changed, 20 insertions(+), 59 deletions(-)
block/Makefile.objs +1 -1
index 0d8c2a4..8f908d9 100644
@@ -3,7 +3,7 @@ block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-c
 block-obj-y += qed.o qed-gencb.o qed-l2-cache.o qed-table.o qed-cluster.o
 block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
-block-obj-$(CONFIG_QUORUM) += quorum.o
+block-obj-y += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
 block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
block/quorum.c +4 -7
index f91ef75..4193f30 100644
@@ -13,8 +13,6 @@
  * See the COPYING file in the top-level directory.
  */
 
-#include <gnutls/gnutls.h>
-#include <gnutls/crypto.h>
 #include "block/block_int.h"
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qdict.h"
@@ -23,6 +21,9 @@
 #include "qapi/qmp/qlist.h"
 #include "qapi/qmp/qstring.h"
 #include "qapi-event.h"
+#include "crypto/hash.h"
+
+#include <glib/gi18n.h>
 
 #define HASH_LENGTH 32
 
@@ -33,7 +34,7 @@
 
 /* This union holds a vote hash value */
 typedef union QuorumVoteValue {
-    char h[HASH_LENGTH];       /* SHA-256 hash */
+    uint8_t h[HASH_LENGTH];    /* SHA-256 hash */
     int64_t l;                 /* simpler 64 bits hash */
 } QuorumVoteValue;
 
@@ -427,25 +428,18 @@ static void quorum_free_vote_list(QuorumVotes *votes)
 
 static int quorum_compute_hash(QuorumAIOCB *acb, int i, QuorumVoteValue *hash)
 {
-    int j, ret;
-    gnutls_hash_hd_t dig;
     QEMUIOVector *qiov = &acb->qcrs[i].qiov;
-
-    ret = gnutls_hash_init(&dig, GNUTLS_DIG_SHA256);

block/quorum.c static void quorum_free_vote_list(QuorumVotes *votes) · line 438

Quoted 10 lines
block/quorum.c +7 -3
-
-    if (ret < 0) {
-        return ret;
+    size_t len = sizeof(hash->h);
+    uint8_t *data = hash->h;
+
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {

The last argument should not be NULL, maybe miss error message.

Regards,
-Gonglei

Quoted 115 lines
block/quorum.c +8 -9
+        return -EINVAL;
     }
 
-    for (j = 0; j < qiov->niov; j++) {
-        ret = gnutls_hash(dig, qiov->iov[j].iov_base, qiov->iov[j].iov_len);
-        if (ret < 0) {
-            break;
-        }
-    }
-
-    gnutls_hash_deinit(dig, (void *) hash);
-    return ret;
+    return 0;
 }
 
 static QuorumVoteVersion *quorum_get_vote_winner(QuorumVotes *votes)
@@ -872,6 +866,12 @@ static int quorum_open(BlockDriverState *bs, QDict *options, int flags,
     int i;
     int ret = 0;
 
+    if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA256)) {
+        error_setg(errp, "%s",
+                   _("SHA256 hash support is required for quorum device"));
+        return -EINVAL;
+    }
+
     qdict_flatten(options);
     qdict_extract_subqdict(options, &sub, "children.");
     qdict_array_split(sub, &list);
configure +0 -39
index a48aa90..cc60f0b 100755
@@ -336,7 +336,6 @@ vte=""
 tpm="yes"
 libssh2=""
 vhdx=""
-quorum=""
 numa=""
 tcmalloc="no"
 
@@ -1133,10 +1132,6 @@ for opt do
   ;;
   --disable-vhdx) vhdx="no"
   ;;
-  --disable-quorum) quorum="no"
-  ;;
-  --enable-quorum) quorum="yes"
-  ;;
   --disable-numa) numa="no"
   ;;
   --enable-numa) numa="yes"
@@ -1416,8 +1411,6 @@ Advanced options (experts only):
   --enable-libssh2         enable ssh block device support
   --disable-vhdx           disable support for the Microsoft VHDX image format
   --enable-vhdx            enable support for the Microsoft VHDX image format
-  --disable-quorum         disable quorum block filter support
-  --enable-quorum          enable quorum block filter support
   --disable-numa           disable libnuma support
   --enable-numa            enable libnuma support
   --disable-tcmalloc       disable tcmalloc support
@@ -2414,33 +2407,6 @@ EOF
 fi
 
 ##########################################
-# Quorum probe (check for gnutls)
-if test "$quorum" != "no" ; then
-cat > $TMPC <<EOF
-#include <gnutls/gnutls.h>
-#include <gnutls/crypto.h>
-int main(void) {char data[4096], digest[32];
-gnutls_hash_fast(GNUTLS_DIG_SHA256, data, 4096, digest);
-return 0;
-}
-EOF
-quorum_tls_cflags=`$pkg_config --cflags gnutls 2> /dev/null`
-quorum_tls_libs=`$pkg_config --libs gnutls 2> /dev/null`
-if compile_prog "$quorum_tls_cflags" "$quorum_tls_libs" ; then
-  qcow_tls=yes
-  libs_softmmu="$quorum_tls_libs $libs_softmmu"
-  libs_tools="$quorum_tls_libs $libs_softmmu"
-  QEMU_CFLAGS="$QEMU_CFLAGS $quorum_tls_cflags"
-  quorum="yes"
-else
-  if test "$quorum" = "yes"; then
-    feature_not_found "gnutls" "gnutls > 2.10.0 required to compile Quorum"
-  fi
-  quorum="no"
-fi
-fi
-
-##########################################
 # VNC SASL detection
 if test "$vnc" = "yes" -a "$vnc_sasl" != "no" ; then
   cat > $TMPC <<EOF
@@ -4562,7 +4528,6 @@ echo "libssh2 support   $libssh2"
 echo "TPM passthrough   $tpm_passthrough"
 echo "QOM debugging     $qom_cast_debug"
 echo "vhdx              $vhdx"
-echo "Quorum            $quorum"
 echo "lzo support       $lzo"
 echo "snappy support    $snappy"
 echo "bzip2 support     $bzip2"
@@ -5038,10 +5003,6 @@ if test "$libssh2" = "yes" ; then
   echo "LIBSSH2_LIBS=$libssh2_libs" >> $config_host_mak
 fi
 
-if test "$quorum" = "yes" ; then
-  echo "CONFIG_QUORUM=y" >> $config_host_mak
-fi
-
 if test "$vhdx" = "yes" ; then
   echo "CONFIG_VHDX=y" >> $config_host_mak
 fi
#23 lore raw

Re: [Qemu-devel] [PATCH 07/10] block: convert quorum blockdrv to use crypto APIs

Quoted 72 lines · Gonglei
Quoted 71 lines · Daniel P. Berrange

Get rid of direct use of gnutls APIs in quorum blockdrv in favour of using the crypto APIs. This avoids the need to do conditional compilation of the quorum driver. It can simply report an error at file open file instead if the required hash algorithm isn't supported by QEMU.

---
 block/Makefile.objs |  2 +-
 block/quorum.c      | 38 +++++++++++++++++++-------------------
 configure           | 39 ---------------------------------------
 3 files changed, 20 insertions(+), 59 deletions(-)
block/Makefile.objs +1 -1
index 0d8c2a4..8f908d9 100644
@@ -3,7 +3,7 @@ block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-c
 block-obj-y += qed.o qed-gencb.o qed-l2-cache.o qed-table.o qed-cluster.o
 block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
-block-obj-$(CONFIG_QUORUM) += quorum.o
+block-obj-y += quorum.o
 block-obj-y += parallels.o blkdebug.o blkverify.o
 block-obj-y += block-backend.o snapshot.o qapi.o
 block-obj-$(CONFIG_WIN32) += raw-win32.o win32-aio.o
block/quorum.c +5 -10
index f91ef75..4193f30 100644
@@ -13,8 +13,6 @@
  * See the COPYING file in the top-level directory.
  */
 
-#include <gnutls/gnutls.h>
-#include <gnutls/crypto.h>
 #include "block/block_int.h"
 #include "qapi/qmp/qbool.h"
 #include "qapi/qmp/qdict.h"
@@ -23,6 +21,9 @@
 #include "qapi/qmp/qlist.h"
 #include "qapi/qmp/qstring.h"
 #include "qapi-event.h"
+#include "crypto/hash.h"
+
+#include <glib/gi18n.h>
 
 #define HASH_LENGTH 32
 
@@ -33,7 +34,7 @@
 
 /* This union holds a vote hash value */
 typedef union QuorumVoteValue {
-    char h[HASH_LENGTH];       /* SHA-256 hash */
+    uint8_t h[HASH_LENGTH];    /* SHA-256 hash */
     int64_t l;                 /* simpler 64 bits hash */
 } QuorumVoteValue;
 
@@ -427,25 +428,18 @@ static void quorum_free_vote_list(QuorumVotes *votes)
 
 static int quorum_compute_hash(QuorumAIOCB *acb, int i, QuorumVoteValue *hash)
 {
-    int j, ret;
-    gnutls_hash_hd_t dig;
     QEMUIOVector *qiov = &acb->qcrs[i].qiov;
-
-    ret = gnutls_hash_init(&dig, GNUTLS_DIG_SHA256);
-
-    if (ret < 0) {
-        return ret;
+    size_t len = sizeof(hash->h);
Quoted 8 lines

block/quorum.c static void quorum_free_vote_list(QuorumVotes *votes) · line 438

Quoted 6 lines
block/quorum.c +6 -0
+    uint8_t *data = hash->h;
+
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA256,
+                            qiov->iov, qiov->niov,
+                            &data, &len,
+                            NULL) < 0) {

The last argument should not be NULL, maybe miss error message.

Yes, it would be desirable to pass in an Error ** object, but this quorum_compute_hash method doesn't currently have any error reporting framework except for returning errno values. The quorum block driver would need some refactoring to be able to propagate Error* objects back up before we can make use of that here, so I just stuck with the generic EINVAL.

Quoted 14 lines
Quoted 4 lines
block/quorum.c +1 -1
+        return -EINVAL;
     }
 
-    for (j = 0; j < qiov->niov; j++) {

block/quorum.c static void quorum_free_vote_list(QuorumVotes *votes) · line 443

Quoted 10 lines
block/quorum.c +1 -8
-        ret = gnutls_hash(dig, qiov->iov[j].iov_base, qiov->iov[j].iov_len);
-        if (ret < 0) {
-            break;
-        }
-    }
-
-    gnutls_hash_deinit(dig, (void *) hash);
-    return ret;
+    return 0;
 }

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

PATCH 8/10 ui: convert VNC websockets to use crypto APIs

In reply to Daniel P. Berrange

Remove the direct use of gnutls for hash processing in the websockets code, in favour of using the crypto APIs. This allows the websockets code to be built unconditionally removing countless conditional checks from the VNC code.

---
 configure        | 19 +--------------
 ui/Makefile.objs |  2 +-
 ui/vnc-ws.c      | 22 ++++++++----------
 ui/vnc-ws.h      |  2 --
 ui/vnc.c         | 70 ++++++++++++--------------------------------------------
 ui/vnc.h         |  8 -------
 6 files changed, 26 insertions(+), 97 deletions(-)
configure +1 -18
index cc60f0b..661e7be 100755
@@ -245,7 +245,6 @@ vnc_tls=""
 vnc_sasl=""
 vnc_jpeg=""
 vnc_png=""
-vnc_ws=""
 xen=""
 xen_ctrl_version=""
 xen_pci_passthrough=""
@@ -887,10 +886,6 @@ for opt do
   ;;
   --enable-vnc-png) vnc_png="yes"
   ;;
-  --disable-vnc-ws) vnc_ws="no"
-  ;;
-  --enable-vnc-ws) vnc_ws="yes"
-  ;;
   --disable-slirp) slirp="no"
   ;;
   --disable-uuid) uuid="no"
@@ -2378,7 +2373,7 @@ fi
 
 ##########################################
 # VNC TLS/WS detection
-if test "$vnc" = "yes" -a \( "$vnc_tls" != "no" -o "$vnc_ws" != "no" \) ; then
+if test "$vnc" = "yes" -a "$vnc_tls" != "no" ; then
   cat > $TMPC <<EOF
 #include <gnutls/gnutls.h>
 int main(void) { gnutls_session_t s; gnutls_init(&s, GNUTLS_SERVER); return 0; }
@@ -2389,20 +2384,13 @@ EOF
     if test "$vnc_tls" != "no" ; then
       vnc_tls=yes
     fi
-    if test "$vnc_ws" != "no" ; then
-      vnc_ws=yes
-    fi
     libs_softmmu="$vnc_tls_libs $libs_softmmu"
     QEMU_CFLAGS="$QEMU_CFLAGS $vnc_tls_cflags"
   else
     if test "$vnc_tls" = "yes" ; then
       feature_not_found "vnc-tls" "Install gnutls devel"
     fi
-    if test "$vnc_ws" = "yes" ; then
-      feature_not_found "vnc-ws" "Install gnutls devel"
-    fi
     vnc_tls=no
-    vnc_ws=no
   fi
 fi
 
@@ -4465,7 +4453,6 @@ if test "$vnc" = "yes" ; then
     echo "VNC SASL support  $vnc_sasl"
     echo "VNC JPEG support  $vnc_jpeg"
     echo "VNC PNG support   $vnc_png"
-    echo "VNC WS support    $vnc_ws"
 fi
 if test -n "$sparc_cpu"; then
     echo "Target Sparc Arch $sparc_cpu"
@@ -4671,10 +4658,6 @@ fi
 if test "$vnc_png" = "yes" ; then
   echo "CONFIG_VNC_PNG=y" >> $config_host_mak
 fi
-if test "$vnc_ws" = "yes" ; then
-  echo "CONFIG_VNC_WS=y" >> $config_host_mak
-  echo "VNC_WS_CFLAGS=$vnc_ws_cflags" >> $config_host_mak
-fi
 if test "$fnmatch" = "yes" ; then
   echo "CONFIG_FNMATCH=y" >> $config_host_mak
 fi
ui/Makefile.objs +1 -1
index d9796b1..7e70d55 100644
@@ -4,7 +4,7 @@ vnc-obj-y += vnc-enc-tight.o vnc-palette.o
 vnc-obj-y += vnc-enc-zrle.o
 vnc-obj-$(CONFIG_VNC_TLS) += vnc-tls.o vnc-auth-vencrypt.o
 vnc-obj-$(CONFIG_VNC_SASL) += vnc-auth-sasl.o
-vnc-obj-$(CONFIG_VNC_WS) += vnc-ws.o
+vnc-obj-y += vnc-ws.o
 vnc-obj-y += vnc-jobs.o
 
 common-obj-y += keymaps.o console.o cursor.o qemu-pixman.o
ui/vnc-ws.c +10 -12
index 38a1b8b..215b9d6 100644
@@ -20,6 +20,7 @@
 
 #include "vnc.h"
 #include "qemu/main-loop.h"
+#include "crypto/hash.h"
 
 #ifdef CONFIG_VNC_TLS
 #include "qemu/sockets.h"
@@ -203,24 +204,21 @@ static char *vncws_extract_handshake_entry(const char *handshake,
 static void vncws_send_handshake_response(VncState *vs, const char* key)
 {
     char combined_key[WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1];
-    unsigned char hash[SHA1_DIGEST_LEN];
-    size_t hash_size = sizeof(hash);
     char *accept = NULL, *response = NULL;
-    gnutls_datum_t in;
-    int ret;
+    Error *err = NULL;
 
     g_strlcpy(combined_key, key, WS_CLIENT_KEY_LEN + 1);
     g_strlcat(combined_key, WS_GUID, WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1);
 
     /* hash and encode it */
-    in.data = (void *)combined_key;
-    in.size = WS_CLIENT_KEY_LEN + WS_GUID_LEN;
-    ret = gnutls_fingerprint(GNUTLS_DIG_SHA1, &in, hash, &hash_size);
-    if (ret == GNUTLS_E_SUCCESS && hash_size <= SHA1_DIGEST_LEN) {
-        accept = g_base64_encode(hash, hash_size);
-    }
-    if (accept == NULL) {
-        VNC_DEBUG("Hashing Websocket combined key failed\n");
+    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,
+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {
+        VNC_DEBUG("Hashing Websocket combined key failed %s\n",
+                  error_get_pretty(err));
+        error_free(err);
         vnc_client_error(vs);
         return;
     }
ui/vnc-ws.h +0 -2
index 14d4230..9494225 100644
@@ -21,8 +21,6 @@
 #ifndef __QEMU_UI_VNC_WS_H
 #define __QEMU_UI_VNC_WS_H
 
-#include <gnutls/gnutls.h>
-
 #define B64LEN(__x) (((__x + 2) / 3) * 12 / 3)
 #define SHA1_DIGEST_LEN 20
 
ui/vnc.c +14 -56

230 lines not on this page · raw message

ui/vnc.h +0 -8
index 3f7c6a9..814d720 100644
@@ -108,9 +108,7 @@ typedef struct VncDisplay VncDisplay;
 #ifdef CONFIG_VNC_SASL
 #include "vnc-auth-sasl.h"
 #endif
-#ifdef CONFIG_VNC_WS
 #include "vnc-ws.h"
-#endif
 
 struct VncRectStat
 {
@@ -156,10 +154,8 @@ struct VncDisplay
     int connections_limit;
     VncSharePolicy share_policy;
     int lsock;
-#ifdef CONFIG_VNC_WS
     int lwebsock;
     bool ws_enabled;
-#endif
     DisplaySurface *ds;
     DisplayChangeListener dcl;
     kbd_layout_t *kbd_layout;
@@ -294,21 +290,17 @@ struct VncState
 #ifdef CONFIG_VNC_SASL
     VncStateSASL sasl;
 #endif
-#ifdef CONFIG_VNC_WS
     bool encode_ws;
     bool websocket;
-#endif /* CONFIG_VNC_WS */
 
     VncClientInfo *info;
 
     Buffer output;
     Buffer input;
-#ifdef CONFIG_VNC_WS
     Buffer ws_input;
     Buffer ws_output;
     size_t ws_payload_remain;
     WsMask ws_payload_mask;
-#endif
     /* current output mode information */
     VncWritePixels *write_pixels;
     PixelFormat client_pf;
Signature · 1 line
2.1.0
#25 lore raw

Re: [Qemu-devel] [PATCH 08/10] ui: convert VNC websockets to use crypto APIs

Quoted 452 lines · Daniel P. Berrange

Remove the direct use of gnutls for hash processing in the websockets code, in favour of using the crypto APIs. This allows the websockets code to be built unconditionally removing countless conditional checks from the VNC code.

---
 configure        | 19 +--------------
 ui/Makefile.objs |  2 +-
 ui/vnc-ws.c      | 22 ++++++++----------
 ui/vnc-ws.h      |  2 --
 ui/vnc.c         | 70 ++++++++++++--------------------------------------------
 ui/vnc.h         |  8 -------
 6 files changed, 26 insertions(+), 97 deletions(-)
configure +1 -18
index cc60f0b..661e7be 100755
@@ -245,7 +245,6 @@ vnc_tls=""
 vnc_sasl=""
 vnc_jpeg=""
 vnc_png=""
-vnc_ws=""
 xen=""
 xen_ctrl_version=""
 xen_pci_passthrough=""
@@ -887,10 +886,6 @@ for opt do
   ;;
   --enable-vnc-png) vnc_png="yes"
   ;;
-  --disable-vnc-ws) vnc_ws="no"
-  ;;
-  --enable-vnc-ws) vnc_ws="yes"
-  ;;
   --disable-slirp) slirp="no"
   ;;
   --disable-uuid) uuid="no"
@@ -2378,7 +2373,7 @@ fi
 
 ##########################################
 # VNC TLS/WS detection
-if test "$vnc" = "yes" -a \( "$vnc_tls" != "no" -o "$vnc_ws" != "no" \) ; then
+if test "$vnc" = "yes" -a "$vnc_tls" != "no" ; then
   cat > $TMPC <<EOF
 #include <gnutls/gnutls.h>
 int main(void) { gnutls_session_t s; gnutls_init(&s, GNUTLS_SERVER); return 0; }
@@ -2389,20 +2384,13 @@ EOF
     if test "$vnc_tls" != "no" ; then
       vnc_tls=yes
     fi
-    if test "$vnc_ws" != "no" ; then
-      vnc_ws=yes
-    fi
     libs_softmmu="$vnc_tls_libs $libs_softmmu"
     QEMU_CFLAGS="$QEMU_CFLAGS $vnc_tls_cflags"
   else
     if test "$vnc_tls" = "yes" ; then
       feature_not_found "vnc-tls" "Install gnutls devel"
     fi
-    if test "$vnc_ws" = "yes" ; then
-      feature_not_found "vnc-ws" "Install gnutls devel"
-    fi
     vnc_tls=no
-    vnc_ws=no
   fi
 fi
 
@@ -4465,7 +4453,6 @@ if test "$vnc" = "yes" ; then
     echo "VNC SASL support  $vnc_sasl"
     echo "VNC JPEG support  $vnc_jpeg"
     echo "VNC PNG support   $vnc_png"
-    echo "VNC WS support    $vnc_ws"
 fi
 if test -n "$sparc_cpu"; then
     echo "Target Sparc Arch $sparc_cpu"
@@ -4671,10 +4658,6 @@ fi
 if test "$vnc_png" = "yes" ; then
   echo "CONFIG_VNC_PNG=y" >> $config_host_mak
 fi
-if test "$vnc_ws" = "yes" ; then
-  echo "CONFIG_VNC_WS=y" >> $config_host_mak
-  echo "VNC_WS_CFLAGS=$vnc_ws_cflags" >> $config_host_mak
-fi
 if test "$fnmatch" = "yes" ; then
   echo "CONFIG_FNMATCH=y" >> $config_host_mak
 fi
ui/Makefile.objs +1 -1
index d9796b1..7e70d55 100644
@@ -4,7 +4,7 @@ vnc-obj-y += vnc-enc-tight.o vnc-palette.o
 vnc-obj-y += vnc-enc-zrle.o
 vnc-obj-$(CONFIG_VNC_TLS) += vnc-tls.o vnc-auth-vencrypt.o
 vnc-obj-$(CONFIG_VNC_SASL) += vnc-auth-sasl.o
-vnc-obj-$(CONFIG_VNC_WS) += vnc-ws.o
+vnc-obj-y += vnc-ws.o
 vnc-obj-y += vnc-jobs.o
 
 common-obj-y += keymaps.o console.o cursor.o qemu-pixman.o
ui/vnc-ws.c +10 -12
index 38a1b8b..215b9d6 100644
@@ -20,6 +20,7 @@
 
 #include "vnc.h"
 #include "qemu/main-loop.h"
+#include "crypto/hash.h"
 
 #ifdef CONFIG_VNC_TLS
 #include "qemu/sockets.h"
@@ -203,24 +204,21 @@ static char *vncws_extract_handshake_entry(const char *handshake,
 static void vncws_send_handshake_response(VncState *vs, const char* key)
 {
     char combined_key[WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1];
-    unsigned char hash[SHA1_DIGEST_LEN];
-    size_t hash_size = sizeof(hash);
     char *accept = NULL, *response = NULL;
-    gnutls_datum_t in;
-    int ret;
+    Error *err = NULL;
 
     g_strlcpy(combined_key, key, WS_CLIENT_KEY_LEN + 1);
     g_strlcat(combined_key, WS_GUID, WS_CLIENT_KEY_LEN + WS_GUID_LEN + 1);
 
     /* hash and encode it */
-    in.data = (void *)combined_key;
-    in.size = WS_CLIENT_KEY_LEN + WS_GUID_LEN;
-    ret = gnutls_fingerprint(GNUTLS_DIG_SHA1, &in, hash, &hash_size);
-    if (ret == GNUTLS_E_SUCCESS && hash_size <= SHA1_DIGEST_LEN) {
-        accept = g_base64_encode(hash, hash_size);
-    }
-    if (accept == NULL) {
-        VNC_DEBUG("Hashing Websocket combined key failed\n");
+    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,
+                            combined_key,
+                            WS_CLIENT_KEY_LEN + WS_GUID_LEN,
+                            &accept,
+                            &err) < 0) {
+        VNC_DEBUG("Hashing Websocket combined key failed %s\n",
+                  error_get_pretty(err));
+        error_free(err);
         vnc_client_error(vs);
         return;
     }
ui/vnc-ws.h +0 -2
index 14d4230..9494225 100644
@@ -21,8 +21,6 @@
 #ifndef __QEMU_UI_VNC_WS_H
 #define __QEMU_UI_VNC_WS_H
 
-#include <gnutls/gnutls.h>
-
 #define B64LEN(__x) (((__x + 2) / 3) * 12 / 3)
 #define SHA1_DIGEST_LEN 20
 
ui/vnc.c +14 -56
index 2b80160..73a6d5f 100644
@@ -38,6 +38,7 @@
 #include "qemu/osdep.h"
 #include "ui/input.h"
 #include "qapi-event.h"
+#include "crypto/hash.h"
 
 #define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
 #define VNC_REFRESH_INTERVAL_INC  50
@@ -353,9 +354,7 @@ static VncClientInfo *qmp_query_vnc_client(const VncState *client)
     info->base->host = g_strdup(host);
     info->base->service = g_strdup(serv);
     info->base->family = inet_netfamily(sa.ss_family);
-#ifdef CONFIG_VNC_WS
     info->base->websocket = client->websocket;
-#endif
 
 #ifdef CONFIG_VNC_TLS
     if (client->tls.session && client->tls.dname) {
@@ -580,12 +579,10 @@ VncInfo2List *qmp_query_vnc_servers(Error **errp)
             info->server = qmp_query_server_entry(vd->lsock, false,
                                                   info->server);
         }
-#ifdef CONFIG_VNC_WS
         if (vd->lwebsock != -1) {
             info->server = qmp_query_server_entry(vd->lwebsock, true,
                                                   info->server);
         }
-#endif
 
         item = g_new0(VncInfo2List, 1);
         item->value = info;
@@ -1229,10 +1226,8 @@ void vnc_disconnect_finish(VncState *vs)
 
     buffer_free(&vs->input);
     buffer_free(&vs->output);
-#ifdef CONFIG_VNC_WS
     buffer_free(&vs->ws_input);
     buffer_free(&vs->ws_output);
-#endif /* CONFIG_VNC_WS */
 
     qapi_free_VncClientInfo(vs->info);
 
@@ -1411,12 +1406,9 @@ static void vnc_client_write_locked(void *opaque)
     } else
 #endif /* CONFIG_VNC_SASL */
     {
-#ifdef CONFIG_VNC_WS
         if (vs->encode_ws) {
             vnc_client_write_ws(vs);
-        } else
-#endif /* CONFIG_VNC_WS */
-        {
+        } else {
             vnc_client_write_plain(vs);
         }
     }
@@ -1427,11 +1419,7 @@ void vnc_client_write(void *opaque)
     VncState *vs = opaque;
 
     vnc_lock_output(vs);
-    if (vs->output.offset
-#ifdef CONFIG_VNC_WS
-            || vs->ws_output.offset
-#endif
-            ) {
+    if (vs->output.offset || vs->ws_output.offset) {
         vnc_client_write_locked(opaque);
     } else if (vs->csock != -1) {
         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
@@ -1537,7 +1525,6 @@ void vnc_client_read(void *opaque)
         ret = vnc_client_read_sasl(vs);
     else
 #endif /* CONFIG_VNC_SASL */
-#ifdef CONFIG_VNC_WS
         if (vs->encode_ws) {
             ret = vnc_client_read_ws(vs);
             if (ret == -1) {
@@ -1547,10 +1534,8 @@ void vnc_client_read(void *opaque)
                 vnc_client_error(vs);
                 return;
             }
-        } else
-#endif /* CONFIG_VNC_WS */
-        {
-        ret = vnc_client_read_plain(vs);
+        } else {
+            ret = vnc_client_read_plain(vs);
         }
     if (!ret) {
         if (vs->csock == -1)
@@ -1622,11 +1607,8 @@ void vnc_write_u8(VncState *vs, uint8_t value)
 void vnc_flush(VncState *vs)
 {
     vnc_lock_output(vs);
-    if (vs->csock != -1 && (vs->output.offset
-#ifdef CONFIG_VNC_WS
-                || vs->ws_output.offset
-#endif
-                )) {
+    if (vs->csock != -1 && (vs->output.offset ||
+                            vs->ws_output.offset)) {
         vnc_client_write_locked(vs);
     }
     vnc_unlock_output(vs);
@@ -3017,7 +2999,6 @@ static void vnc_connect(VncDisplay *vd, int csock,
     VNC_DEBUG("New client on socket %d\n", csock);
     update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
     qemu_set_nonblock(vs->csock);
-#ifdef CONFIG_VNC_WS
     if (websocket) {
         vs->websocket = 1;
 #ifdef CONFIG_VNC_TLS
@@ -3030,9 +3011,7 @@ static void vnc_connect(VncDisplay *vd, int csock,
             qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
                                  NULL, vs);
         }
-    } else
-#endif /* CONFIG_VNC_WS */
-    {
+    } else {
         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
     }
 
@@ -3040,10 +3019,7 @@ static void vnc_connect(VncDisplay *vd, int csock,
     vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
     vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
 
-#ifdef CONFIG_VNC_WS
-    if (!vs->websocket)
-#endif
-    {
+    if (!vs->websocket) {
         vnc_init_state(vs);
     }
 
@@ -3099,12 +3075,9 @@ static void vnc_listen_read(void *opaque, bool websocket)
 
     /* Catch-up */
     graphic_hw_update(vs->dcl.con);
-#ifdef CONFIG_VNC_WS
     if (websocket) {
         csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
-    } else
-#endif /* CONFIG_VNC_WS */
-    {
+    } else {
         csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
     }
 
@@ -3119,12 +3092,10 @@ static void vnc_listen_regular_read(void *opaque)
     vnc_listen_read(opaque, false);
 }
 
-#ifdef CONFIG_VNC_WS
 static void vnc_listen_websocket_read(void *opaque)
 {
     vnc_listen_read(opaque, true);
 }
-#endif /* CONFIG_VNC_WS */
 
 static const DisplayChangeListenerOps dcl_ops = {
     .dpy_name             = "vnc",
@@ -3150,9 +3121,7 @@ void vnc_display_init(const char *id)
     QTAILQ_INSERT_TAIL(&vnc_displays, vs, next);
 
     vs->lsock = -1;
-#ifdef CONFIG_VNC_WS
     vs->lwebsock = -1;
-#endif
 
     QTAILQ_INIT(&vs->clients);
     vs->expires = TIME_MAX;
@@ -3186,14 +3155,12 @@ static void vnc_display_close(VncDisplay *vs)
         close(vs->lsock);
         vs->lsock = -1;
     }
-#ifdef CONFIG_VNC_WS
     vs->ws_enabled = false;
     if (vs->lwebsock != -1) {
         qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
         close(vs->lwebsock);
         vs->lwebsock = -1;
     }
-#endif /* CONFIG_VNC_WS */
     vs->auth = VNC_AUTH_INVALID;
     vs->subauth = VNC_AUTH_INVALID;
 #ifdef CONFIG_VNC_TLS
@@ -3579,13 +3546,12 @@ void vnc_display_open(const char *id, Error **errp)
 
     websocket = qemu_opt_get(opts, "websocket");
     if (websocket) {
-#ifdef CONFIG_VNC_WS
         vs->ws_enabled = true;
         qemu_opt_set(wsopts, "port", websocket, &error_abort);
-#else /* ! CONFIG_VNC_WS */
-        error_setg(errp, "Websockets protocol requires gnutls support");
-        goto fail;
-#endif /* ! CONFIG_VNC_WS */
+        if (!qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {
+            error_setg(errp, "SHA1 hash support is required for websockets");
+            goto fail;
+        }
     }
 
 #ifdef CONFIG_VNC_JPEG
@@ -3668,9 +3634,7 @@ void vnc_display_open(const char *id, Error **errp)
         /* connect to viewer */
         int csock;
         vs->lsock = -1;
-#ifdef CONFIG_VNC_WS
         vs->lwebsock = -1;
-#endif
         if (strncmp(vnc, "unix:", 5) == 0) {
             csock = unix_connect(vnc+5, errp);
         } else {
@@ -3693,7 +3657,6 @@ void vnc_display_open(const char *id, Error **errp)
             if (vs->lsock < 0) {
                 goto fail;
             }
-#ifdef CONFIG_VNC_WS
             if (vs->ws_enabled) {
                 vs->lwebsock = inet_listen_opts(wsopts, 0, errp);
                 if (vs->lwebsock < 0) {
@@ -3704,17 +3667,14 @@ void vnc_display_open(const char *id, Error **errp)
                     goto fail;
                 }
             }
-#endif /* CONFIG_VNC_WS */
         }
         vs->enabled = true;
         qemu_set_fd_handler2(vs->lsock, NULL,
                 vnc_listen_regular_read, NULL, vs);
-#ifdef CONFIG_VNC_WS
         if (vs->ws_enabled) {
             qemu_set_fd_handler2(vs->lwebsock, NULL,
                     vnc_listen_websocket_read, NULL, vs);
         }
-#endif /* CONFIG_VNC_WS */
     }
     qemu_opts_del(sopts);
     qemu_opts_del(wsopts);
@@ -3724,9 +3684,7 @@ fail:
     qemu_opts_del(sopts);
     qemu_opts_del(wsopts);
     vs->enabled = false;
-#ifdef CONFIG_VNC_WS
     vs->ws_enabled = false;
-#endif /* CONFIG_VNC_WS */
 }
 
 void vnc_display_add_client(const char *id, int csock, bool skipauth)
ui/vnc.h +0 -6
index 3f7c6a9..814d720 100644
@@ -108,9 +108,7 @@ typedef struct VncDisplay VncDisplay;
 #ifdef CONFIG_VNC_SASL
 #include "vnc-auth-sasl.h"
 #endif
-#ifdef CONFIG_VNC_WS
 #include "vnc-ws.h"
-#endif
 
 struct VncRectStat
 {
@@ -156,10 +154,8 @@ struct VncDisplay
     int connections_limit;
     VncSharePolicy share_policy;
     int lsock;
-#ifdef CONFIG_VNC_WS
     int lwebsock;
     bool ws_enabled;
-#endif
     DisplaySurface *ds;
     DisplayChangeListener dcl;
     kbd_layout_t *kbd_layout;
@@ -294,21 +290,17 @@ struct VncState
 #ifdef CONFIG_VNC_SASL
     VncStateSASL sasl;
 #endif
-#ifdef CONFIG_VNC_WS
     bool encode_ws;
     bool websocket;
-#endif /* CONFIG_VNC_WS */
 
     VncClientInfo *info;
 
     Buffer output;

ui/vnc.h struct VncState · line 306

Quoted 10 lines
ui/vnc.h +0 -2
     Buffer input;
-#ifdef CONFIG_VNC_WS
     Buffer ws_input;
     Buffer ws_output;
     size_t ws_payload_remain;
     WsMask ws_payload_mask;
-#endif
     /* current output mode information */
     VncWritePixels *write_pixels;
     PixelFormat client_pf;

It's more clear now :)

Regards,
-Gonglei

#26 lore raw

PATCH 9/10 block: convert qcow/qcow2 to use generic cipher API

In reply to Daniel P. Berrange

Switch the qcow/qcow2 block driver over to use the generic cipher API, this allows it to use the pluggable AES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 block/qcow.c          | 100 ++++++++++++++++++++++++++++++++++++--------------
 block/qcow2-cluster.c |  46 ++++++++++++++++++-----
 block/qcow2.c         |  94 ++++++++++++++++++++++++-----------------------
 block/qcow2.h         |  13 +++----
 4 files changed, 162 insertions(+), 91 deletions(-)
block/qcow.c +73 -27
index 50dbcee..7338d1d 100644
@@ -25,7 +25,7 @@
 #include "block/block_int.h"
 #include "qemu/module.h"
 #include <zlib.h>
-#include "crypto/aes.h"
+#include "crypto/cipher.h"
 #include "migration/migration.h"
 
 /**************************************************************/
@@ -71,10 +71,8 @@ typedef struct BDRVQcowState {
     uint8_t *cluster_cache;
     uint8_t *cluster_data;
     uint64_t cluster_cache_offset;
-    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
+    QCryptoCipher *cipher; /* NULL if no key yet */
     uint32_t crypt_method_header;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
     CoMutex lock;
     Error *migration_blocker;
 } BDRVQcowState;
@@ -153,6 +151,11 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         ret = -EINVAL;
         goto fail;
     }
+    if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES)) {
+        error_setg(errp, "AES cipher not available");
+        ret = -EINVAL;
+        goto fail;
+    }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
         bs->encrypted = 1;
@@ -259,6 +262,7 @@ 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);
@@ -269,38 +273,66 @@ static int qcow_set_key(BlockDriverState *bs, const char *key)
     for(i = 0;i < len;i++) {
         keybuf[i] = key[i];
     }
-    s->crypt_method = s->crypt_method_header;
 
-    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
-        return -1;
-    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
+    if (s->cipher) {
+        qcrypto_cipher_free(s->cipher);
+    }
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
+
+    if (!s->cipher) {
+        error_free(err);
         return -1;
+    }
     return 0;
 }
 
 /* The crypt function is compatible with the linux cryptoloop
    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
    supported */
-static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                            uint8_t *out_buf, const uint8_t *in_buf,
-                            int nb_sectors, int enc,
-                            const AES_KEY *key)
+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)
 {
     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;
-        AES_cbc_encrypt(in_buf, out_buf, 512, key,
-                        ivec.b, enc);
+        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,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        } else {
+            ret = qcrypto_cipher_decrypt(s->cipher,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        }
+        if (ret < 0) {
+            return -1;
+        }
         sector_num++;
         in_buf += 512;
         out_buf += 512;
     }
+    return 0;
 }
 
 /* 'allocate' is:
@@ -411,17 +443,22 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                 bdrv_truncate(bs->file, cluster_offset + s->cluster_size);
                 /* if encrypted, we must initialize the cluster
                    content which won't be written */
-                if (s->crypt_method &&
+                if (s->cipher &&
                     (n_end - n_start) < s->cluster_sectors) {
                     uint64_t start_sect;
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
                     memset(s->cluster_data + 512, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {
                         if (i < n_start || i >= n_end) {
-                            encrypt_sectors(s, start_sect + i,
-                                            s->cluster_data,
-                                            s->cluster_data + 512, 1, 1,
-                                            &s->aes_encrypt_key);
+                            Error *err = NULL;
+                            if (encrypt_sectors(s, start_sect + i,
+                                                s->cluster_data,
+                                                s->cluster_data + 512, 1,
+                                                true, &err) < 0) {
+                                error_free(err);
+                                errno = EIO;
+                                return -1;
+                            }
                             if (bdrv_pwrite(bs->file, cluster_offset + i * 512,
                                             s->cluster_data, 512) != 512)
                                 return -1;
@@ -461,7 +498,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->crypt_method) {
+    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
         return BDRV_BLOCK_DATA;
     }
     cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
@@ -528,6 +565,7 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
     QEMUIOVector hd_qiov;
     uint8_t *buf;
     void *orig_buf;
+    Error *err = NULL;
 
     if (qiov->niov > 1) {
         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
@@ -590,10 +628,11 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
             if (ret < 0) {
                 break;
             }
-            if (s->crypt_method) {
-                encrypt_sectors(s, sector_num, buf, buf,
-                                n, 0,
-                                &s->aes_decrypt_key);
+            if (s->cipher) {
+                if (encrypt_sectors(s, sector_num, buf, buf,
+                                    n, false, &err) < 0) {
+                    goto fail;
+                }
             }
         }
         ret = 0;
@@ -614,6 +653,7 @@ done:
     return ret;
 
 fail:
+    error_free(err);
     ret = -EIO;
     goto done;
 }
@@ -661,12 +701,17 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
             ret = -EIO;
             break;
         }
-        if (s->crypt_method) {
+        if (s->cipher) {
+            Error *err = NULL;
             if (!cluster_data) {
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            encrypt_sectors(s, sector_num, cluster_data, buf,
-                            n, 1, &s->aes_encrypt_key);
+            if (encrypt_sectors(s, sector_num, cluster_data, buf,
+                                n, true, &err) < 0) {
+                error_free(err);
+                ret = -EIO;
+                break;
+            }
             src_buf = cluster_data;
         } else {
             src_buf = buf;
@@ -703,6 +748,7 @@ static void qcow_close(BlockDriverState *bs)
 {
     BDRVQcowState *s = bs->opaque;
 
+    qcrypto_cipher_free(s->cipher);
     g_free(s->l1_table);
     qemu_vfree(s->l2_cache);
     g_free(s->cluster_cache);
block/qcow2-cluster.c +36 -10

72 lines not on this page · raw message

block/qcow2.c +48 -46

187 lines not on this page · raw message

block/qcow2.h +5 -8
index 3cf5318..4af1471 100644
@@ -25,7 +25,7 @@
 #ifndef BLOCK_QCOW2_H
 #define BLOCK_QCOW2_H
 
-#include "crypto/aes.h"
+#include "crypto/cipher.h"
 #include "block/coroutine.h"
 
 //#define DEBUG_ALLOC
@@ -250,10 +250,8 @@ typedef struct BDRVQcowState {
 
     CoMutex lock;
 
-    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
+    QCryptoCipher *cipher; /* current cipher, NULL if no key yet */
     uint32_t crypt_method_header;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
     uint64_t snapshots_offset;
     int snapshots_size;
     unsigned int nb_snapshots;
@@ -533,10 +531,9 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
 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);
-void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                     uint8_t *out_buf, const uint8_t *in_buf,
-                     int nb_sectors, int enc,
-                     const AES_KEY *key);
+int qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
+                          uint8_t *out_buf, const uint8_t *in_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.1.0
#27 lore raw

Re: [Qemu-devel] [PATCH 09/10] block: convert qcow/qcow2 to use generic cipher API

Quoted 58 lines · Daniel P. Berrange

Switch the qcow/qcow2 block driver over to use the generic cipher API, this allows it to use the pluggable AES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 block/qcow.c          | 100 ++++++++++++++++++++++++++++++++++++--------------
 block/qcow2-cluster.c |  46 ++++++++++++++++++-----
 block/qcow2.c         |  94 ++++++++++++++++++++++++-----------------------
 block/qcow2.h         |  13 +++----
 4 files changed, 162 insertions(+), 91 deletions(-)
block/qcow.c +8 -4
index 50dbcee..7338d1d 100644
@@ -25,7 +25,7 @@
 #include "block/block_int.h"
 #include "qemu/module.h"
 #include <zlib.h>
-#include "crypto/aes.h"
+#include "crypto/cipher.h"
 #include "migration/migration.h"
 
 /**************************************************************/
@@ -71,10 +71,8 @@ typedef struct BDRVQcowState {
     uint8_t *cluster_cache;
     uint8_t *cluster_data;
     uint64_t cluster_cache_offset;
-    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
+    QCryptoCipher *cipher; /* NULL if no key yet */
     uint32_t crypt_method_header;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
     CoMutex lock;
     Error *migration_blocker;
 } BDRVQcowState;
@@ -153,6 +151,11 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         ret = -EINVAL;
         goto fail;
     }
+    if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES)) {
+        error_setg(errp, "AES cipher not available");
+        ret = -EINVAL;
+        goto fail;
+    }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
         bs->encrypted = 1;
@@ -259,6 +262,7 @@ 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);

block/qcow.c static int qcow_set_key(BlockDriverState *bs, const char *key) · line 277

Quoted 9 lines
block/qcow.c +1 -4
@@ -269,38 +273,66 @@ static int qcow_set_key(BlockDriverState *bs, const char *key)
     for(i = 0;i < len;i++) {
         keybuf[i] = key[i];
     }
-    s->crypt_method = s->crypt_method_header;
 
-    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
-        return -1;
-    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
+    if (s->cipher) {

This above check is superfluous.

block/qcow.c static int qcow_set_key(BlockDriverState *bs, const char *key) · line 287

Quoted 10 lines
block/qcow.c +10 -0
+        qcrypto_cipher_free(s->cipher);
+    }
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
+
+    if (!s->cipher) {
+        error_free(err);

Maybe we should report the error message before free it. It's the same for below error handling.

Quoted 381 lines
block/qcow.c +54 -19
         return -1;
+    }
     return 0;
 }
 
 /* The crypt function is compatible with the linux cryptoloop
    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
    supported */
-static void encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                            uint8_t *out_buf, const uint8_t *in_buf,
-                            int nb_sectors, int enc,
-                            const AES_KEY *key)
+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)
 {
     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;
-        AES_cbc_encrypt(in_buf, out_buf, 512, key,
-                        ivec.b, enc);
+        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,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        } else {
+            ret = qcrypto_cipher_decrypt(s->cipher,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        }
+        if (ret < 0) {
+            return -1;
+        }
         sector_num++;
         in_buf += 512;
         out_buf += 512;
     }
+    return 0;
 }
 
 /* 'allocate' is:
@@ -411,17 +443,22 @@ static uint64_t get_cluster_offset(BlockDriverState *bs,
                 bdrv_truncate(bs->file, cluster_offset + s->cluster_size);
                 /* if encrypted, we must initialize the cluster
                    content which won't be written */
-                if (s->crypt_method &&
+                if (s->cipher &&
                     (n_end - n_start) < s->cluster_sectors) {
                     uint64_t start_sect;
                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
                     memset(s->cluster_data + 512, 0x00, 512);
                     for(i = 0; i < s->cluster_sectors; i++) {
                         if (i < n_start || i >= n_end) {
-                            encrypt_sectors(s, start_sect + i,
-                                            s->cluster_data,
-                                            s->cluster_data + 512, 1, 1,
-                                            &s->aes_encrypt_key);
+                            Error *err = NULL;
+                            if (encrypt_sectors(s, start_sect + i,
+                                                s->cluster_data,
+                                                s->cluster_data + 512, 1,
+                                                true, &err) < 0) {
+                                error_free(err);
+                                errno = EIO;
+                                return -1;
+                            }
                             if (bdrv_pwrite(bs->file, cluster_offset + i * 512,
                                             s->cluster_data, 512) != 512)
                                 return -1;
@@ -461,7 +498,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->crypt_method) {
+    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
         return BDRV_BLOCK_DATA;
     }
     cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
@@ -528,6 +565,7 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
     QEMUIOVector hd_qiov;
     uint8_t *buf;
     void *orig_buf;
+    Error *err = NULL;
 
     if (qiov->niov > 1) {
         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
@@ -590,10 +628,11 @@ static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
             if (ret < 0) {
                 break;
             }
-            if (s->crypt_method) {
-                encrypt_sectors(s, sector_num, buf, buf,
-                                n, 0,
-                                &s->aes_decrypt_key);
+            if (s->cipher) {
+                if (encrypt_sectors(s, sector_num, buf, buf,
+                                    n, false, &err) < 0) {
+                    goto fail;
+                }
             }
         }
         ret = 0;
@@ -614,6 +653,7 @@ done:
     return ret;
 
 fail:
+    error_free(err);
     ret = -EIO;
     goto done;
 }
@@ -661,12 +701,17 @@ static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
             ret = -EIO;
             break;
         }
-        if (s->crypt_method) {
+        if (s->cipher) {
+            Error *err = NULL;
             if (!cluster_data) {
                 cluster_data = g_malloc0(s->cluster_size);
             }
-            encrypt_sectors(s, sector_num, cluster_data, buf,
-                            n, 1, &s->aes_encrypt_key);
+            if (encrypt_sectors(s, sector_num, cluster_data, buf,
+                                n, true, &err) < 0) {
+                error_free(err);
+                ret = -EIO;
+                break;
+            }
             src_buf = cluster_data;
         } else {
             src_buf = buf;
@@ -703,6 +748,7 @@ static void qcow_close(BlockDriverState *bs)
 {
     BDRVQcowState *s = bs->opaque;
 
+    qcrypto_cipher_free(s->cipher);
     g_free(s->l1_table);
     qemu_vfree(s->l2_cache);
     g_free(s->cluster_cache);
block/qcow2-cluster.c +36 -10
index ed2b44d..afc2d90 100644
@@ -342,26 +342,47 @@ static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_tab
 /* The crypt function is compatible with the linux cryptoloop
    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
    supported */
-void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                           uint8_t *out_buf, const uint8_t *in_buf,
-                           int nb_sectors, int enc,
-                           const AES_KEY *key)
+int qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
+                          uint8_t *out_buf, const uint8_t *in_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;
-        AES_cbc_encrypt(in_buf, out_buf, 512, key,
-                        ivec.b, enc);
+        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,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        } else {
+            ret = qcrypto_cipher_decrypt(s->cipher,
+                                         in_buf,
+                                         out_buf,
+                                         512,
+                                         errp);
+        }
+        if (ret < 0) {
+            return -1;
+        }
         sector_num++;
         in_buf += 512;
         out_buf += 512;
     }
+    return 0;
 }
 
 static int coroutine_fn copy_sectors(BlockDriverState *bs,
@@ -403,10 +424,15 @@ static int coroutine_fn copy_sectors(BlockDriverState *bs,
         goto out;
     }
 
-    if (s->crypt_method) {
-        qcow2_encrypt_sectors(s, start_sect + n_start,
-                        iov.iov_base, iov.iov_base, n, 1,
-                        &s->aes_encrypt_key);
+    if (s->cipher) {
+        Error *err = NULL;
+        if (qcow2_encrypt_sectors(s, start_sect + n_start,
+                                  iov.iov_base, iov.iov_base, n,
+                                  true, &err) < 0) {
+            ret = -EIO;
+            error_free(err);
+            goto out;
+        }
     }
 
     ret = qcow2_pre_write_overlap_check(bs, 0,
block/qcow2.c +39 -31
index 83e5ec9..2d1100d 100644
@@ -694,6 +694,11 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
         ret = -EINVAL;
         goto fail;
     }
+    if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES)) {
+        error_setg(errp, "AES cipher not available");
+        ret = -EINVAL;
+        goto fail;
+    }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
         bs->encrypted = 1;
@@ -1026,6 +1031,7 @@ static int qcow2_set_key(BlockDriverState *bs, const char *key)
     BDRVQcowState *s = bs->opaque;
     uint8_t keybuf[16];
     int len, i;
+    Error *err = NULL;
 
     memset(keybuf, 0, 16);
     len = strlen(key);
@@ -1036,30 +1042,20 @@ static int qcow2_set_key(BlockDriverState *bs, const char *key)
     for(i = 0;i < len;i++) {
         keybuf[i] = key[i];
     }
-    s->crypt_method = s->crypt_method_header;
 
-    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
-        return -1;
-    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
+    if (s->cipher) {
+        qcrypto_cipher_free(s->cipher);
+    }
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
+
+    if (!s->cipher) {
+        error_free(err);
         return -1;
-#if 0
-    /* test */
-    {
-        uint8_t in[16];
-        uint8_t out[16];
-        uint8_t tmp[16];
-        for(i=0;i<16;i++)
-            in[i] = i;
-        AES_encrypt(in, tmp, &s->aes_encrypt_key);
-        AES_decrypt(tmp, out, &s->aes_decrypt_key);
-        for(i = 0; i < 16; i++)
-            printf(" %02x", tmp[i]);
-        printf("\n");
-        for(i = 0; i < 16; i++)
-            printf(" %02x", out[i]);
-        printf("\n");
     }
-#endif
     return 0;
 }
 
@@ -1102,7 +1098,7 @@ static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
     }
 
     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
-        !s->crypt_method) {
+        !s->cipher) {
         index_in_cluster = sector_num & (s->cluster_sectors - 1);
         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
@@ -1152,7 +1148,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
 
         /* prepare next request */
         cur_nr_sectors = remaining_sectors;
-        if (s->crypt_method) {
+        if (s->cipher) {
             cur_nr_sectors = MIN(cur_nr_sectors,
                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
         }
@@ -1223,7 +1219,7 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
                 goto fail;
             }
 
-            if (s->crypt_method) {
+            if (s->cipher) {
                 /*
                  * For encrypted images, read everything into a temporary
                  * contiguous buffer on which the AES functions can work.
@@ -1254,9 +1250,15 @@ static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
             if (ret < 0) {
                 goto fail;
             }
-            if (s->crypt_method) {
-                qcow2_encrypt_sectors(s, sector_num,  cluster_data,
-                    cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
+            if (s->cipher) {
+                Error *err = NULL;
+                if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
+                                          cluster_data, cur_nr_sectors, false,
+                                          &err) < 0) {
+                    error_free(err);
+                    ret = -EIO;
+                    goto fail;
+                }
                 qemu_iovec_from_buf(qiov, bytes_done,
                     cluster_data, 512 * cur_nr_sectors);
             }
@@ -1314,7 +1316,7 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
         trace_qcow2_writev_start_part(qemu_coroutine_self());
         index_in_cluster = sector_num & (s->cluster_sectors - 1);
         cur_nr_sectors = remaining_sectors;
-        if (s->crypt_method &&
+        if (s->cipher &&
             cur_nr_sectors >
             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
             cur_nr_sectors =
@@ -1333,7 +1335,8 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
             cur_nr_sectors * 512);
 
-        if (s->crypt_method) {
+        if (s->cipher) {
+            Error *err = NULL;
             if (!cluster_data) {
                 cluster_data = qemu_try_blockalign(bs->file,
                                                    QCOW_MAX_CRYPT_CLUSTERS
@@ -1348,8 +1351,13 @@ static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
 
-            qcow2_encrypt_sectors(s, sector_num, cluster_data,
-                cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
+            if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
+                                      cluster_data, cur_nr_sectors,
+                                      true, &err) < 0) {
+                error_free(err);
+                ret = -EIO;
+                goto fail;
+            }
 
             qemu_iovec_reset(&hd_qiov);
             qemu_iovec_add(&hd_qiov, cluster_data,

block/qcow2.c static void qcow2_close(BlockDriverState *bs) · line 1467

Quoted 5 lines
block/qcow2.c +2 -0
@@ -1455,6 +1463,8 @@ static void qcow2_close(BlockDriverState *bs)
     qcow2_cache_destroy(bs, s->l2_table_cache);
     qcow2_cache_destroy(bs, s->refcount_block_cache);
 
+    qcrypto_cipher_free(s->cipher);
+

Do we need to set s->cipher = NULL ?

Regards,
-Gonglei

Quoted 93 lines
block/qcow2.c +7 -15
     g_free(s->unknown_header_fields);
     cleanup_unknown_header_ext(bs);
 
@@ -1471,9 +1481,7 @@ static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
 {
     BDRVQcowState *s = bs->opaque;
     int flags = s->flags;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
-    uint32_t crypt_method = 0;
+    QCryptoCipher *cipher = NULL;
     QDict *options;
     Error *local_err = NULL;
     int ret;
@@ -1483,11 +1491,8 @@ static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
      * that means we don't have to worry about reopening them here.
      */
 
-    if (s->crypt_method) {
-        crypt_method = s->crypt_method;
-        memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
-        memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
-    }
+    cipher = s->cipher;
+    s->cipher = NULL;
 
     qcow2_close(bs);
 
@@ -1512,11 +1517,7 @@ static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
         return;
     }
 
-    if (crypt_method) {
-        s->crypt_method = crypt_method;
-        memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
-        memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
-    }
+    s->cipher = cipher;
 }
 
 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
@@ -2717,8 +2718,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->crypt_method);
-            if (encrypt != !!s->crypt_method) {
+                                        !!s->cipher);
+
+            if (encrypt != !!s->cipher) {
                 fprintf(stderr, "Changing the encryption flag is not "
                         "supported.\n");
                 return -ENOTSUP;
block/qcow2.h +5 -8
index 3cf5318..4af1471 100644
@@ -25,7 +25,7 @@
 #ifndef BLOCK_QCOW2_H
 #define BLOCK_QCOW2_H
 
-#include "crypto/aes.h"
+#include "crypto/cipher.h"
 #include "block/coroutine.h"
 
 //#define DEBUG_ALLOC
@@ -250,10 +250,8 @@ typedef struct BDRVQcowState {
 
     CoMutex lock;
 
-    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
+    QCryptoCipher *cipher; /* current cipher, NULL if no key yet */
     uint32_t crypt_method_header;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
     uint64_t snapshots_offset;
     int snapshots_size;
     unsigned int nb_snapshots;
@@ -533,10 +531,9 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
 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);
-void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
-                     uint8_t *out_buf, const uint8_t *in_buf,
-                     int nb_sectors, int enc,
-                     const AES_KEY *key);
+int qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
+                          uint8_t *out_buf, const uint8_t *in_buf,
+                          int nb_sectors, bool enc, Error **errp);
 
 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
     int *num, uint64_t *cluster_offset);
#28 lore raw

Re: [Qemu-devel] [PATCH 09/10] block: convert qcow/qcow2 to use generic cipher API

Quoted 64 lines · Gonglei
Quoted 63 lines · Daniel P. Berrange

Switch the qcow/qcow2 block driver over to use the generic cipher API, this allows it to use the pluggable AES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 block/qcow.c          | 100 ++++++++++++++++++++++++++++++++++++--------------
 block/qcow2-cluster.c |  46 ++++++++++++++++++-----
 block/qcow2.c         |  94 ++++++++++++++++++++++++-----------------------
 block/qcow2.h         |  13 +++----
 4 files changed, 162 insertions(+), 91 deletions(-)
block/qcow.c +8 -5
index 50dbcee..7338d1d 100644
@@ -25,7 +25,7 @@
 #include "block/block_int.h"
 #include "qemu/module.h"
 #include <zlib.h>
-#include "crypto/aes.h"
+#include "crypto/cipher.h"
 #include "migration/migration.h"
 
 /**************************************************************/
@@ -71,10 +71,8 @@ typedef struct BDRVQcowState {
     uint8_t *cluster_cache;
     uint8_t *cluster_data;
     uint64_t cluster_cache_offset;
-    uint32_t crypt_method; /* current crypt method, 0 if no key yet */
+    QCryptoCipher *cipher; /* NULL if no key yet */
     uint32_t crypt_method_header;
-    AES_KEY aes_encrypt_key;
-    AES_KEY aes_decrypt_key;
     CoMutex lock;
     Error *migration_blocker;
 } BDRVQcowState;
@@ -153,6 +151,11 @@ static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
         ret = -EINVAL;
         goto fail;
     }
+    if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES)) {
+        error_setg(errp, "AES cipher not available");
+        ret = -EINVAL;
+        goto fail;
+    }
     s->crypt_method_header = header.crypt_method;
     if (s->crypt_method_header) {
         bs->encrypted = 1;
@@ -259,6 +262,7 @@ 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);
@@ -269,38 +273,66 @@ static int qcow_set_key(BlockDriverState *bs, const char *key)
     for(i = 0;i < len;i++) {
         keybuf[i] = key[i];
     }
-    s->crypt_method = s->crypt_method_header;
 
Quoted 6 lines

block/qcow.c static int qcow_set_key(BlockDriverState *bs, const char *key) · line 277

Quoted 4 lines
block/qcow.c +1 -3
-    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
-        return -1;
-    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
+    if (s->cipher) {

This above check is superfluous.

Hmm, yes, the free method accepts NULL just fine.

Quoted 12 lines

block/qcow.c static int qcow_set_key(BlockDriverState *bs, const char *key) · line 287

Quoted 11 lines
block/qcow.c +10 -0
+        qcrypto_cipher_free(s->cipher);
+    }
+    s->cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_AES,
+        QCRYPTO_CIPHER_MODE_CBC,
+        keybuf, G_N_ELEMENTS(keybuf),
+        &err);
+
+    if (!s->cipher) {
+        error_free(err);
Quoted 2 lines

Maybe we should report the error message before free it. It's the same for below error handling.

We're limited by the error code abilities of this code - basically there is no where to propagate the error back up to. As & when this code is updated to properly propagate errors we can do this here.

Quoted 8 lines

block/qcow.c static void qcow2_close(BlockDriverState *bs) · line 1467

Quoted 6 lines
block/qcow.c +2 -0
@@ -1455,6 +1463,8 @@ static void qcow2_close(BlockDriverState *bs)
     qcow2_cache_destroy(bs, s->l2_table_cache);
     qcow2_cache_destroy(bs, s->refcount_block_cache);
 
+    qcrypto_cipher_free(s->cipher);
+

Do we need to set s->cipher = NULL ?

Yes, probably worth while as a sanity check.

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

PATCH 10/10 ui: convert VNC to use generic cipher API

In reply to Daniel P. Berrange

Switch the VNC server over to use the generic cipher API, this allows it to use the pluggable DES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 ui/vnc.c | 52 +++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 11 deletions(-)
ui/vnc.c +41 -11
index 73a6d5f..b885c71 100644
@@ -47,7 +47,7 @@ static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
 static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
 
 #include "vnc_keysym.h"
-#include "crypto/desrfb.h"
+#include "crypto/cipher.h"
 
 static QTAILQ_HEAD(, VncDisplay) vnc_displays =
     QTAILQ_HEAD_INITIALIZER(vnc_displays);
@@ -2515,9 +2515,11 @@ static void make_challenge(VncState *vs)
 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
 {
     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
-    int i, j, pwlen;
+    size_t i, pwlen;
     unsigned char key[8];
     time_t now = time(NULL);
+    QCryptoCipher *cipher;
+    Error *err;
 
     if (!vs->vd->password) {
         VNC_DEBUG("No password configured on server");
@@ -2534,9 +2536,29 @@ static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
     pwlen = strlen(vs->vd->password);
     for (i=0; i<sizeof(key); i++)
         key[i] = i<pwlen ? vs->vd->password[i] : 0;
-    deskey(key, EN0);
-    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
-        des(response+j, response+j);
+
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);
+    if (!cipher) {
+        VNC_DEBUG("Cannot initialize cipher %s",
+                  error_get_pretty(err));
+        error_free(err);
+        goto reject;
+    }
+
+    if (qcrypto_cipher_decrypt(cipher,
+                               vs->challenge,
+                               response,
+                               VNC_AUTH_CHALLENGE_SIZE,
+                               &err) < 0) {
+        VNC_DEBUG("Cannot encrypt challenge %s",
+                  error_get_pretty(err));
+        error_free(err);
+        goto reject;
+    }
 
     /* Compare expected vs actual challenge response */
     if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
@@ -3483,12 +3505,20 @@ void vnc_display_open(const char *id, Error **errp)
     }
 
     password = qemu_opt_get_bool(opts, "password", false);
-    if (password && fips_get_state()) {
-        error_setg(errp,
-                   "VNC password auth disabled due to FIPS mode, "
-                   "consider using the VeNCrypt or SASL authentication "
-                   "methods as an alternative");
-        goto fail;
+    if (password) {
+        if (fips_get_state()) {
+            error_setg(errp,
+                       "VNC password auth disabled due to FIPS mode, "
+                       "consider using the VeNCrypt or SASL authentication "
+                       "methods as an alternative");
+            goto fail;
+        }
+        if (!qcrypto_cipher_supports(
+                QCRYPTO_CIPHER_ALG_DES_RFB)) {
+            error_setg(errp,
+                       "Cipher backend does not support DES RFB algorithm");
+            goto fail;
+        }
     }
 
     reverse = qemu_opt_get_bool(opts, "reverse", false);
Signature · 1 line
2.1.0
#30 lore raw

Re: [Qemu-devel] [PATCH 10/10] ui: convert VNC to use generic cipher API

Quoted 11 lines · Daniel P. Berrange

Switch the VNC server over to use the generic cipher API, this allows it to use the pluggable DES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 ui/vnc.c | 52 +++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 11 deletions(-)

ui/vnc.c static void make_challenge(VncState *vs) · line 2522

Quoted 9 lines
ui/vnc.c +3 -1
@@ -2515,9 +2515,11 @@ static void make_challenge(VncState *vs)
 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
 {
     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
-    int i, j, pwlen;
+    size_t i, pwlen;
     unsigned char key[8];
     time_t now = time(NULL);
+    QCryptoCipher *cipher;
+    Error *err;

Leaving this uninitialized...

Quoted 6 lines
ui/vnc.c +0 -0
     if (!vs->vd->password) {
         VNC_DEBUG("No password configured on server");
@@ -2534,9 +2536,29 @@ static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
     pwlen = strlen(vs->vd->password);
     for (i=0; i<sizeof(key); i++)

ui/vnc.c static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len) · line 2544

Quoted 10 lines
ui/vnc.c +6 -3
         key[i] = i<pwlen ? vs->vd->password[i] : 0;
-    deskey(key, EN0);
-    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
-        des(response+j, response+j);
+
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);

means that gcrypto_cipher_new may assert if it tries to set an error but dereferences bogus memory. Local errors must always start life at NULL.

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 10/10] ui: convert VNC to use generic cipher API

Quoted 35 lines · Eric Blake
Quoted 11 lines · Daniel P. Berrange

Switch the VNC server over to use the generic cipher API, this allows it to use the pluggable DES implementations, instead of being hardcoded to use QEMU's built-in impl.

---
 ui/vnc.c | 52 +++++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 41 insertions(+), 11 deletions(-)

ui/vnc.c static void make_challenge(VncState *vs) · line 2522

Quoted 9 lines
ui/vnc.c +3 -1
@@ -2515,9 +2515,11 @@ static void make_challenge(VncState *vs)
 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
 {
     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
-    int i, j, pwlen;
+    size_t i, pwlen;
     unsigned char key[8];
     time_t now = time(NULL);
+    QCryptoCipher *cipher;
+    Error *err;

Leaving this uninitialized...

Quoted 11 lines
ui/vnc.c +1 -3
     if (!vs->vd->password) {
         VNC_DEBUG("No password configured on server");
@@ -2534,9 +2536,29 @@ static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
     pwlen = strlen(vs->vd->password);
     for (i=0; i<sizeof(key); i++)
         key[i] = i<pwlen ? vs->vd->password[i] : 0;
-    deskey(key, EN0);
-    for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
-        des(response+j, response+j);
+
Quoted 8 lines

ui/vnc.c static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len) · line 2544

Quoted 5 lines
ui/vnc.c +5 -0
+    cipher = qcrypto_cipher_new(
+        QCRYPTO_CIPHER_ALG_DES_RFB,
+        QCRYPTO_CIPHER_MODE_ECB,
+        key, G_N_ELEMENTS(key),
+        &err);

means that gcrypto_cipher_new may assert if it tries to set an error but dereferences bogus memory. Local errors must always start life at NULL.

Opps, yes, missed 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 :|
#32 lore raw
In reply to Daniel P. Berrange
Quoted 11 lines · Daniel P. Berrange

This small series covers the crypto consolidation patches I previously posted as part of a larger RFC for the TLS work

https://lists.nongnu.org/archive/html/qemu-devel/2015-04/msg02038.html

Currently there are a 5 main places in QEMU which use some form of cryptographic hash or cipher algorithm. These are the quorum block driver (hash), qcow[2] block driver (cipher), VNC password auth (cipher), VNC websockets (hash) and some of the CPU instruction emulation (cipher).

Quoted 10 lines

For ciphers the code is using the in-tree implementations of AES and/or the RFB cripple-DES. While there is nothing broken about these implementations, it is none the less desirable to be able to use the GNUTLS provided impls in cases whre we are already linking to GNUTLS. This will allow QEMU to use FIPS certified implementations, which have been well audited, have some protection against side-channel leakage and are generally actively maintained by people knowledgable about encryption.

Can we use OpenSSL library in Qemu? If not, that's because of the license?

Quoted 38 lines

For hash digests the code is already using GNUTLS APIs.

With the TLS work, and possible future improved block device encryption, there will be more general purpose crypto APIs needed in QEMU.

It is undesirable to continue to litter the code with countless #ifdef WITH_GNUTLS conditionals, as it makes it increasingly hard to understand the code.

The goal of this series is to thus consolidate all the crypto code into a single logical place in QEMU - the source in $GIT/crypto and heads in $GIT/include/crypto The code in this location will provide QEMU internal APIs for hash digests, ciphers, and later TLS and block encryption primitives. The implementations will be backed by GNUTLS, and either libgcrypt or nettle depending on which of these GNUTLS is linking to. In the case where GNUTLS is disabled at build time, we'll still keep the built-in AES & RFB-cripple-DES implementations available so we have no regression vs today's level of support.

The callers of the crypto code can now be unconditionally compiled and, if needed, they can check the availability of algorithms they want at runtime and report clear errors to the CLI or QMP if not available. This is a minor difference in behaviour for the quorum block driver which would previously be disabled at compile time if gnutls was not available.

A future posting will include the TLS crypto APIs.

I have not attempted to convert the CPU emulation code to use the new crypto APIs, since that code appears to have quite specific need for access to the low level internal stages of the AES algorithm. So I've left it using the QEMU built-in AES code.

Quoted 5 lines

I've added myself in the MAINTAINERS file for the new directories, since it was't clear if anyone else on the existing QEMU maintainer list had any interest / knowledge in maintaining the crypto related pieces.

Good job :)
Recently, My colleague and I do some work about cryptography, maybe we can discuss them if possible.

Regards,
-Gonglei

Quoted 68 lines

Daniel P. Berrange (10):
crypto: introduce new module for computing hash digests
crypto: move built-in AES implementation into crypto/
crypto: move built-in D3DES implementation into crypto/
crypto: introduce generic cipher API & built-in implementation
crypto: add a gcrypt cipher implementation
crypto: add a nettle cipher implementation
block: convert quorum blockdrv to use crypto APIs
ui: convert VNC websockets to use crypto APIs
block: convert qcow/qcow2 to use generic cipher API
ui: convert VNC to use generic cipher API

 MAINTAINERS                           |   7 +
 Makefile.objs                         |   1 +
 block/Makefile.objs                   |   2 +-
 block/qcow.c                          | 100 ++++++---
 block/qcow2-cluster.c                 |  46 +++-
 block/qcow2.c                         |  95 +++++----
 block/qcow2.h                         |  13 +-
 block/quorum.c                        |  38 ++--
 configure                             | 162 +++++++++-----
 crypto/Makefile.objs                  |   5 +
 {util => crypto}/aes.c                |   2 +-
 crypto/cipher-builtin.c               | 391 ++++++++++++++++++++++++++++++++++
 crypto/cipher-gcrypt.c                | 203 ++++++++++++++++++
 crypto/cipher-nettle.c                | 226 ++++++++++++++++++++
 crypto/cipher.c                       |  31 +++
 ui/d3des.c => crypto/desrfb.c         |   2 +-
 crypto/hash.c                         | 202 ++++++++++++++++++
 crypto/init.c                         | 152 +++++++++++++
 include/{qemu => crypto}/aes.h        |   0
 include/crypto/cipher.h               | 208 ++++++++++++++++++
 ui/d3des.h => include/crypto/desrfb.h |   0
 include/crypto/hash.h                 | 189 ++++++++++++++++
 include/crypto/init.h                 |  29 +++
 target-arm/crypto_helper.c            |   2 +-
 target-i386/fpu_helper.c              |   1 -
 target-i386/ops_sse.h                 |   2 +-
 target-ppc/int_helper.c               |   2 +-
 tests/.gitignore                      |   2 +
 tests/Makefile                        |   4 +
 tests/test-crypto-cipher.c            | 290 +++++++++++++++++++++++++
 tests/test-crypto-hash.c              | 209 ++++++++++++++++++
 ui/Makefile.objs                      |   4 +-
 ui/vnc-ws.c                           |  22 +-
 ui/vnc-ws.h                           |   2 -
 ui/vnc.c                              | 122 +++++------
 ui/vnc.h                              |   8 -
 util/Makefile.objs                    |   2 +-
 vl.c                                  |   8 +
 38 files changed, 2517 insertions(+), 267 deletions(-)
 create mode 100644 crypto/Makefile.objs
 rename {util => crypto}/aes.c (99%)
 create mode 100644 crypto/cipher-builtin.c
 create mode 100644 crypto/cipher-gcrypt.c
 create mode 100644 crypto/cipher-nettle.c
 create mode 100644 crypto/cipher.c
 rename ui/d3des.c => crypto/desrfb.c (99%)
 create mode 100644 crypto/hash.c
 create mode 100644 crypto/init.c
 rename include/{qemu => crypto}/aes.h (100%)
 create mode 100644 include/crypto/cipher.h
 rename ui/d3des.h => include/crypto/desrfb.h (100%)
 create mode 100644 include/crypto/hash.h
 create mode 100644 include/crypto/init.h
 create mode 100644 tests/test-crypto-cipher.c
 create mode 100644 tests/test-crypto-hash.c
#33 lore raw
Quoted 22 lines · Gonglei
Quoted 11 lines · Daniel P. Berrange

This small series covers the crypto consolidation patches I previously posted as part of a larger RFC for the TLS work

https://lists.nongnu.org/archive/html/qemu-devel/2015-04/msg02038.html

Currently there are a 5 main places in QEMU which use some form of cryptographic hash or cipher algorithm. These are the quorum block driver (hash), qcow[2] block driver (cipher), VNC password auth (cipher), VNC websockets (hash) and some of the CPU instruction emulation (cipher).

Quoted 10 lines

For ciphers the code is using the in-tree implementations of AES and/or the RFB cripple-DES. While there is nothing broken about these implementations, it is none the less desirable to be able to use the GNUTLS provided impls in cases whre we are already linking to GNUTLS. This will allow QEMU to use FIPS certified implementations, which have been well audited, have some protection against side-channel leakage and are generally actively maintained by people knowledgable about encryption.

Quoted 1 line

Can we use OpenSSL library in Qemu? If not, that's because of the license?

There are differing opinions on OpenSSL licensing. Personally I consider it to be GPL incompatible because I don't accept the suggestion that openssl is exempt under the system libraries clause. In any case QEMU is already using GNUTLS and IME it has a more friendly API with better documentation than openssl or nss.

That all said, one benefit of the crypto consolidation is that it makes it more feasible to plug in alternative crypto libraries, because all the gnutls specific code is isolated in one place, instead of spread across the entire codebase. I don't intend to do any work to support other crypto libraries though as I don't think there's any compelling benefit to them.

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 :|
#34 lore raw
Quoted 31 lines · Daniel P. Berrange
Quoted 22 lines · Gonglei
Quoted 11 lines · Daniel P. Berrange

This small series covers the crypto consolidation patches I previously posted as part of a larger RFC for the TLS work

https://lists.nongnu.org/archive/html/qemu-devel/2015-04/msg02038.html

Currently there are a 5 main places in QEMU which use some form of cryptographic hash or cipher algorithm. These are the quorum block driver (hash), qcow[2] block driver (cipher), VNC password auth (cipher), VNC websockets (hash) and some of the CPU instruction emulation (cipher).

Quoted 10 lines

For ciphers the code is using the in-tree implementations of AES and/or the RFB cripple-DES. While there is nothing broken about these implementations, it is none the less desirable to be able to use the GNUTLS provided impls in cases whre we are already linking to GNUTLS. This will allow QEMU to use FIPS certified implementations, which have been well audited, have some protection against side-channel leakage and are generally actively maintained by people knowledgable about encryption.

Quoted 1 line

Can we use OpenSSL library in Qemu? If not, that's because of the license?

There are differing opinions on OpenSSL licensing. Personally I consider it to be GPL incompatible because I don't accept the suggestion that openssl is exempt under the system libraries clause. In any case QEMU is already using GNUTLS and IME it has a more friendly API with better documentation than openssl or nss.

Quoted 7 lines

That all said, one benefit of the crypto consolidation is that it makes it more feasible to plug in alternative crypto libraries, because all the gnutls specific code is isolated in one place, instead of spread across the entire codebase. I don't intend to do any work to support other crypto libraries though as I don't think there's any compelling benefit to them.

OK, I see, thanks.
BTW do you have a github branch which can be easier to test?

Regards,
-Gonglei

#35 lore raw
Quoted 39 lines · Gonglei
Quoted 31 lines · Daniel P. Berrange
Quoted 22 lines · Gonglei
Quoted 11 lines · Daniel P. Berrange

This small series covers the crypto consolidation patches I previously posted as part of a larger RFC for the TLS work

https://lists.nongnu.org/archive/html/qemu-devel/2015-04/msg02038.html

Currently there are a 5 main places in QEMU which use some form of cryptographic hash or cipher algorithm. These are the quorum block driver (hash), qcow[2] block driver (cipher), VNC password auth (cipher), VNC websockets (hash) and some of the CPU instruction emulation (cipher).

Quoted 10 lines

For ciphers the code is using the in-tree implementations of AES and/or the RFB cripple-DES. While there is nothing broken about these implementations, it is none the less desirable to be able to use the GNUTLS provided impls in cases whre we are already linking to GNUTLS. This will allow QEMU to use FIPS certified implementations, which have been well audited, have some protection against side-channel leakage and are generally actively maintained by people knowledgable about encryption.

Quoted 1 line

Can we use OpenSSL library in Qemu? If not, that's because of the license?

There are differing opinions on OpenSSL licensing. Personally I consider it to be GPL incompatible because I don't accept the suggestion that openssl is exempt under the system libraries clause. In any case QEMU is already using GNUTLS and IME it has a more friendly API with better documentation than openssl or nss.

Quoted 7 lines

That all said, one benefit of the crypto consolidation is that it makes it more feasible to plug in alternative crypto libraries, because all the gnutls specific code is isolated in one place, instead of spread across the entire codebase. I don't intend to do any work to support other crypto libraries though as I don't think there's any compelling benefit to them.

Quoted 2 lines

OK, I see, thanks.
BTW do you have a github branch which can be easier to test?

This small series is here:

https://github.com/berrange/qemu/tree/qemu-crypto-v1

It is ultimately part of a much larger (work in progress) series I have here:

https://github.com/berrange/qemu/tree/qemu-io-channel-12

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 :|