Skip to contentSkip to conversation

Add qemu_getrandom and ARMv8.5-RNG etc

PATCH Superseded Richard Henderson 3 participants 54 messages May 6, 2019 – May 8, 2019

Subsystems (6)

v4 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v4 cover Add qemu_getrandom and ARMv8.5-RNG etc

Changes since v3:
* Do not autoenable gnutls if linking is broken.

    Fixes --static on ubuntu 18.04.

Changes since v2:
* Changes from review.
- getrandom is not exclusive of /dev/urandom fallback.
- vnc fails gracefully on crypto failure.
- a great renaming.
* Drop the "nonblock" argument, as it's not deliverable from the backend.
* Propagate Error back through qemu_guest_getrandom.
* Add qemu_guest_getrandom_nofail to centralize "Argh! Death!".
* Convert hw/misc/
* Implement ppc darn.
* Implement x86 rdrand.

Changes since v1:
* Build crypto-obj-y for linux-user as well.
* Several patches to tidy crypto/random-platform.c.
* Use getrandom(2) in crypto/random-platform.c.
* Use qcrypto_random_bytes in ui/vnc.c.
* In qemu_getrandom:
- Use g_rand_int instead of srand48.
- Use qcrypto_random_bytes instead of getrandom directly.

Patches without review/ack:

0001-configure-Link-test-before-auto-enabling-gnutls.patch (new) 0002-crypto-Merge-crypto-obj-y-into-libqemuutil.a.patch 0022-target-arm-Implement-ARMv8.5-RNG.patch 0024-target-i386-Implement-CPUID_EXT_RDRAND.patch

r~

Richard Henderson (24):
configure: Link test before auto-enabling gnutls
crypto: Merge crypto-obj-y into libqemuutil.a
crypto: Reverse code blocks in random-platform.c
crypto: Do not fail for EINTR during qcrypto_random_bytes
crypto: Use O_CLOEXEC in qcrypto_random_init
crypto: Use getrandom for qcrypto_random_bytes
crypto: Change the qcrypto_random_bytes buffer type to void* ui/vnc: Split out authentication_failed
ui/vnc: Use gcrypto_random_bytes for start_auth_vnc
util: Add qemu_guest_getrandom and associated routines
cpus: Initialize pseudo-random seeds for all guest cpus
linux-user: Initialize pseudo-random seeds for all guest cpus
linux-user: Call qcrypto_init if not using -seed
linux-user: Use qemu_guest_getrandom_nofail for AT_RANDOM linux-user/aarch64: Use qemu_guest_getrandom for PAUTH keys
linux-user: Remove srand call
aspeed/scu: Use qemu_guest_getrandom_nofail hw/misc/nrf51_rng: Use qemu_guest_getrandom_nofail hw/misc/bcm2835_rng: Use qemu_guest_getrandom_nofail hw/misc/exynos4210_rng: Use qemu_guest_getrandom target/arm: Put all PAC keys into a structure target/arm: Implement ARMv8.5-RNG
target/ppc: Use qemu_guest_getrandom for DARN target/i386: Implement CPUID_EXT_RDRAND

 Makefile                            |  12 ++--
 Makefile.objs                       |   8 +--
 Makefile.target                     |   4 --
 include/crypto/random.h             |   2 +-
 include/qemu/guest-random.h         |  68 ++++++++++++++++++
 include/qom/cpu.h                   |   1 +
 linux-user/aarch64/target_syscall.h |   2 -
 target/arm/cpu.h                    |  17 +++--
 target/i386/helper.h                |   2 +
 cpus.c                              |   9 +++
 crypto/random-gcrypt.c              |   2 +-
 crypto/random-gnutls.c              |   2 +-
 crypto/random-platform.c            | 104 +++++++++++++++++-----------
 hw/misc/aspeed_scu.c                |  10 +--
 hw/misc/bcm2835_rng.c               |  32 ++++-----
 hw/misc/exynos4210_rng.c            |  11 ++-
 hw/misc/nrf51_rng.c                 |   4 +-
 linux-user/aarch64/cpu_loop.c       |  25 +------
 linux-user/elfload.c                |   8 +--
 linux-user/main.c                   |  34 +++++----
 linux-user/syscall.c                |  34 +++++++--
 target/arm/cpu64.c                  |   1 +
 target/arm/helper.c                 |  64 ++++++++++++++---
 target/arm/pauth_helper.c           |  18 ++---
 target/i386/cpu.c                   |   5 +-
 target/i386/int_helper.c            |  21 ++++++
 target/i386/translate.c             |  55 +++++++++++----
 target/ppc/int_helper.c             |  42 +++++++----
 ui/vnc.c                            |  53 ++++++--------
 util/guest-random.c                 |  93 +++++++++++++++++++++++++
 vl.c                                |   4 ++
 configure                           |  42 ++++++++---
 crypto/Makefile.objs                |   5 +-
 qemu-options.hx                     |  10 +++
 util/Makefile.objs                  |   1 +
 35 files changed, 562 insertions(+), 243 deletions(-)
 create mode 100644 include/qemu/guest-random.h
 create mode 100644 util/guest-random.c
Signature · 1 line
2.17.1
#1 lore raw

PATCH v4 1/24 configure: Link test before auto-enabling gnutls

At least ubuntu 18.04 does not package static gnutls libraries.

---
 configure | 19 +++++++++++++------
 1 file changed, 13 insertions(+), 6 deletions(-)
configure +13 -6
index 5b183c2e39..daadfe9ad4 100755
@@ -2784,17 +2784,24 @@ fi
 # GNUTLS probe
 
 if test "$gnutls" != "no"; then
+    pass="no"
     if $pkg_config --exists "gnutls >= 3.1.18"; 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"
-    elif test "$gnutls" = "yes"; then
+        # Packaging for the static libraries is not always correct.
+        # At least ubuntu 18.04 ships only shared libraries.
+        write_c_skeleton
+        if compile_prog "" "$gnutls_libs" ; then
+            libs_softmmu="$gnutls_libs $libs_softmmu"
+            libs_tools="$gnutls_libs $libs_tools"
+            QEMU_CFLAGS="$QEMU_CFLAGS $gnutls_cflags"
+            pass="yes"
+        fi
+    fi
+    if test "$pass" = "no" && test "$gnutls" = "yes"; then
 	feature_not_found "gnutls" "Install gnutls devel >= 3.1.18"
     else
-        gnutls="no"
+        gnutls="$pass"
     fi
 fi
 
Signature · 1 line
2.17.1
#3 lore raw

PATCH v4 2/24 crypto: Merge crypto-obj-y into libqemuutil.a

In reply to Richard Henderson

We will shortly need this in the user-only binaries, so drop the split into system and tools binaries. This also means that crypto-aes-obj-y can be merged back into crypto-obj-y.

Cc Daniel P. Berrangé <[email protected]>
---
 Makefile             | 12 +++++-------
 Makefile.objs        |  8 ++------
 Makefile.target      |  4 ----
 configure            |  9 +++------
 crypto/Makefile.objs |  5 +----
 5 files changed, 11 insertions(+), 27 deletions(-)
Makefile +5 -7
index d372493042..09c8591805 100644
@@ -410,7 +410,6 @@ dummy := $(call unnest-vars,, \
                 block-obj-y \
                 block-obj-m \
                 crypto-obj-y \
-                crypto-aes-obj-y \
                 qom-obj-y \
                 io-obj-y \
                 common-obj-y \
@@ -446,7 +445,6 @@ SOFTMMU_SUBDIR_RULES=$(filter %-softmmu,$(SUBDIR_RULES))
 
 $(SOFTMMU_SUBDIR_RULES): $(authz-obj-y)
 $(SOFTMMU_SUBDIR_RULES): $(block-obj-y)
-$(SOFTMMU_SUBDIR_RULES): $(crypto-obj-y)
 $(SOFTMMU_SUBDIR_RULES): $(io-obj-y)
 $(SOFTMMU_SUBDIR_RULES): config-all-devices.mak
 $(SOFTMMU_SUBDIR_RULES): $(edk2-decompressed)
@@ -502,7 +500,7 @@ Makefile: $(version-obj-y)
 ######################################################################
 # Build libraries
 
-libqemuutil.a: $(util-obj-y) $(trace-obj-y) $(stub-obj-y)
+libqemuutil.a: $(util-obj-y) $(trace-obj-y) $(stub-obj-y) $(crypto-obj-y)
 libvhost-user.a: $(libvhost-user-obj-y) $(util-obj-y) $(stub-obj-y)
 
 ######################################################################
@@ -511,9 +509,9 @@ COMMON_LDADDS = libqemuutil.a
 
 qemu-img.o: qemu-img-cmds.h
 
-qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
 
 qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
 
@@ -524,7 +522,7 @@ qemu-edid$(EXESUF): qemu-edid.o hw/display/edid-generate.o $(COMMON_LDADDS)
 fsdev/virtfs-proxy-helper$(EXESUF): fsdev/virtfs-proxy-helper.o fsdev/9p-marshal.o fsdev/9p-iov-marshal.o $(COMMON_LDADDS)
 fsdev/virtfs-proxy-helper$(EXESUF): LIBS += -lcap
 
-scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(authz-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(authz-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
 ifdef CONFIG_MPATH
 scsi/qemu-pr-helper$(EXESUF): LIBS += -ludev -lmultipath -lmpathpersist
 endif
Makefile.objs +2 -6
index cf065de5ed..0ce429c1af 100644
@@ -3,6 +3,8 @@
 stub-obj-y = stubs/ util/ crypto/
 util-obj-y = util/ qobject/ qapi/
 
+crypto-obj-y = crypto/
+
 chardev-obj-y = chardev/
 
 #######################################################################
@@ -21,12 +23,6 @@ block-obj-$(CONFIG_REPLICATION) += replication.o
 
 block-obj-m = block/
 
-#######################################################################
-# crypto-obj-y is code used by both qemu system emulation and qemu-img
-
-crypto-obj-y = crypto/
-crypto-aes-obj-y = crypto/
-
 #######################################################################
 # qom-obj-y is code used by both qemu system emulation and qemu-img
 
Makefile.target +0 -4
index ae02495951..ce02924ffb 100644
@@ -179,8 +179,6 @@ dummy := $(call unnest-vars,.., \
                block-obj-y \
                block-obj-m \
                chardev-obj-y \
-               crypto-obj-y \
-               crypto-aes-obj-y \
                qom-obj-y \
                io-obj-y \
                common-obj-y \
@@ -189,8 +187,6 @@ all-obj-y += $(common-obj-y)
 all-obj-y += $(qom-obj-y)
 all-obj-$(CONFIG_SOFTMMU) += $(authz-obj-y)
 all-obj-$(CONFIG_SOFTMMU) += $(block-obj-y) $(chardev-obj-y)
-all-obj-$(CONFIG_USER_ONLY) += $(crypto-aes-obj-y)
-all-obj-$(CONFIG_SOFTMMU) += $(crypto-obj-y)
 all-obj-$(CONFIG_SOFTMMU) += $(io-obj-y)
 
 ifdef CONFIG_SOFTMMU
configure +3 -6
index daadfe9ad4..0099e85a03 100755
@@ -2792,8 +2792,7 @@ if test "$gnutls" != "no"; then
         # At least ubuntu 18.04 ships only shared libraries.
         write_c_skeleton
         if compile_prog "" "$gnutls_libs" ; then
-            libs_softmmu="$gnutls_libs $libs_softmmu"
-            libs_tools="$gnutls_libs $libs_tools"
+            LIBS="$gnutls_libs $LIBS"
             QEMU_CFLAGS="$QEMU_CFLAGS $gnutls_cflags"
             pass="yes"
         fi
@@ -2860,8 +2859,7 @@ if test "$nettle" != "no"; then
         nettle_cflags=$($pkg_config --cflags nettle)
         nettle_libs=$($pkg_config --libs nettle)
         nettle_version=$($pkg_config --modversion nettle)
-        libs_softmmu="$nettle_libs $libs_softmmu"
-        libs_tools="$nettle_libs $libs_tools"
+        LIBS="$nettle_libs $LIBS"
         QEMU_CFLAGS="$QEMU_CFLAGS $nettle_cflags"
         nettle="yes"
 
@@ -2888,8 +2886,7 @@ if test "$gcrypt" != "no"; then
         then
             gcrypt_libs="$gcrypt_libs -lgpg-error"
         fi
-        libs_softmmu="$gcrypt_libs $libs_softmmu"
-        libs_tools="$gcrypt_libs $libs_tools"
+        LIBS="$gcrypt_libs $LIBS"
         QEMU_CFLAGS="$QEMU_CFLAGS $gcrypt_cflags"
         gcrypt="yes"
 
crypto/Makefile.objs +1 -4
index 256c9aca1f..a291bc5b9a 100644
@@ -34,8 +34,5 @@ crypto-obj-y += xts.o
 crypto-obj-y += block.o
 crypto-obj-y += block-qcow.o
 crypto-obj-y += block-luks.o
-
-# Let the userspace emulators avoid linking gnutls/etc
-crypto-aes-obj-y = aes.o
-
+crypto-obj-y += aes.o
 stub-obj-y += pbkdf-stub.o
Signature · 1 line
2.17.1
#4 lore raw

Re: [Qemu-devel] [PATCH v4 02/24] crypto: Merge crypto-obj-y into libqemuutil.a

Quoted 4 lines · Richard Henderson

We will shortly need this in the user-only binaries, so drop the split into system and tools binaries. This also means that crypto-aes-obj-y can be merged back into crypto-obj-y.

This patch breaks linux-user statically linked build on Fedora.

Fedora doesn't provide static version of nettle and gcrypt, so the configure fails.

You should update the configure for them like you did for gnutls in PATCH 1.

Thanks,
Laurent

Quoted 158 lines
Cc Daniel P. Berrangé <[email protected]>
---
  Makefile             | 12 +++++-------
  Makefile.objs        |  8 ++------
  Makefile.target      |  4 ----
  configure            |  9 +++------
  crypto/Makefile.objs |  5 +----
  5 files changed, 11 insertions(+), 27 deletions(-)
Makefile +5 -7
index d372493042..09c8591805 100644
@@ -410,7 +410,6 @@ dummy := $(call unnest-vars,, \
                  block-obj-y \
                  block-obj-m \
                  crypto-obj-y \
-                crypto-aes-obj-y \
                  qom-obj-y \
                  io-obj-y \
                  common-obj-y \
@@ -446,7 +445,6 @@ SOFTMMU_SUBDIR_RULES=$(filter %-softmmu,$(SUBDIR_RULES))
 
  $(SOFTMMU_SUBDIR_RULES): $(authz-obj-y)
  $(SOFTMMU_SUBDIR_RULES): $(block-obj-y)
-$(SOFTMMU_SUBDIR_RULES): $(crypto-obj-y)
  $(SOFTMMU_SUBDIR_RULES): $(io-obj-y)
  $(SOFTMMU_SUBDIR_RULES): config-all-devices.mak
  $(SOFTMMU_SUBDIR_RULES): $(edk2-decompressed)
@@ -502,7 +500,7 @@ Makefile: $(version-obj-y)
  ######################################################################
  # Build libraries
 
-libqemuutil.a: $(util-obj-y) $(trace-obj-y) $(stub-obj-y)
+libqemuutil.a: $(util-obj-y) $(trace-obj-y) $(stub-obj-y) $(crypto-obj-y)
  libvhost-user.a: $(libvhost-user-obj-y) $(util-obj-y) $(stub-obj-y)
 
  ######################################################################
@@ -511,9 +509,9 @@ COMMON_LDADDS = libqemuutil.a
 
  qemu-img.o: qemu-img-cmds.h
 
-qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
 
  qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
 
@@ -524,7 +522,7 @@ qemu-edid$(EXESUF): qemu-edid.o hw/display/edid-generate.o $(COMMON_LDADDS)
  fsdev/virtfs-proxy-helper$(EXESUF): fsdev/virtfs-proxy-helper.o fsdev/9p-marshal.o fsdev/9p-iov-marshal.o $(COMMON_LDADDS)
  fsdev/virtfs-proxy-helper$(EXESUF): LIBS += -lcap
 
-scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(authz-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(authz-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
  ifdef CONFIG_MPATH
  scsi/qemu-pr-helper$(EXESUF): LIBS += -ludev -lmultipath -lmpathpersist
  endif
Makefile.objs +2 -6
index cf065de5ed..0ce429c1af 100644
@@ -3,6 +3,8 @@
  stub-obj-y = stubs/ util/ crypto/
  util-obj-y = util/ qobject/ qapi/
 
+crypto-obj-y = crypto/
+
  chardev-obj-y = chardev/
 
  #######################################################################
@@ -21,12 +23,6 @@ block-obj-$(CONFIG_REPLICATION) += replication.o
 
  block-obj-m = block/
 
-#######################################################################
-# crypto-obj-y is code used by both qemu system emulation and qemu-img
-
-crypto-obj-y = crypto/
-crypto-aes-obj-y = crypto/
-
  #######################################################################
  # qom-obj-y is code used by both qemu system emulation and qemu-img
 
Makefile.target +0 -4
index ae02495951..ce02924ffb 100644
@@ -179,8 +179,6 @@ dummy := $(call unnest-vars,.., \
                 block-obj-y \
                 block-obj-m \
                 chardev-obj-y \
-               crypto-obj-y \
-               crypto-aes-obj-y \
                 qom-obj-y \
                 io-obj-y \
                 common-obj-y \
@@ -189,8 +187,6 @@ all-obj-y += $(common-obj-y)
  all-obj-y += $(qom-obj-y)
  all-obj-$(CONFIG_SOFTMMU) += $(authz-obj-y)
  all-obj-$(CONFIG_SOFTMMU) += $(block-obj-y) $(chardev-obj-y)
-all-obj-$(CONFIG_USER_ONLY) += $(crypto-aes-obj-y)
-all-obj-$(CONFIG_SOFTMMU) += $(crypto-obj-y)
  all-obj-$(CONFIG_SOFTMMU) += $(io-obj-y)
 
  ifdef CONFIG_SOFTMMU
configure +3 -6
index daadfe9ad4..0099e85a03 100755
@@ -2792,8 +2792,7 @@ if test "$gnutls" != "no"; then
          # At least ubuntu 18.04 ships only shared libraries.
          write_c_skeleton
          if compile_prog "" "$gnutls_libs" ; then
-            libs_softmmu="$gnutls_libs $libs_softmmu"
-            libs_tools="$gnutls_libs $libs_tools"
+            LIBS="$gnutls_libs $LIBS"
              QEMU_CFLAGS="$QEMU_CFLAGS $gnutls_cflags"
              pass="yes"
          fi
@@ -2860,8 +2859,7 @@ if test "$nettle" != "no"; then
          nettle_cflags=$($pkg_config --cflags nettle)
          nettle_libs=$($pkg_config --libs nettle)
          nettle_version=$($pkg_config --modversion nettle)
-        libs_softmmu="$nettle_libs $libs_softmmu"
-        libs_tools="$nettle_libs $libs_tools"
+        LIBS="$nettle_libs $LIBS"
          QEMU_CFLAGS="$QEMU_CFLAGS $nettle_cflags"
          nettle="yes"
 
@@ -2888,8 +2886,7 @@ if test "$gcrypt" != "no"; then
          then
              gcrypt_libs="$gcrypt_libs -lgpg-error"
          fi
-        libs_softmmu="$gcrypt_libs $libs_softmmu"
-        libs_tools="$gcrypt_libs $libs_tools"
+        LIBS="$gcrypt_libs $LIBS"
          QEMU_CFLAGS="$QEMU_CFLAGS $gcrypt_cflags"
          gcrypt="yes"
 
crypto/Makefile.objs +1 -4
index 256c9aca1f..a291bc5b9a 100644
@@ -34,8 +34,5 @@ crypto-obj-y += xts.o
  crypto-obj-y += block.o
  crypto-obj-y += block-qcow.o
  crypto-obj-y += block-luks.o
-
-# Let the userspace emulators avoid linking gnutls/etc
-crypto-aes-obj-y = aes.o
-
+crypto-obj-y += aes.o
  stub-obj-y += pbkdf-stub.o
#5 lore raw

Re: [Qemu-devel] [PATCH v4 02/24] crypto: Merge crypto-obj-y into libqemuutil.a

Quoted 6 lines · Laurent Vivier

This patch breaks linux-user statically linked build on Fedora.

Fedora doesn't provide static version of nettle and gcrypt, so the configure fails.

You should update the configure for them like you did for gnutls in PATCH 1.

Which fedora? I just tried fedora30 and it worked for me...

r~

#6 lore raw

Re: [Qemu-devel] [PATCH v4 02/24] crypto: Merge crypto-obj-y into libqemuutil.a

Quoted 9 lines · Richard Henderson
Quoted 6 lines · Laurent Vivier

This patch breaks linux-user statically linked build on Fedora.

Fedora doesn't provide static version of nettle and gcrypt, so the configure fails.

You should update the configure for them like you did for gnutls in PATCH 1.

Which fedora? I just tried fedora30 and it worked for me...

Nevermind, I see it now.

r~

#7 lore raw

PATCH v4 3/24 crypto: Reverse code blocks in random-platform.c

In reply to Richard Henderson

Use #ifdef _WIN32 instead of #ifndef _WIN32. This will make other tests easier to sequence.

---
 crypto/random-platform.c | 35 +++++++++++++++++------------------
 1 file changed, 17 insertions(+), 18 deletions(-)
crypto/random-platform.c +17 -18
index 7541b4cae7..f995fc0ef1 100644
@@ -32,7 +32,14 @@ static int fd; /* a file handle to either /dev/urandom or /dev/random */
 
 int qcrypto_random_init(Error **errp)
 {
-#ifndef _WIN32
+#ifdef _WIN32
+    if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
+                             CRYPT_SILENT | CRYPT_VERIFYCONTEXT)) {
+        error_setg_win32(errp, GetLastError(),
+                         "Unable to create cryptographic provider");
+        return -1;
+    }
+#else
     /* TBD perhaps also add support for BSD getentropy / Linux
      * getrandom syscalls directly */
     fd = open("/dev/urandom", O_RDONLY);
@@ -44,15 +51,7 @@ int qcrypto_random_init(Error **errp)
         error_setg(errp, "No /dev/urandom or /dev/random found");
         return -1;
     }
-#else
-    if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
-                             CRYPT_SILENT | CRYPT_VERIFYCONTEXT)) {
-        error_setg_win32(errp, GetLastError(),
-                         "Unable to create cryptographic provider");
-        return -1;
-    }
 #endif
-
     return 0;
 }
 
@@ -60,7 +59,15 @@ int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
                          size_t buflen G_GNUC_UNUSED,
                          Error **errp)
 {
-#ifndef _WIN32
+#ifdef _WIN32
+    if (!CryptGenRandom(hCryptProv, buflen, buf)) {
+        error_setg_win32(errp, GetLastError(),
+                         "Unable to read random bytes");
+        return -1;
+    }
+
+    return 0;
+#else
     int ret = -1;
     int got;
 
@@ -82,13 +89,5 @@ int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
     ret = 0;
  cleanup:
     return ret;
-#else
-    if (!CryptGenRandom(hCryptProv, buflen, buf)) {
-        error_setg_win32(errp, GetLastError(),
-                         "Unable to read random bytes");
-        return -1;
-    }
-
-    return 0;
 #endif
 }
Signature · 1 line
2.17.1
Reviewed-by on v4 3/24
#8 lore raw

Re: [Qemu-devel] [PATCH v4 03/24] crypto: Reverse code blocks in random-platform.c

Quoted 10 lines · Richard Henderson

Use #ifdef _WIN32 instead of #ifndef _WIN32. This will make other tests easier to sequence.

---
  crypto/random-platform.c | 35 +++++++++++++++++------------------
  1 file changed, 17 insertions(+), 18 deletions(-)
#9 lore raw

PATCH v4 4/24 crypto: Do not fail for EINTR during qcrypto_random_bytes

In reply to Richard Henderson

We can always get EINTR for read; /dev/urandom is no exception.

Rearrange the order of tests for likelihood; allow degenerate buflen==0 case to perform a no-op zero-length read. This means that the normal success path is a straight line with a single test for success.

---
v3: Rearrage the read loop again.

---
 crypto/random-platform.c | 36 +++++++++++++++---------------------
 1 file changed, 15 insertions(+), 21 deletions(-)
crypto/random-platform.c +15 -21
index f995fc0ef1..260b64564d 100644
@@ -65,29 +65,23 @@ int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
                          "Unable to read random bytes");
         return -1;
     }
-
-    return 0;
 #else
-    int ret = -1;
-    int got;
-
-    while (buflen > 0) {
-        got = read(fd, buf, buflen);
-        if (got < 0) {
-            error_setg_errno(errp, errno,
-                             "Unable to read random bytes");
-            goto cleanup;
-        } else if (!got) {
-            error_setg(errp,
-                       "Unexpected EOF reading random bytes");
-            goto cleanup;
+    while (1) {
+        ssize_t got = read(fd, buf, buflen);
+        if (likely(got == buflen)) {
+            return 0;
+        }
+        if (got > 0) {
+            buflen -= got;
+            buf += got;
+        } else if (got == 0) {
+            error_setg(errp, "Unexpected EOF reading random bytes");
+            return -1;
+        } else if (errno != EINTR) {
+            error_setg_errno(errp, errno, "Unable to read random bytes");
+            return -1;
         }
-        buflen -= got;
-        buf += got;
     }
-
-    ret = 0;
- cleanup:
-    return ret;
 #endif
+    return 0;
 }
Signature · 1 line
2.17.1
Reviewed-by on v4 4/24
#10 lore raw

Re: [Qemu-devel] [PATCH v4 04/24] crypto: Do not fail for EINTR during qcrypto_random_bytes

Quoted 6 lines · Richard Henderson

We can always get EINTR for read; /dev/urandom is no exception.

Rearrange the order of tests for likelihood; allow degenerate buflen==0 case to perform a no-op zero-length read. This means that the normal success path is a straight line with a single test for success.

Quoted 8 lines

---
v3: Rearrage the read loop again.

---
  crypto/random-platform.c | 36 +++++++++++++++---------------------
  1 file changed, 15 insertions(+), 21 deletions(-)
#11 lore raw

PATCH v4 5/24 crypto: Use O_CLOEXEC in qcrypto_random_init

In reply to Richard Henderson

Avoids leaking the /dev/urandom fd into any child processes.

---
 crypto/random-platform.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
crypto/random-platform.c +2 -2
index 260b64564d..6df40744c7 100644
@@ -42,9 +42,9 @@ int qcrypto_random_init(Error **errp)
 #else
     /* TBD perhaps also add support for BSD getentropy / Linux
      * getrandom syscalls directly */
-    fd = open("/dev/urandom", O_RDONLY);
+    fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
     if (fd == -1 && errno == ENOENT) {
-        fd = open("/dev/random", O_RDONLY);
+        fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
     }
 
     if (fd < 0) {
Signature · 1 line
2.17.1
Reviewed-by on v4 5/24
#12 lore raw

Re: [Qemu-devel] [PATCH v4 05/24] crypto: Use O_CLOEXEC in qcrypto_random_init

Quoted 8 lines · Richard Henderson

Avoids leaking the /dev/urandom fd into any child processes.

---
  crypto/random-platform.c | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
#13 lore raw

PATCH v4 6/24 crypto: Use getrandom for qcrypto_random_bytes

In reply to Richard Henderson

Prefer it to direct use of /dev/urandom.

---
v3: If getrandom is not present, fall back on /dev/(u)random.

---
 crypto/random-platform.c | 37 ++++++++++++++++++++++++++++++++-----
 configure                | 18 +++++++++++++++++-
 2 files changed, 49 insertions(+), 6 deletions(-)
crypto/random-platform.c +32 -5
index 6df40744c7..cb3ca1bc09 100644
@@ -27,7 +27,11 @@
 #include <wincrypt.h>
 static HCRYPTPROV hCryptProv;
 #else
-static int fd; /* a file handle to either /dev/urandom or /dev/random */
+# ifdef CONFIG_GETRANDOM
+#  include <sys/random.h>
+# endif
+/* This is -1 for getrandom(), or a file handle for /dev/{u,}random.  */
+static int fd;
 #endif
 
 int qcrypto_random_init(Error **errp)
@@ -40,15 +44,20 @@ int qcrypto_random_init(Error **errp)
         return -1;
     }
 #else
-    /* TBD perhaps also add support for BSD getentropy / Linux
-     * getrandom syscalls directly */
+# ifdef CONFIG_GETRANDOM
+    if (getrandom(NULL, 0, 0) == 0) {
+        /* Use getrandom() */
+        fd = -1;
+        return 0;
+    }
+    /* Fall through to /dev/urandom case.  */
+# endif
     fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
     if (fd == -1 && errno == ENOENT) {
         fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
     }
-
     if (fd < 0) {
-        error_setg(errp, "No /dev/urandom or /dev/random found");
+        error_setg_errno(errp, errno, "No /dev/urandom or /dev/random");
         return -1;
     }
 #endif
@@ -66,6 +75,24 @@ int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
         return -1;
     }
 #else
+# ifdef CONFIG_GETRANDOM
+    if (likely(fd < 0)) {
+        while (1) {
+            ssize_t got = getrandom(buf, buflen, 0);
+            if (likely(got == buflen)) {
+                return 0;
+            }
+            if (got >= 0) {
+                buflen -= got;
+                buf += got;
+            } else if (errno != EINTR) {
+                error_setg_errno(errp, errno, "getrandom");
+                return -1;
+            }
+        }
+    }
+    /* Fall through to /dev/urandom case.  */
+# endif
     while (1) {
         ssize_t got = read(fd, buf, buflen);
         if (likely(got == buflen)) {
configure +17 -1
index 0099e85a03..5138a1a45c 100755
@@ -5806,6 +5806,20 @@ if compile_prog "" "" ; then
     have_utmpx=yes
 fi
 
+##########################################
+# check for getrandom()
+
+have_getrandom=no
+cat > $TMPC << EOF
+#include <sys/random.h>
+int main(void) {
+    return getrandom(0, 0, GRND_NONBLOCK);
+}
+EOF
+if compile_prog "" "" ; then
+    have_getrandom=yes
+fi
+
 ##########################################
 # checks for sanitizers
 
@@ -7193,7 +7207,9 @@ fi
 if test "$have_utmpx" = "yes" ; then
   echo "HAVE_UTMPX=y" >> $config_host_mak
 fi
-
+if test "$have_getrandom" = "yes" ; then
+  echo "CONFIG_GETRANDOM=y" >> $config_host_mak
+fi
 if test "$ivshmem" = "yes" ; then
   echo "CONFIG_IVSHMEM=y" >> $config_host_mak
 fi
Signature · 1 line
2.17.1
Reviewed-by on v4 6/24
#14 lore raw

Re: [Qemu-devel] [PATCH v4 06/24] crypto: Use getrandom for qcrypto_random_bytes

Quoted 11 lines · Richard Henderson

Prefer it to direct use of /dev/urandom.

---
v3: If getrandom is not present, fall back on /dev/(u)random.

---
  crypto/random-platform.c | 37 ++++++++++++++++++++++++++++++++-----
  configure                | 18 +++++++++++++++++-
  2 files changed, 49 insertions(+), 6 deletions(-)
#15 lore raw

PATCH v4 7/24 crypto: Change the qcrypto_random_bytes buffer type to void*

In reply to Richard Henderson

Using uint8_t* merely requires useless casts for use with other types to be filled with randomness.

---
 include/crypto/random.h  | 2 +-
 crypto/random-gcrypt.c   | 2 +-
 crypto/random-gnutls.c   | 2 +-
 crypto/random-platform.c | 4 ++--
 4 files changed, 5 insertions(+), 5 deletions(-)
include/crypto/random.h +1 -1
index 8764ca0562..fde592904e 100644
@@ -34,7 +34,7 @@
  *
  * Returns 0 on success, -1 on error
  */
-int qcrypto_random_bytes(uint8_t *buf,
+int qcrypto_random_bytes(void *buf,
                          size_t buflen,
                          Error **errp);
 
crypto/random-gcrypt.c +1 -1
index 9f1c9ee60e..7aea4ac81f 100644
@@ -24,7 +24,7 @@
 
 #include <gcrypt.h>
 
-int qcrypto_random_bytes(uint8_t *buf,
+int qcrypto_random_bytes(void *buf,
                          size_t buflen,
                          Error **errp G_GNUC_UNUSED)
 {
crypto/random-gnutls.c +1 -1
index 445fd6a30b..ed6c9ca12f 100644
@@ -26,7 +26,7 @@
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
 
-int qcrypto_random_bytes(uint8_t *buf,
+int qcrypto_random_bytes(void *buf,
                          size_t buflen,
                          Error **errp)
 {
crypto/random-platform.c +2 -2
index cb3ca1bc09..66624106fe 100644
@@ -64,8 +64,8 @@ int qcrypto_random_init(Error **errp)
     return 0;
 }
 
-int qcrypto_random_bytes(uint8_t *buf G_GNUC_UNUSED,
-                         size_t buflen G_GNUC_UNUSED,
+int qcrypto_random_bytes(void *buf,
+                         size_t buflen,
                          Error **errp)
 {
 #ifdef _WIN32
Signature · 1 line
2.17.1
Reviewed-by on v4 7/24
#16 lore raw

Re: [Qemu-devel] [PATCH v4 07/24] crypto: Change the qcrypto_random_bytes buffer type to void*

Quoted 6 lines · Richard Henderson

Using uint8_t* merely requires useless casts for use with other types to be filled with randomness.

Quoted 7 lines
---
  include/crypto/random.h  | 2 +-
  crypto/random-gcrypt.c   | 2 +-
  crypto/random-gnutls.c   | 2 +-
  crypto/random-platform.c | 4 ++--
  4 files changed, 5 insertions(+), 5 deletions(-)
#17 lore raw

PATCH v4 8/24 ui/vnc: Split out authentication_failed

In reply to Richard Henderson

There were 3 copies of this code, one of which used the wrong data size for the failure indicator.

---
 ui/vnc.c | 37 +++++++++++++++----------------------
 1 file changed, 15 insertions(+), 22 deletions(-)
ui/vnc.c +15 -22
index 1871422e1d..785edf3af1 100644
@@ -2535,6 +2535,18 @@ void start_client_init(VncState *vs)
     vnc_read_when(vs, protocol_client_init, 1);
 }
 
+static void authentication_failed(VncState *vs)
+{
+    vnc_write_u32(vs, 1); /* Reject auth */
+    if (vs->minor >= 8) {
+        static const char err[] = "Authentication failed";
+        vnc_write_u32(vs, sizeof(err));
+        vnc_write(vs, err, sizeof(err));
+    }
+    vnc_flush(vs);
+    vnc_client_error(vs);
+}
+
 static void make_challenge(VncState *vs)
 {
     int i;
@@ -2609,14 +2621,7 @@ static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
     return 0;
 
 reject:
-    vnc_write_u32(vs, 1); /* Reject auth */
-    if (vs->minor >= 8) {
-        static const char err[] = "Authentication failed";
-        vnc_write_u32(vs, sizeof(err));
-        vnc_write(vs, err, sizeof(err));
-    }
-    vnc_flush(vs);
-    vnc_client_error(vs);
+    authentication_failed(vs);
     qcrypto_cipher_free(cipher);
     return 0;
 }
@@ -2638,13 +2643,7 @@ static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
      * must pick the one we sent. Verify this */
     if (data[0] != vs->auth) { /* Reject auth */
        trace_vnc_auth_reject(vs, vs->auth, (int)data[0]);
-       vnc_write_u32(vs, 1);
-       if (vs->minor >= 8) {
-           static const char err[] = "Authentication failed";
-           vnc_write_u32(vs, sizeof(err));
-           vnc_write(vs, err, sizeof(err));
-       }
-       vnc_client_error(vs);
+       authentication_failed(vs);
     } else { /* Accept requested auth */
        trace_vnc_auth_start(vs, vs->auth);
        switch (vs->auth) {
@@ -2673,13 +2672,7 @@ static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
 
        default: /* Should not be possible, but just in case */
            trace_vnc_auth_fail(vs, vs->auth, "Unhandled auth method", "");
-           vnc_write_u8(vs, 1);
-           if (vs->minor >= 8) {
-               static const char err[] = "Authentication failed";
-               vnc_write_u32(vs, sizeof(err));
-               vnc_write(vs, err, sizeof(err));
-           }
-           vnc_client_error(vs);
+           authentication_failed(vs);
        }
     }
     return 0;
Signature · 1 line
2.17.1
Reviewed-by on v4 8/24
#18 lore raw

Re: [Qemu-devel] [PATCH v4 08/24] ui/vnc: Split out authentication_failed

Quoted 11 lines · Richard Henderson

There were 3 copies of this code, one of which used the wrong data size for the failure indicator.

---
  ui/vnc.c | 37 +++++++++++++++----------------------
  1 file changed, 15 insertions(+), 22 deletions(-)
#19 lore raw

PATCH v4 9/24 ui/vnc: Use gcrypto_random_bytes for start_auth_vnc

In reply to Richard Henderson

Use a better interface for random numbers than rand(). Fail gracefully if for some reason we cannot use the crypto system.

---
v2: Use qcrypto_random_bytes, not qemu_getrandom, as there is
no need for deterministic results for this interface.
v3: Fail gracefully in the event qcrypto_random_bytes fails.

---
 ui/vnc.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
ui/vnc.c +11 -11
index 785edf3af1..d83f4a6ff9 100644
@@ -43,6 +43,7 @@
 #include "crypto/hash.h"
 #include "crypto/tlscredsanon.h"
 #include "crypto/tlscredsx509.h"
+#include "crypto/random.h"
 #include "qom/object_interfaces.h"
 #include "qemu/cutils.h"
 #include "io/dns-resolver.h"
@@ -2547,16 +2548,6 @@ static void authentication_failed(VncState *vs)
     vnc_client_error(vs);
 }
 
-static void make_challenge(VncState *vs)
-{
-    int i;
-
-    srand(time(NULL)+getpid()+getpid()*987654+rand());
-
-    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
-        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
-}
-
 static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
 {
     unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
@@ -2628,7 +2619,16 @@ reject:
 
 void start_auth_vnc(VncState *vs)
 {
-    make_challenge(vs);
+    Error *err = NULL;
+
+    if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
+        trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
+                            error_get_pretty(err));
+        error_free(err);
+        authentication_failed(vs);
+        return;
+    }
+
     /* Send client a 'random' challenge */
     vnc_write(vs, vs->challenge, sizeof(vs->challenge));
     vnc_flush(vs);
Signature · 1 line
2.17.1
#20 lore raw

Re: [Qemu-devel] [PATCH v4 09/24] ui/vnc: Use gcrypto_random_bytes for start_auth_vnc

Quoted 49 lines · Richard Henderson

Use a better interface for random numbers than rand(). Fail gracefully if for some reason we cannot use the crypto system.

---
v2: Use qcrypto_random_bytes, not qemu_getrandom, as there is
no need for deterministic results for this interface.
v3: Fail gracefully in the event qcrypto_random_bytes fails.

---
  ui/vnc.c | 22 +++++++++++-----------
  1 file changed, 11 insertions(+), 11 deletions(-)
ui/vnc.c +1 -11
index 785edf3af1..d83f4a6ff9 100644
@@ -43,6 +43,7 @@
  #include "crypto/hash.h"
  #include "crypto/tlscredsanon.h"
  #include "crypto/tlscredsx509.h"
+#include "crypto/random.h"
  #include "qom/object_interfaces.h"
  #include "qemu/cutils.h"
  #include "io/dns-resolver.h"
@@ -2547,16 +2548,6 @@ static void authentication_failed(VncState *vs)
      vnc_client_error(vs);
  }
 
-static void make_challenge(VncState *vs)
-{
-    int i;
-
-    srand(time(NULL)+getpid()+getpid()*987654+rand());
-
-    for (i = 0 ; i < sizeof(vs->challenge) ; i++)
-        vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
-}
-
  static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
  {
      unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
@@ -2628,7 +2619,16 @@ reject:
 
  void start_auth_vnc(VncState *vs)
  {
-    make_challenge(vs);

ui/vnc.c reject: · line 2631

Quoted 10 lines
ui/vnc.c +10 -0
+    Error *err = NULL;
+
+    if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) {
+        trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes",
+                            error_get_pretty(err));
+        error_free(err);
+        authentication_failed(vs);
+        return;
+    }
+

This part is weird for me: if auth fails we send "vnc_write_u32(vs, 1)" but if it succeeds we send the challenge. There is no success value to send (like "vnc_write_u32(vs, 0)") ?

Quoted 4 lines
ui/vnc.c +0 -0
      /* Send client a 'random' challenge */
      vnc_write(vs, vs->challenge, sizeof(vs->challenge));
      vnc_flush(vs);
#21 lore raw

Re: [Qemu-devel] [PATCH v4 09/24] ui/vnc: Use gcrypto_random_bytes for start_auth_vnc

Quoted 9 lines · Laurent Vivier
Quoted 9 lines

    void start_auth_vnc(VncState *vs)
  {
-    make_challenge(vs);
+    Error *err = NULL;
+
+    if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) { +        trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes", +                            error_get_pretty(err));
+        error_free(err);

Quoted 8 lines
Quoted 4 lines

+        authentication_failed(vs);
+        return;
+    }
+

This part is weird for me: if auth fails we send "vnc_write_u32(vs, 1)" but if it succeeds we send the challenge. There is no success value to send (like "vnc_write_u32(vs, 0)") ?

There is, but this code is a mess of callbacks. In this case it happens toward the end of protocol_client_auth_vnc:

   2604         trace_vnc_auth_pass(vs, vs->auth);
   2605         vnc_write_u32(vs, 0); /* Accept auth */
   2606         vnc_flush(vs);

r~

Reviewed-by
#22 lore raw

Re: [Qemu-devel] [PATCH v4 09/24] ui/vnc: Use gcrypto_random_bytes for start_auth_vnc

Quoted 19 lines · Richard Henderson
Quoted 9 lines · Laurent Vivier
Quoted 9 lines

    void start_auth_vnc(VncState *vs)
  {
-    make_challenge(vs);
+    Error *err = NULL;
+
+    if (qcrypto_random_bytes(vs->challenge, sizeof(vs->challenge), &err)) { +        trace_vnc_auth_fail(vs, vs->auth, "cannot get random bytes", +                            error_get_pretty(err));
+        error_free(err);

Quoted 8 lines
Quoted 4 lines

+        authentication_failed(vs);
+        return;
+    }
+

This part is weird for me: if auth fails we send "vnc_write_u32(vs, 1)" but if it succeeds we send the challenge. There is no success value to send (like "vnc_write_u32(vs, 0)") ?

Quoted 7 lines

There is, but this code is a mess of callbacks. In this case it happens toward the end of protocol_client_auth_vnc:

    2604         trace_vnc_auth_pass(vs, vs->auth);
    2605         vnc_write_u32(vs, 0); /* Accept auth */
    2606         vnc_flush(vs);

ok, thanks.

#23 lore raw

PATCH v4 10/24 util: Add qemu_guest_getrandom and associated routines

In reply to Richard Henderson

This routine is intended to produce high-quality random numbers to the guest. Normally, such numbers are crypto quality from the host, but a command-line option can force the use of a fully deterministic sequence for use while debugging.

---
 include/qemu/guest-random.h | 68 +++++++++++++++++++++++++++
 util/guest-random.c         | 93 +++++++++++++++++++++++++++++++++++++
 util/Makefile.objs          |  1 +
 3 files changed, 162 insertions(+)
 create mode 100644 include/qemu/guest-random.h
 create mode 100644 util/guest-random.c
include/qemu/guest-random.h new file +68 -0
new file mode 100644
index 0000000000..09ff9c2236
@@ -0,0 +1,68 @@
+/*
+ * QEMU guest-visible random functions
+ *
+ * Copyright 2019 Linaro, Ltd.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the Free
+ * Software Foundation; either version 2 of the License, or (at your option)
+ * any later version.
+ */
+
+#ifndef QEMU_GUEST_RANDOM_H
+#define QEMU_GUEST_RANDOM_H
+
+/**
+ * qemu_guest_random_seed_main(const char *optarg, Error **errp)
+ * @optarg: a non-NULL pointer to a C string
+ * @errp: an error indicator
+ *
+ * The @optarg value is that which accompanies the -seed argument.
+ * This forces qemu_guest_getrandom into deterministic mode.
+ *
+ * Returns 0 on success, < 0 on failure while setting *errp.
+ */
+int qemu_guest_random_seed_main(const char *optarg, Error **errp);
+
+/**
+ * qemu_guest_random_seed_thread_part1(void)
+ *
+ * If qemu_getrandom is in deterministic mode, returns an
+ * independent seed for the new thread.  Otherwise returns 0.
+ */
+uint64_t qemu_guest_random_seed_thread_part1(void);
+
+/**
+ * qemu_guest_random_seed_thread_part2(uint64_t seed)
+ * @seed: a value for the new thread.
+ *
+ * If qemu_guest_getrandom is in deterministic mode, this stores an
+ * independent seed for the new thread.  Otherwise a no-op.
+ */
+void qemu_guest_random_seed_thread_part2(uint64_t seed);
+
+/**
+ * qemu_guest_getrandom(void *buf, size_t len, Error **errp)
+ * @buf: a buffer of bytes to be written
+ * @len: the number of bytes in @buf
+ * @errp: an error indicator
+ *
+ * Fills len bytes in buf with random data.  This should only be used
+ * for data presented to the guest.  Host-side crypto services should
+ * use qcrypto_random_bytes.
+ *
+ * Returns 0 on success, < 0 on failure while setting *errp.
+ */
+int qemu_guest_getrandom(void *buf, size_t len, Error **errp);
+
+/**
+ * qemu_guest_getrandom_nofail(void *buf, size_t len)
+ * @buf: a buffer of bytes to be written
+ * @len: the number of bytes in @buf
+ *
+ * Like qemu_guest_getrandom, but will assert for failure.
+ * Use this when there is no reasonable recovery.
+ */
+void qemu_guest_getrandom_nofail(void *buf, size_t len);
+
+#endif /* QEMU_GUEST_RANDOM_H */
util/guest-random.c new file +93 -0

93 lines not on this page · raw message

util/Makefile.objs +1 -0
index 9206878dec..c27a923dbe 100644
@@ -54,5 +54,6 @@ util-obj-y += iova-tree.o
 util-obj-$(CONFIG_INOTIFY1) += filemonitor-inotify.o
 util-obj-$(CONFIG_LINUX) += vfio-helpers.o
 util-obj-$(CONFIG_OPENGL) += drm.o
+util-obj-y += guest-random.o
 
 stub-obj-y += filemonitor-stub.o
Signature · 1 line
2.17.1
Reviewed-by on v4 10/24
#24 lore raw

Re: [Qemu-devel] [PATCH v4 10/24] util: Add qemu_guest_getrandom and associated routines

Quoted 8 lines · Richard Henderson

This routine is intended to produce high-quality random numbers to the guest. Normally, such numbers are crypto quality from the host, but a command-line option can force the use of a fully deterministic sequence for use while debugging.

Quoted 7 lines
---
  include/qemu/guest-random.h | 68 +++++++++++++++++++++++++++
  util/guest-random.c         | 93 +++++++++++++++++++++++++++++++++++++
  util/Makefile.objs          |  1 +
  3 files changed, 162 insertions(+)

create mode 100644 include/qemu/guest-random.h
create mode 100644 util/guest-random.c

#25 lore raw

PATCH v4 11/24 cpus: Initialize pseudo-random seeds for all guest cpus

In reply to Richard Henderson

When the -seed option is given, call qemu_guest_random_seed_main, putting the subsystem into deterministic mode. Pass derived seeds to each cpu created; which is a no-op unless the subsystem is in deterministic mode.

---
 include/qom/cpu.h |  1 +
 cpus.c            |  9 +++++++++
 vl.c              |  4 ++++
 qemu-options.hx   | 10 ++++++++++
 4 files changed, 24 insertions(+)
include/qom/cpu.h +1 -0
index 08abcbd3fe..9793ec39bc 100644
@@ -369,6 +369,7 @@ struct CPUState {
     int singlestep_enabled;
     int64_t icount_budget;
     int64_t icount_extra;
+    uint64_t random_seed;
     sigjmp_buf jmp_env;
 
     QemuMutex work_mutex;
cpus.c +9 -0
index e58e7ab0f6..ffc57119ca 100644
@@ -50,6 +50,7 @@
 #include "qemu/option.h"
 #include "qemu/bitmap.h"
 #include "qemu/seqlock.h"
+#include "qemu/guest-random.h"
 #include "tcg.h"
 #include "hw/nmi.h"
 #include "sysemu/replay.h"
@@ -1276,6 +1277,7 @@ static void *qemu_kvm_cpu_thread_fn(void *arg)
     /* signal CPU creation */
     cpu->created = true;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     do {
         if (cpu_can_run(cpu)) {
@@ -1319,6 +1321,7 @@ static void *qemu_dummy_cpu_thread_fn(void *arg)
     /* signal CPU creation */
     cpu->created = true;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     do {
         qemu_mutex_unlock_iothread();
@@ -1478,6 +1481,7 @@ static void *qemu_tcg_rr_cpu_thread_fn(void *arg)
     cpu->created = true;
     cpu->can_do_io = 1;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     /* wait for initial kick-off after machine start */
     while (first_cpu->stopped) {
@@ -1592,6 +1596,7 @@ static void *qemu_hax_cpu_thread_fn(void *arg)
 
     hax_init_vcpu(cpu);
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     do {
         if (cpu_can_run(cpu)) {
@@ -1631,6 +1636,7 @@ static void *qemu_hvf_cpu_thread_fn(void *arg)
     /* signal CPU creation */
     cpu->created = true;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     do {
         if (cpu_can_run(cpu)) {
@@ -1671,6 +1677,7 @@ static void *qemu_whpx_cpu_thread_fn(void *arg)
     /* signal CPU creation */
     cpu->created = true;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     do {
         if (cpu_can_run(cpu)) {
@@ -1724,6 +1731,7 @@ static void *qemu_tcg_cpu_thread_fn(void *arg)
     cpu->can_do_io = 1;
     current_cpu = cpu;
     qemu_cond_signal(&qemu_cpu_cond);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
 
     /* process any pending work */
     cpu->exit_request = 1;
@@ -2071,6 +2079,7 @@ void qemu_init_vcpu(CPUState *cpu)
     cpu->nr_cores = smp_cores;
     cpu->nr_threads = smp_threads;
     cpu->stopped = true;
+    cpu->random_seed = qemu_guest_random_seed_thread_part1();
 
     if (!cpu->as) {
         /* If the target cpu hasn't set up any address spaces itself,
vl.c +4 -0
index d9fea0a119..d847b3ebad 100644
@@ -128,6 +128,7 @@ int main(int argc, char **argv)
 #include "qapi/qapi-commands-ui.h"
 #include "qapi/qmp/qerror.h"
 #include "sysemu/iothread.h"
+#include "qemu/guest-random.h"
 
 #define MAX_VIRTIO_CONSOLES 1
 
@@ -3319,6 +3320,9 @@ int main(int argc, char **argv, char **envp)
             case QEMU_OPTION_DFILTER:
                 qemu_set_dfilter_ranges(optarg, &error_fatal);
                 break;
+            case QEMU_OPTION_seed:
+                qemu_guest_random_seed_main(optarg, &error_fatal);
+                break;
             case QEMU_OPTION_s:
                 add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
                 break;
qemu-options.hx +10 -0
index 51802cbb26..0191ef8b1e 100644
@@ -3601,6 +3601,16 @@ the 0x200 sized block starting at 0xffffffc000080000 and another 0x1000 sized
 block starting at 0xffffffc00005f000.
 ETEXI
 
+DEF("seed", HAS_ARG, QEMU_OPTION_seed, \
+    "-seed number       seed the pseudo-random number generator\n",
+    QEMU_ARCH_ALL)
+STEXI
+@item -seed @var{number}
+@findex -seed
+Force the guest to use a deterministic pseudo-random number generator, seeded
+with @var{number}.  This does not affect crypto routines within the host.
+ETEXI
+
 DEF("L", HAS_ARG, QEMU_OPTION_L, \
     "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n",
     QEMU_ARCH_ALL)
Signature · 1 line
2.17.1
Reviewed-by on v4 11/24
#26 lore raw

Re: [Qemu-devel] [PATCH v4 11/24] cpus: Initialize pseudo-random seeds for all guest cpus

Quoted 8 lines · Richard Henderson

When the -seed option is given, call qemu_guest_random_seed_main, putting the subsystem into deterministic mode. Pass derived seeds to each cpu created; which is a no-op unless the subsystem is in deterministic mode.

Quoted 7 lines
---
  include/qom/cpu.h |  1 +
  cpus.c            |  9 +++++++++
  vl.c              |  4 ++++
  qemu-options.hx   | 10 ++++++++++
  4 files changed, 24 insertions(+)
#27 lore raw

PATCH v4 12/24 linux-user: Initialize pseudo-random seeds for all guest cpus

In reply to Richard Henderson

When the -seed option is given, call qemu_guest_random_seed_main, putting the subsystem into deterministic mode. Pass derived seeds to each cpu created during clone; which is a no-op unless the subsystem is in deterministic mode.

---
 linux-user/main.c    | 21 ++++++++++-----------
 linux-user/syscall.c |  3 +++
 2 files changed, 13 insertions(+), 11 deletions(-)
linux-user/main.c +10 -11
index 3d2230320b..7dfb202e5d 100644
@@ -34,6 +34,7 @@
 #include "tcg.h"
 #include "qemu/timer.h"
 #include "qemu/envlist.h"
+#include "qemu/guest-random.h"
 #include "elf.h"
 #include "trace/control.h"
 #include "target_elf.h"
@@ -48,6 +49,7 @@ static int gdbstub_port;
 static envlist_t *envlist;
 static const char *cpu_model;
 static const char *cpu_type;
+static const char *seed_optarg;
 unsigned long mmap_min_addr;
 unsigned long guest_base;
 int have_guest_base;
@@ -290,15 +292,9 @@ static void handle_arg_pagesize(const char *arg)
     }
 }
 
-static void handle_arg_randseed(const char *arg)
+static void handle_arg_seed(const char *arg)
 {
-    unsigned long long seed;
-
-    if (parse_uint_full(arg, &seed, 0) != 0 || seed > UINT_MAX) {
-        fprintf(stderr, "Invalid seed number: %s\n", arg);
-        exit(EXIT_FAILURE);
-    }
-    srand(seed);
+    seed_optarg = arg;
 }
 
 static void handle_arg_gdb(const char *arg)
@@ -433,7 +429,7 @@ static const struct qemu_argument arg_table[] = {
      "",           "run in singlestep mode"},
     {"strace",     "QEMU_STRACE",      false, handle_arg_strace,
      "",           "log system calls"},
-    {"seed",       "QEMU_RAND_SEED",   true,  handle_arg_randseed,
+    {"seed",       "QEMU_RAND_SEED",   true,  handle_arg_seed,
      "",           "Seed for pseudo-random number generator"},
     {"trace",      "QEMU_TRACE",       true,  handle_arg_trace,
      "",           "[[enable=]<pattern>][,events=<file>][,file=<file>]"},
@@ -689,8 +685,11 @@ int main(int argc, char **argv, char **envp)
         do_strace = 1;
     }
 
-    if (getenv("QEMU_RAND_SEED")) {
-        handle_arg_randseed(getenv("QEMU_RAND_SEED"));
+    if (seed_optarg == NULL) {
+        seed_optarg = getenv("QEMU_RAND_SEED");
+    }
+    if (seed_optarg != NULL) {
+        qemu_guest_random_seed_main(seed_optarg, &error_fatal);
     }
 
     target_environ = envlist_to_environ(envlist, NULL);
linux-user/syscall.c +3 -0
index 96cd4bf86d..ce377b2fc1 100644
@@ -110,6 +110,7 @@
 #include "uname.h"
 
 #include "qemu.h"
+#include "qemu/guest-random.h"
 #include "fd-trans.h"
 
 #ifndef CLONE_IO
@@ -5441,6 +5442,7 @@ static void *clone_func(void *arg)
         put_user_u32(info->tid, info->child_tidptr);
     if (info->parent_tidptr)
         put_user_u32(info->tid, info->parent_tidptr);
+    qemu_guest_random_seed_thread_part2(cpu->random_seed);
     /* Enable signals.  */
     sigprocmask(SIG_SETMASK, &info->sigmask, NULL);
     /* Signal to the parent that we're ready.  */
@@ -5527,6 +5529,7 @@ static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
            initializing, so temporarily block all signals.  */
         sigfillset(&sigmask);
         sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);
+        cpu->random_seed = qemu_guest_random_seed_thread_part1();
 
         /* If this is our first additional thread, we need to ensure we
          * generate code for parallel execution and flush old translations.
Signature · 1 line
2.17.1
#28 lore raw

Re: [Qemu-devel] [PATCH v4 12/24] linux-user: Initialize pseudo-random seeds for all guest cpus

Quoted 37 lines · Richard Henderson

When the -seed option is given, call qemu_guest_random_seed_main, putting the subsystem into deterministic mode. Pass derived seeds to each cpu created during clone; which is a no-op unless the subsystem is in deterministic mode.

---
  linux-user/main.c    | 21 ++++++++++-----------
  linux-user/syscall.c |  3 +++
  2 files changed, 13 insertions(+), 11 deletions(-)
linux-user/main.c +2 -0
index 3d2230320b..7dfb202e5d 100644
@@ -34,6 +34,7 @@
  #include "tcg.h"
  #include "qemu/timer.h"
  #include "qemu/envlist.h"
+#include "qemu/guest-random.h"
  #include "elf.h"
  #include "trace/control.h"
  #include "target_elf.h"
@@ -48,6 +49,7 @@ static int gdbstub_port;
  static envlist_t *envlist;
  static const char *cpu_model;
  static const char *cpu_type;
+static const char *seed_optarg;
  unsigned long mmap_min_addr;
  unsigned long guest_base;
  int have_guest_base;
@@ -290,15 +292,9 @@ static void handle_arg_pagesize(const char *arg)
      }
  }
 

linux-user/main.c static void handle_arg_pagesize(const char *arg) · line 301

Quoted 10 lines
linux-user/main.c +1 -8
-static void handle_arg_randseed(const char *arg)
+static void handle_arg_seed(const char *arg)
  {
-    unsigned long long seed;
-
-    if (parse_uint_full(arg, &seed, 0) != 0 || seed > UINT_MAX) {
-        fprintf(stderr, "Invalid seed number: %s\n", arg);
-        exit(EXIT_FAILURE);
-    }
-    srand(seed);

It's a detail, but I think you can't remove this srand() in this patch: you initialize qemu_guest_random() sequence but the code continues to use rand() to have a random number, so the seed value is in fact ignored. you can remove it in PATCH 16.

Thanks,
Laurent

#29 lore raw

PATCH v4 13/24 linux-user: Call qcrypto_init if not using -seed

In reply to Richard Henderson
---
 linux-user/main.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)
linux-user/main.c +13 -2
index 7dfb202e5d..e05aebe4e1 100644
@@ -39,6 +39,7 @@
 #include "trace/control.h"
 #include "target_elf.h"
 #include "cpu_loop-common.h"
+#include "crypto/init.h"
 
 char *exec_path;
 
@@ -688,8 +689,18 @@ int main(int argc, char **argv, char **envp)
     if (seed_optarg == NULL) {
         seed_optarg = getenv("QEMU_RAND_SEED");
     }
-    if (seed_optarg != NULL) {
-        qemu_guest_random_seed_main(seed_optarg, &error_fatal);
+    {
+        Error *err = NULL;
+        if (seed_optarg != NULL) {
+            qemu_guest_random_seed_main(seed_optarg, &err);
+        } else {
+            /* ??? Assumes qcrypto is only used by qemu_guest_getrandom.  */
+            qcrypto_init(&err);
+        }
+        if (err) {
+            error_reportf_err(err, "cannot initialize crypto: ");
+            exit(1);
+        }
     }
 
     target_environ = envlist_to_environ(envlist, NULL);
Signature · 1 line
2.17.1
#30 lore raw

Re: [Qemu-devel] [PATCH v4 13/24] linux-user: Call qcrypto_init if not using -seed

Quoted 21 lines · Richard Henderson
---
  linux-user/main.c | 15 +++++++++++++--
  1 file changed, 13 insertions(+), 2 deletions(-)
linux-user/main.c +1 -0
index 7dfb202e5d..e05aebe4e1 100644
@@ -39,6 +39,7 @@
  #include "trace/control.h"
  #include "target_elf.h"
  #include "cpu_loop-common.h"
+#include "crypto/init.h"
 
  char *exec_path;
 
@@ -688,8 +689,18 @@ int main(int argc, char **argv, char **envp)
      if (seed_optarg == NULL) {

linux-user/main.c int main(int argc, char **argv, char **envp) · line 697

Quoted 10 lines
linux-user/main.c +6 -2
          seed_optarg = getenv("QEMU_RAND_SEED");
      }
-    if (seed_optarg != NULL) {
-        qemu_guest_random_seed_main(seed_optarg, &error_fatal);
+    {
+        Error *err = NULL;
+        if (seed_optarg != NULL) {
+            qemu_guest_random_seed_main(seed_optarg, &err);
+        } else {
+            /* ??? Assumes qcrypto is only used by qemu_guest_getrandom.  */

perhaps you can add a qemu_guest_random_init() function close to this assumption to call qcrypto_init()? So we will not forget to change this if we use something else in the future.

linux-user/main.c int main(int argc, char **argv, char **envp) · line 706

Quoted 10 lines
linux-user/main.c +6 -0
+            qcrypto_init(&err);
+        }
+        if (err) {
+            error_reportf_err(err, "cannot initialize crypto: ");
+            exit(1);
+        }
      }
 
      target_environ = envlist_to_environ(envlist, NULL);

Thanks,
Laurent

#31 lore raw

Re: [Qemu-devel] [PATCH v4 13/24] linux-user: Call qcrypto_init if not using -seed

Quoted 9 lines · Laurent Vivier
Quoted 8 lines

-    if (seed_optarg != NULL) {
-        qemu_guest_random_seed_main(seed_optarg, &error_fatal); +    {
+        Error *err = NULL;
+        if (seed_optarg != NULL) {
+            qemu_guest_random_seed_main(seed_optarg, &err);
+        } else {
+            /* ??? Assumes qcrypto is only used by qemu_guest_getrandom.  */

Quoted 3 lines

perhaps you can add a qemu_guest_random_init() function close to this assumption to call qcrypto_init()? So we will not forget to change this if we use something else in the future.

I'm not sure what you're suggesting.

Why would putting qcrypto_init within qemu_guest_random_init make it more likely that, if something else within linux-user required qcrypto routines, we would remember to remove qemu_guest_random_init and call qcrypto_init exactly once?

r~

Reviewed-by
#32 lore raw

Re: [Qemu-devel] [PATCH v4 13/24] linux-user: Call qcrypto_init if not using -seed

Quoted 14 lines · Richard Henderson
Quoted 9 lines · Laurent Vivier
Quoted 8 lines

-    if (seed_optarg != NULL) {
-        qemu_guest_random_seed_main(seed_optarg, &error_fatal); +    {
+        Error *err = NULL;
+        if (seed_optarg != NULL) {
+            qemu_guest_random_seed_main(seed_optarg, &err);
+        } else {
+            /* ??? Assumes qcrypto is only used by qemu_guest_getrandom.  */

Quoted 3 lines

perhaps you can add a qemu_guest_random_init() function close to this assumption to call qcrypto_init()? So we will not forget to change this if we use something else in the future.

Quoted 5 lines

I'm not sure what you're suggesting.

Why would putting qcrypto_init within qemu_guest_random_init make it more likely that, if something else within linux-user required qcrypto routines, we would remember to remove qemu_guest_random_init and call qcrypto_init exactly once?

Why would we need qcrypto routines rather than qemu_guest_getrandom()?
The idea was if qemu_guest_getrandom() stops to use qcrypto we don't forget to remove this call.

But it's only cosmetic, so:

#33 lore raw

PATCH v4 14/24 linux-user: Use qemu_guest_getrandom_nofail for AT_RANDOM

In reply to Richard Henderson

Use a better interface for random numbers than rand * 16.

---
 linux-user/elfload.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
linux-user/elfload.c +3 -5
index c1a26021f8..e673f7ea55 100644
@@ -7,6 +7,7 @@
 #include "qemu.h"
 #include "disas/disas.h"
 #include "qemu/path.h"
+#include "qemu/guest-random.h"
 
 #ifdef _ARCH_PPC64
 #undef ARCH_DLINFO
@@ -1883,12 +1884,9 @@ static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
     }
 
     /*
-     * Generate 16 random bytes for userspace PRNG seeding (not
-     * cryptically secure but it's not the aim of QEMU).
+     * Generate 16 random bytes for userspace PRNG seeding.
      */
-    for (i = 0; i < 16; i++) {
-        k_rand_bytes[i] = rand();
-    }
+    qemu_guest_getrandom_nofail(k_rand_bytes, sizeof(k_rand_bytes));
     if (STACK_GROWS_DOWN) {
         sp -= 16;
         u_rand_bytes = sp;
Signature · 1 line
2.17.1
Reviewed-by on v4 14/24
#34 lore raw

Re: [Qemu-devel] [PATCH v4 14/24] linux-user: Use qemu_guest_getrandom_nofail for AT_RANDOM

Quoted 27 lines · Richard Henderson

Use a better interface for random numbers than rand * 16.

---
  linux-user/elfload.c | 8 +++-----
  1 file changed, 3 insertions(+), 5 deletions(-)
linux-user/elfload.c +1 -1
index c1a26021f8..e673f7ea55 100644
@@ -7,6 +7,7 @@
  #include "qemu.h"
  #include "disas/disas.h"
  #include "qemu/path.h"
+#include "qemu/guest-random.h"
 
  #ifdef _ARCH_PPC64
  #undef ARCH_DLINFO
@@ -1883,12 +1884,9 @@ static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc,
      }
 
      /*
-     * Generate 16 random bytes for userspace PRNG seeding (not

linux-user/elfload.c static abi_ulong create_elf_tables(abi_ulong p, int argc, int envc, · line 1892

Quoted 10 lines
linux-user/elfload.c +2 -4
-     * cryptically secure but it's not the aim of QEMU).
+     * Generate 16 random bytes for userspace PRNG seeding.
       */
-    for (i = 0; i < 16; i++) {
-        k_rand_bytes[i] = rand();
-    }
+    qemu_guest_getrandom_nofail(k_rand_bytes, sizeof(k_rand_bytes));
      if (STACK_GROWS_DOWN) {
          sp -= 16;
          u_rand_bytes = sp;
#35 lore raw

PATCH v4 15/24 linux-user/aarch64: Use qemu_guest_getrandom for PAUTH keys

In reply to Richard Henderson

Use a better interface for random numbers than rand() * 3.

---
 linux-user/aarch64/target_syscall.h |  2 --
 linux-user/aarch64/cpu_loop.c       | 29 ++++++---------------------
 linux-user/syscall.c                | 31 ++++++++++++++++++++++++-----
 3 files changed, 32 insertions(+), 30 deletions(-)
linux-user/aarch64/target_syscall.h +0 -2
index b595e5da82..995e475c73 100644
@@ -29,6 +29,4 @@ struct target_pt_regs {
 # define TARGET_PR_PAC_APDBKEY   (1 << 3)
 # define TARGET_PR_PAC_APGAKEY   (1 << 4)
 
-void arm_init_pauth_key(ARMPACKey *key);
-
 #endif /* AARCH64_TARGET_SYSCALL_H */
linux-user/aarch64/cpu_loop.c +6 -23
index d75fd9d3e2..cedad39ca0 100644
@@ -20,6 +20,7 @@
 #include "qemu/osdep.h"
 #include "qemu.h"
 #include "cpu_loop-common.h"
+#include "qemu/guest-random.h"
 
 #define get_user_code_u32(x, gaddr, env)                \
     ({ abi_long __r = get_user_u32((x), (gaddr));       \
@@ -147,24 +148,6 @@ void cpu_loop(CPUARMState *env)
     }
 }
 
-static uint64_t arm_rand64(void)
-{
-    int shift = 64 - clz64(RAND_MAX);
-    int i, n = 64 / shift + (64 % shift != 0);
-    uint64_t ret = 0;
-
-    for (i = 0; i < n; i++) {
-        ret = (ret << shift) | rand();
-    }
-    return ret;
-}
-
-void arm_init_pauth_key(ARMPACKey *key)
-{
-    key->lo = arm_rand64();
-    key->hi = arm_rand64();
-}
-
 void target_cpu_copy_regs(CPUArchState *env, struct target_pt_regs *regs)
 {
     ARMCPU *cpu = arm_env_get_cpu(env);
@@ -192,11 +175,11 @@ void target_cpu_copy_regs(CPUArchState *env, struct target_pt_regs *regs)
 #endif
 
     if (cpu_isar_feature(aa64_pauth, cpu)) {
-        arm_init_pauth_key(&env->apia_key);
-        arm_init_pauth_key(&env->apib_key);
-        arm_init_pauth_key(&env->apda_key);
-        arm_init_pauth_key(&env->apdb_key);
-        arm_init_pauth_key(&env->apga_key);
+        qemu_guest_getrandom_nofail(&env->apia_key, sizeof(ARMPACKey));
+        qemu_guest_getrandom_nofail(&env->apib_key, sizeof(ARMPACKey));
+        qemu_guest_getrandom_nofail(&env->apda_key, sizeof(ARMPACKey));
+        qemu_guest_getrandom_nofail(&env->apdb_key, sizeof(ARMPACKey));
+        qemu_guest_getrandom_nofail(&env->apga_key, sizeof(ARMPACKey));
     }
 
     ts->stack_base = info->start_stack;
linux-user/syscall.c +26 -5
index ce377b2fc1..b73d1d9f65 100644
@@ -111,6 +111,7 @@
 
 #include "qemu.h"
 #include "qemu/guest-random.h"
+#include "qapi/error.h"
 #include "fd-trans.h"
 
 #ifndef CLONE_IO
@@ -9724,25 +9725,45 @@ static abi_long do_syscall1(void *cpu_env, int num, abi_long arg1,
                     int all = (TARGET_PR_PAC_APIAKEY | TARGET_PR_PAC_APIBKEY |
                                TARGET_PR_PAC_APDAKEY | TARGET_PR_PAC_APDBKEY |
                                TARGET_PR_PAC_APGAKEY);
+                    int ret = 0;
+                    Error *err = NULL;
+
                     if (arg2 == 0) {
                         arg2 = all;
                     } else if (arg2 & ~all) {
                         return -TARGET_EINVAL;
                     }
                     if (arg2 & TARGET_PR_PAC_APIAKEY) {
-                        arm_init_pauth_key(&env->apia_key);
+                        ret |= qemu_guest_getrandom(&env->apia_key,
+                                                    sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APIBKEY) {
-                        arm_init_pauth_key(&env->apib_key);
+                        ret |= qemu_guest_getrandom(&env->apib_key,
+                                                    sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APDAKEY) {
-                        arm_init_pauth_key(&env->apda_key);
+                        ret |= qemu_guest_getrandom(&env->apda_key,
+                                                    sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APDBKEY) {
-                        arm_init_pauth_key(&env->apdb_key);
+                        ret |= qemu_guest_getrandom(&env->apdb_key,
+                                                    sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APGAKEY) {
-                        arm_init_pauth_key(&env->apga_key);
+                        ret |= qemu_guest_getrandom(&env->apga_key,
+                                                    sizeof(ARMPACKey), &err);
+                    }
+                    if (ret != 0) {
+                        /*
+                         * Some unknown failure in the crypto.  The best
+                         * we can do is log it and fail the syscall.
+                         * The real syscall cannot fail this way.
+                         */
+                        qemu_log_mask(LOG_UNIMP,
+                                      "PR_PAC_RESET_KEYS: Crypto failure: %s",
+                                      error_get_pretty(err));
+                        error_free(err);
+                        return -TARGET_EIO;
                     }
                     return 0;
                 }
Signature · 1 line
2.17.1
Reviewed-by on v4 15/24
#36 lore raw

Re: [Qemu-devel] [PATCH v4 15/24] linux-user/aarch64: Use qemu_guest_getrandom for PAUTH keys

Quoted 11 lines · Richard Henderson

Use a better interface for random numbers than rand() * 3.

---
  linux-user/aarch64/target_syscall.h |  2 --
  linux-user/aarch64/cpu_loop.c       | 29 ++++++---------------------
  linux-user/syscall.c                | 31 ++++++++++++++++++++++++-----
  3 files changed, 32 insertions(+), 30 deletions(-)
#37 lore raw

PATCH v4 16/24 linux-user: Remove srand call

In reply to Richard Henderson

We no longer use rand() within linux-user.

---
 linux-user/main.c | 2 --
 1 file changed, 2 deletions(-)
linux-user/main.c +0 -2
index e05aebe4e1..5d1c6a115b 100644
@@ -623,8 +623,6 @@ int main(int argc, char **argv, char **envp)
 
     cpu_model = NULL;
 
-    srand(time(NULL));
-
     qemu_add_opts(&qemu_trace_opts);
 
     optind = parse_args(argc, argv);
Signature · 1 line
2.17.1
#38 lore raw

Re: [Qemu-devel] [PATCH v4 16/24] linux-user: Remove srand call

Quoted 15 lines · Richard Henderson

We no longer use rand() within linux-user.

---
  linux-user/main.c | 2 --
  1 file changed, 2 deletions(-)
linux-user/main.c +0 -0
index e05aebe4e1..5d1c6a115b 100644

linux-user/main.c int main(int argc, char **argv, char **envp) · line 628

Quoted 8 lines
linux-user/main.c +0 -2
@@ -623,8 +623,6 @@ int main(int argc, char **argv, char **envp)
 
      cpu_model = NULL;
 
-    srand(time(NULL));
-
      qemu_add_opts(&qemu_trace_opts);
 
      optind = parse_args(argc, argv);

Move the one from PATCH 12 here.

Thanks,
Laurent

#39 lore raw

PATCH v4 17/24 aspeed/scu: Use qemu_guest_getrandom_nofail

In reply to Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of rolling our own error handling locally.

---
 hw/misc/aspeed_scu.c | 10 ++--------
 1 file changed, 2 insertions(+), 8 deletions(-)
hw/misc/aspeed_scu.c +2 -8
index c8217740ef..ab1e18ed4b 100644
@@ -16,7 +16,7 @@
 #include "qapi/visitor.h"
 #include "qemu/bitops.h"
 #include "qemu/log.h"
-#include "crypto/random.h"
+#include "qemu/guest-random.h"
 #include "trace.h"
 
 #define TO_REG(offset) ((offset) >> 2)
@@ -157,14 +157,8 @@ static const uint32_t ast2500_a1_resets[ASPEED_SCU_NR_REGS] = {
 
 static uint32_t aspeed_scu_get_random(void)
 {
-    Error *err = NULL;
     uint32_t num;
-
-    if (qcrypto_random_bytes((uint8_t *)&num, sizeof(num), &err)) {
-        error_report_err(err);
-        exit(1);
-    }
-
+    qemu_guest_getrandom_nofail(&num, sizeof(num));
     return num;
 }
 
Signature · 1 line
2.17.1
Reviewed-by on v4 17/24
#40 lore raw

Re: [Qemu-arm] [Qemu-devel] [PATCH v4 17/24] aspeed/scu: Use qemu_guest_getrandom_nofail

Quoted 10 lines · Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of rolling our own error handling locally.

Quoted 3 lines
---
  hw/misc/aspeed_scu.c | 10 ++--------
  1 file changed, 2 insertions(+), 8 deletions(-)
#41 lore raw

PATCH v4 18/24 hw/misc/nrf51_rng: Use qemu_guest_getrandom_nofail

In reply to Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of error_abort directly.

---
 hw/misc/nrf51_rng.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
hw/misc/nrf51_rng.c +2 -2
index d188f044f4..3400e90a9b 100644
@@ -14,7 +14,7 @@
 #include "qapi/error.h"
 #include "hw/arm/nrf51.h"
 #include "hw/misc/nrf51_rng.h"
-#include "crypto/random.h"
+#include "qemu/guest-random.h"
 
 static void update_irq(NRF51RNGState *s)
 {
@@ -145,7 +145,7 @@ static void nrf51_rng_timer_expire(void *opaque)
 {
     NRF51RNGState *s = NRF51_RNG(opaque);
 
-    qcrypto_random_bytes(&s->value, 1, &error_abort);
+    qemu_guest_getrandom_nofail(&s->value, 1);
 
     s->event_valrdy = 1;
     qemu_set_irq(s->eep_valrdy, 1);
Signature · 1 line
2.17.1
Reviewed-by on v4 18/24
#42 lore raw

Re: [Qemu-arm] [Qemu-devel] [PATCH v4 18/24] hw/misc/nrf51_rng: Use qemu_guest_getrandom_nofail

Quoted 11 lines · Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of error_abort directly.

---
  hw/misc/nrf51_rng.c | 4 ++--
  1 file changed, 2 insertions(+), 2 deletions(-)
#43 lore raw

PATCH v4 19/24 hw/misc/bcm2835_rng: Use qemu_guest_getrandom_nofail

In reply to Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of rolling our own error handling locally.

---
 hw/misc/bcm2835_rng.c | 32 ++++++++++++++------------------
 1 file changed, 14 insertions(+), 18 deletions(-)
hw/misc/bcm2835_rng.c +14 -18
index 4d62143b24..fe59c868f5 100644
@@ -9,30 +9,26 @@
 
 #include "qemu/osdep.h"
 #include "qemu/log.h"
-#include "qapi/error.h"
-#include "crypto/random.h"
+#include "qemu/guest-random.h"
 #include "hw/misc/bcm2835_rng.h"
 
 static uint32_t get_random_bytes(void)
 {
     uint32_t res;
-    Error *err = NULL;
 
-    if (qcrypto_random_bytes((uint8_t *)&res, sizeof(res), &err) < 0) {
-        /* On failure we don't want to return the guest a non-random
-         * value in case they're really using it for cryptographic
-         * purposes, so the best we can do is die here.
-         * This shouldn't happen unless something's broken.
-         * In theory we could implement this device's full FIFO
-         * and interrupt semantics and then just stop filling the
-         * FIFO. That's a lot of work, though, so we assume any
-         * errors are systematic problems and trust that if we didn't
-         * fail as the guest inited then we won't fail later on
-         * mid-run.
-         */
-        error_report_err(err);
-        exit(1);
-    }
+    /*
+     * On failure we don't want to return the guest a non-random
+     * value in case they're really using it for cryptographic
+     * purposes, so the best we can do is die here.
+     * This shouldn't happen unless something's broken.
+     * In theory we could implement this device's full FIFO
+     * and interrupt semantics and then just stop filling the
+     * FIFO. That's a lot of work, though, so we assume any
+     * errors are systematic problems and trust that if we didn't
+     * fail as the guest inited then we won't fail later on
+     * mid-run.
+     */
+    qemu_guest_getrandom_nofail(&res, sizeof(res));
     return res;
 }
 
Signature · 1 line
2.17.1
Reviewed-by on v4 19/24
#44 lore raw

Re: [Qemu-arm] [Qemu-devel] [PATCH v4 19/24] hw/misc/bcm2835_rng: Use qemu_guest_getrandom_nofail

Quoted 11 lines · Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility. Use the *_nofail routine instead of rolling our own error handling locally.

---
  hw/misc/bcm2835_rng.c | 32 ++++++++++++++------------------
  1 file changed, 14 insertions(+), 18 deletions(-)
#45 lore raw

PATCH v4 20/24 hw/misc/exynos4210_rng: Use qemu_guest_getrandom

In reply to Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility.

---
 hw/misc/exynos4210_rng.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
hw/misc/exynos4210_rng.c +4 -7
index 4ecbebd2d7..0e70ffb404 100644
@@ -18,10 +18,10 @@
  */
 
 #include "qemu/osdep.h"
-#include "crypto/random.h"
 #include "hw/sysbus.h"
 #include "qapi/error.h"
 #include "qemu/log.h"
+#include "qemu/guest-random.h"
 
 #define DEBUG_EXYNOS_RNG 0
 
@@ -109,7 +109,6 @@ static void exynos4210_rng_set_seed(Exynos4210RngState *s, unsigned int i,
 static void exynos4210_rng_run_engine(Exynos4210RngState *s)
 {
     Error *err = NULL;
-    int ret;
 
     /* Seed set? */
     if ((s->reg_status & EXYNOS4210_RNG_STATUS_SEED_SETTING_DONE) == 0) {
@@ -127,13 +126,11 @@ static void exynos4210_rng_run_engine(Exynos4210RngState *s)
     }
 
     /* Get randoms */
-    ret = qcrypto_random_bytes((uint8_t *)s->randr_value,
-                               sizeof(s->randr_value), &err);
-    if (!ret) {
+    if (qemu_guest_getrandom(s->randr_value, sizeof(s->randr_value), &err)) {
+        error_report_err(err);
+    } else {
         /* Notify that PRNG is ready */
         s->reg_status |= EXYNOS4210_RNG_STATUS_PRNG_DONE;
-    } else {
-        error_report_err(err);
     }
 
 out:
Signature · 1 line
2.17.1
Reviewed-by on v4 20/24
#46 lore raw

Re: [Qemu-devel] [PATCH v4 20/24] hw/misc/exynos4210_rng: Use qemu_guest_getrandom

Quoted 11 lines · Richard Henderson

The random number is intended for use by the guest. As such, we should honor the -seed argument for reproducibility.

---
  hw/misc/exynos4210_rng.c | 11 ++++-------
  1 file changed, 4 insertions(+), 7 deletions(-)
#47 lore raw

PATCH v4 21/24 target/arm: Put all PAC keys into a structure

In reply to Richard Henderson

This allows us to use a single syscall to initialize them all.

---
 target/arm/cpu.h              | 12 +++++++-----
 linux-user/aarch64/cpu_loop.c |  6 +-----
 linux-user/syscall.c          | 10 +++++-----
 target/arm/helper.c           | 20 ++++++++++----------
 target/arm/pauth_helper.c     | 18 +++++++++---------
 5 files changed, 32 insertions(+), 34 deletions(-)
target/arm/cpu.h +7 -5
index 22bc6e00ab..9448a76186 100644
@@ -636,11 +636,13 @@ typedef struct CPUARMState {
     } iwmmxt;
 
 #ifdef TARGET_AARCH64
-    ARMPACKey apia_key;
-    ARMPACKey apib_key;
-    ARMPACKey apda_key;
-    ARMPACKey apdb_key;
-    ARMPACKey apga_key;
+    struct {
+        ARMPACKey apia;
+        ARMPACKey apib;
+        ARMPACKey apda;
+        ARMPACKey apdb;
+        ARMPACKey apga;
+    } keys;
 #endif
 
 #if defined(CONFIG_USER_ONLY)
linux-user/aarch64/cpu_loop.c +1 -5
index cedad39ca0..2f2f63e3e8 100644
@@ -175,11 +175,7 @@ void target_cpu_copy_regs(CPUArchState *env, struct target_pt_regs *regs)
 #endif
 
     if (cpu_isar_feature(aa64_pauth, cpu)) {
-        qemu_guest_getrandom_nofail(&env->apia_key, sizeof(ARMPACKey));
-        qemu_guest_getrandom_nofail(&env->apib_key, sizeof(ARMPACKey));
-        qemu_guest_getrandom_nofail(&env->apda_key, sizeof(ARMPACKey));
-        qemu_guest_getrandom_nofail(&env->apdb_key, sizeof(ARMPACKey));
-        qemu_guest_getrandom_nofail(&env->apga_key, sizeof(ARMPACKey));
+        qemu_guest_getrandom_nofail(&env->keys, sizeof(env->keys));
     }
 
     ts->stack_base = info->start_stack;
linux-user/syscall.c +5 -5
index b73d1d9f65..3c26f6f9d4 100644
@@ -9734,23 +9734,23 @@ static abi_long do_syscall1(void *cpu_env, int num, abi_long arg1,
                         return -TARGET_EINVAL;
                     }
                     if (arg2 & TARGET_PR_PAC_APIAKEY) {
-                        ret |= qemu_guest_getrandom(&env->apia_key,
+                        ret |= qemu_guest_getrandom(&env->keys.apia,
                                                     sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APIBKEY) {
-                        ret |= qemu_guest_getrandom(&env->apib_key,
+                        ret |= qemu_guest_getrandom(&env->keys.apib,
                                                     sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APDAKEY) {
-                        ret |= qemu_guest_getrandom(&env->apda_key,
+                        ret |= qemu_guest_getrandom(&env->keys.apda,
                                                     sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APDBKEY) {
-                        ret |= qemu_guest_getrandom(&env->apdb_key,
+                        ret |= qemu_guest_getrandom(&env->keys.apdb,
                                                     sizeof(ARMPACKey), &err);
                     }
                     if (arg2 & TARGET_PR_PAC_APGAKEY) {
-                        ret |= qemu_guest_getrandom(&env->apga_key,
+                        ret |= qemu_guest_getrandom(&env->keys.apga,
                                                     sizeof(ARMPACKey), &err);
                     }
                     if (ret != 0) {
target/arm/helper.c +10 -10
index 81a92ab491..658a5a9822 100644
@@ -5683,43 +5683,43 @@ static const ARMCPRegInfo pauth_reginfo[] = {
     { .name = "APDAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 0,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apda_key.lo) },
+      .fieldoffset = offsetof(CPUARMState, keys.apda.lo) },
     { .name = "APDAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 1,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apda_key.hi) },
+      .fieldoffset = offsetof(CPUARMState, keys.apda.hi) },
     { .name = "APDBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 2,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apdb_key.lo) },
+      .fieldoffset = offsetof(CPUARMState, keys.apdb.lo) },
     { .name = "APDBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 2, .opc2 = 3,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apdb_key.hi) },
+      .fieldoffset = offsetof(CPUARMState, keys.apdb.hi) },
     { .name = "APGAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 0,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apga_key.lo) },
+      .fieldoffset = offsetof(CPUARMState, keys.apga.lo) },
     { .name = "APGAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 3, .opc2 = 1,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apga_key.hi) },
+      .fieldoffset = offsetof(CPUARMState, keys.apga.hi) },
     { .name = "APIAKEYLO_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 0,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apia_key.lo) },
+      .fieldoffset = offsetof(CPUARMState, keys.apia.lo) },
     { .name = "APIAKEYHI_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 1,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apia_key.hi) },
+      .fieldoffset = offsetof(CPUARMState, keys.apia.hi) },
     { .name = "APIBKEYLO_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 2,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apib_key.lo) },
+      .fieldoffset = offsetof(CPUARMState, keys.apib.lo) },
     { .name = "APIBKEYHI_EL1", .state = ARM_CP_STATE_AA64,
       .opc0 = 3, .opc1 = 0, .crn = 2, .crm = 1, .opc2 = 3,
       .access = PL1_RW, .accessfn = access_pauth,
-      .fieldoffset = offsetof(CPUARMState, apib_key.hi) },
+      .fieldoffset = offsetof(CPUARMState, keys.apib.hi) },
     REGINFO_SENTINEL
 };
 #endif
target/arm/pauth_helper.c +9 -9
index d750f96edf..7f30ae7395 100644
@@ -403,7 +403,7 @@ uint64_t HELPER(pacia)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_addpac(env, x, y, &env->apia_key, false);
+    return pauth_addpac(env, x, y, &env->keys.apia, false);
 }
 
 uint64_t HELPER(pacib)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -413,7 +413,7 @@ uint64_t HELPER(pacib)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_addpac(env, x, y, &env->apib_key, false);
+    return pauth_addpac(env, x, y, &env->keys.apib, false);
 }
 
 uint64_t HELPER(pacda)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -423,7 +423,7 @@ uint64_t HELPER(pacda)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_addpac(env, x, y, &env->apda_key, true);
+    return pauth_addpac(env, x, y, &env->keys.apda, true);
 }
 
 uint64_t HELPER(pacdb)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -433,7 +433,7 @@ uint64_t HELPER(pacdb)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_addpac(env, x, y, &env->apdb_key, true);
+    return pauth_addpac(env, x, y, &env->keys.apdb, true);
 }
 
 uint64_t HELPER(pacga)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -441,7 +441,7 @@ uint64_t HELPER(pacga)(CPUARMState *env, uint64_t x, uint64_t y)
     uint64_t pac;
 
     pauth_check_trap(env, arm_current_el(env), GETPC());
-    pac = pauth_computepac(x, y, env->apga_key);
+    pac = pauth_computepac(x, y, env->keys.apga);
 
     return pac & 0xffffffff00000000ull;
 }
@@ -453,7 +453,7 @@ uint64_t HELPER(autia)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_auth(env, x, y, &env->apia_key, false, 0);
+    return pauth_auth(env, x, y, &env->keys.apia, false, 0);
 }
 
 uint64_t HELPER(autib)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -463,7 +463,7 @@ uint64_t HELPER(autib)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_auth(env, x, y, &env->apib_key, false, 1);
+    return pauth_auth(env, x, y, &env->keys.apib, false, 1);
 }
 
 uint64_t HELPER(autda)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -473,7 +473,7 @@ uint64_t HELPER(autda)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_auth(env, x, y, &env->apda_key, true, 0);
+    return pauth_auth(env, x, y, &env->keys.apda, true, 0);
 }
 
 uint64_t HELPER(autdb)(CPUARMState *env, uint64_t x, uint64_t y)
@@ -483,7 +483,7 @@ uint64_t HELPER(autdb)(CPUARMState *env, uint64_t x, uint64_t y)
         return x;
     }
     pauth_check_trap(env, el, GETPC());
-    return pauth_auth(env, x, y, &env->apdb_key, true, 1);
+    return pauth_auth(env, x, y, &env->keys.apdb, true, 1);
 }
 
 uint64_t HELPER(xpaci)(CPUARMState *env, uint64_t a)
Signature · 1 line
2.17.1
Reviewed-by on v4 21/24
#48 lore raw

Re: [Qemu-devel] [PATCH v4 21/24] target/arm: Put all PAC keys into a structure

Quoted 11 lines · Richard Henderson

This allows us to use a single syscall to initialize them all.

---
  target/arm/cpu.h              | 12 +++++++-----
  linux-user/aarch64/cpu_loop.c |  6 +-----
  linux-user/syscall.c          | 10 +++++-----
  target/arm/helper.c           | 20 ++++++++++----------
  target/arm/pauth_helper.c     | 18 +++++++++---------
  5 files changed, 32 insertions(+), 34 deletions(-)
#49 lore raw

PATCH v4 22/24 target/arm: Implement ARMv8.5-RNG

In reply to Richard Henderson

---
v3: Log errors with -d unimp, for lack of a better flag.

---
 target/arm/cpu.h    |  5 +++++
 target/arm/cpu64.c  |  1 +
 target/arm/helper.c | 44 ++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 50 insertions(+)
target/arm/cpu.h +5 -0
index 9448a76186..5c228fee8e 100644
@@ -3510,6 +3510,11 @@ static inline bool isar_feature_aa64_condm_5(const ARMISARegisters *id)
     return FIELD_EX64(id->id_aa64isar0, ID_AA64ISAR0, TS) >= 2;
 }
 
+static inline bool isar_feature_aa64_rndr(const ARMISARegisters *id)
+{
+    return FIELD_EX64(id->id_aa64isar0, ID_AA64ISAR0, RNDR) != 0;
+}
+
 static inline bool isar_feature_aa64_jscvt(const ARMISARegisters *id)
 {
     return FIELD_EX64(id->id_aa64isar1, ID_AA64ISAR1, JSCVT) != 0;
target/arm/cpu64.c +1 -0
index 228906f267..835f73cceb 100644
@@ -310,6 +310,7 @@ static void aarch64_max_initfn(Object *obj)
         t = FIELD_DP64(t, ID_AA64ISAR0, DP, 1);
         t = FIELD_DP64(t, ID_AA64ISAR0, FHM, 1);
         t = FIELD_DP64(t, ID_AA64ISAR0, TS, 2); /* v8.5-CondM */
+        t = FIELD_DP64(t, ID_AA64ISAR0, RNDR, 1);
         cpu->isar.id_aa64isar0 = t;
 
         t = cpu->isar.id_aa64isar1;
target/arm/helper.c +44 -0

62 lines not on this page · raw message

Signature · 1 line
2.17.1
#50 lore raw

PATCH v4 23/24 target/ppc: Use qemu_guest_getrandom for DARN

In reply to Richard Henderson

We now have an interface for guest visible random numbers.

---
 target/ppc/int_helper.c | 42 +++++++++++++++++++++++++++++------------
 1 file changed, 30 insertions(+), 12 deletions(-)
target/ppc/int_helper.c +30 -12
index f6a088ac08..9059e70b9c 100644
@@ -23,6 +23,8 @@
 #include "exec/helper-proto.h"
 #include "crypto/aes.h"
 #include "fpu/softfloat.h"
+#include "qapi/error.h"
+#include "qemu/guest-random.h"
 
 #include "helper_regs.h"
 /*****************************************************************************/
@@ -158,25 +160,41 @@ uint32_t helper_cmpeqb(target_ulong ra, target_ulong rb)
 #undef hasvalue
 
 /*
- * Return invalid random number.
- *
- * FIXME: Add rng backend or other mechanism to get cryptographically suitable
- * random number
+ * Return a random number.
  */
-target_ulong helper_darn32(void)
+uint64_t helper_darn32(void)
 {
-    return -1;
+    Error *err = NULL;
+    uint32_t ret;
+
+    if (qemu_guest_getrandom(&ret, 4, &err) < 0) {
+        qemu_log_mask(LOG_UNIMP, "darn: Crypto failure: %s",
+                      error_get_pretty(err));
+        error_free(err);
+        return -1;
+    }
+
+    return ret;
 }
 
-target_ulong helper_darn64(void)
+uint64_t helper_darn64(void)
 {
-    return -1;
+    Error *err = NULL;
+    uint64_t ret;
+
+    do {
+        if (qemu_guest_getrandom(&ret, 8, &err) < 0) {
+            qemu_log_mask(LOG_UNIMP, "darn: Crypto failure: %s",
+                          error_get_pretty(err));
+            error_free(err);
+            return -1;
+        }
+        /* Since -1 is the error condition, try again for that case.  */
+    } while (unlikely(ret == -1));
+
+    return ret;
 }
 
-#endif
-
-#if defined(TARGET_PPC64)
-
 uint64_t helper_bpermd(uint64_t rs, uint64_t rb)
 {
     int i;
Signature · 1 line
2.17.1
#51 lore raw

Re: [Qemu-devel] [PATCH v4 23/24] target/ppc: Use qemu_guest_getrandom for DARN

Quoted 29 lines · Richard Henderson

We now have an interface for guest visible random numbers.

---
  target/ppc/int_helper.c | 42 +++++++++++++++++++++++++++++------------
  1 file changed, 30 insertions(+), 12 deletions(-)
target/ppc/int_helper.c +2 -4
index f6a088ac08..9059e70b9c 100644
@@ -23,6 +23,8 @@
  #include "exec/helper-proto.h"
  #include "crypto/aes.h"
  #include "fpu/softfloat.h"
+#include "qapi/error.h"
+#include "qemu/guest-random.h"
 
  #include "helper_regs.h"
  /*****************************************************************************/
@@ -158,25 +160,41 @@ uint32_t helper_cmpeqb(target_ulong ra, target_ulong rb)
  #undef hasvalue
 
  /*
- * Return invalid random number.
- *
- * FIXME: Add rng backend or other mechanism to get cryptographically suitable
- * random number

target/ppc/int_helper.c uint32_t helper_cmpeqb(target_ulong ra, target_ulong rb) · line 170

Quoted 10 lines
target/ppc/int_helper.c +6 -2
+ * Return a random number.
   */
-target_ulong helper_darn32(void)
+uint64_t helper_darn32(void)
  {
-    return -1;
+    Error *err = NULL;
+    uint32_t ret;
+
+    if (qemu_guest_getrandom(&ret, 4, &err) < 0) {

sizeof(ret)?

Quoted 8 lines
target/ppc/int_helper.c +7 -0
+        qemu_log_mask(LOG_UNIMP, "darn: Crypto failure: %s",
+                      error_get_pretty(err));
+        error_free(err);
+        return -1;
+    }
+
+    return ret;
  }

target/ppc/int_helper.c uint32_t helper_cmpeqb(target_ulong ra, target_ulong rb) · line 186

Quoted 10 lines
target/ppc/int_helper.c +6 -2
 
-target_ulong helper_darn64(void)
+uint64_t helper_darn64(void)
  {
-    return -1;
+    Error *err = NULL;
+    uint64_t ret;
+
+    do {
+        if (qemu_guest_getrandom(&ret, 8, &err) < 0) {

sizeof(ret)?

target/ppc/int_helper.c uint32_t helper_cmpeqb(target_ulong ra, target_ulong rb) · line 193

Quoted 7 lines
target/ppc/int_helper.c +7 -0
+            qemu_log_mask(LOG_UNIMP, "darn: Crypto failure: %s",
+                          error_get_pretty(err));
+            error_free(err);
+            return -1;
+        }
+        /* Since -1 is the error condition, try again for that case.  */
+    } while (unlikely(ret == -1));

I think you don't need to do that, according to documentation, this is done by the software:

"Programming Note: When the error value is obtained, software is expected to repeat the operation. [...]" - PowerISA Version 3.0B

Thanks,
Laurent

#52 lore raw

PATCH v4 24/24 target/i386: Implement CPUID_EXT_RDRAND

In reply to Richard Henderson

We now have an interface for guest visible random numbers.

Cc Paolo Bonzini <[email protected]>
Cc Eduardo Habkost <[email protected]>
---
 target/i386/helper.h     |  2 ++
 target/i386/cpu.c        |  5 ++--
 target/i386/int_helper.c | 21 +++++++++++++++
 target/i386/translate.c  | 55 +++++++++++++++++++++++++++++-----------
 4 files changed, 66 insertions(+), 17 deletions(-)
target/i386/helper.h +2 -0
index 6fb8fb9b74..8f9e1905c3 100644
@@ -226,3 +226,5 @@ DEF_HELPER_3(rcrl, tl, env, tl, tl)
 DEF_HELPER_3(rclq, tl, env, tl, tl)
 DEF_HELPER_3(rcrq, tl, env, tl, tl)
 #endif
+
+DEF_HELPER_1(rdrand, tl, env)
target/i386/cpu.c +3 -2
index 722c5514d4..1386814957 100644
@@ -730,13 +730,14 @@ static void x86_cpu_vendor_words2str(char *dst, uint32_t vendor1,
           CPUID_EXT_MONITOR | CPUID_EXT_SSSE3 | CPUID_EXT_CX16 | \
           CPUID_EXT_SSE41 | CPUID_EXT_SSE42 | CPUID_EXT_POPCNT | \
           CPUID_EXT_XSAVE | /* CPUID_EXT_OSXSAVE is dynamic */   \
-          CPUID_EXT_MOVBE | CPUID_EXT_AES | CPUID_EXT_HYPERVISOR)
+          CPUID_EXT_MOVBE | CPUID_EXT_AES | CPUID_EXT_HYPERVISOR | \
+          CPUID_EXT_RDRAND)
           /* missing:
           CPUID_EXT_DTES64, CPUID_EXT_DSCPL, CPUID_EXT_VMX, CPUID_EXT_SMX,
           CPUID_EXT_EST, CPUID_EXT_TM2, CPUID_EXT_CID, CPUID_EXT_FMA,
           CPUID_EXT_XTPR, CPUID_EXT_PDCM, CPUID_EXT_PCID, CPUID_EXT_DCA,
           CPUID_EXT_X2APIC, CPUID_EXT_TSC_DEADLINE_TIMER, CPUID_EXT_AVX,
-          CPUID_EXT_F16C, CPUID_EXT_RDRAND */
+          CPUID_EXT_F16C */
 
 #ifdef TARGET_X86_64
 #define TCG_EXT2_X86_64_FEATURES (CPUID_EXT2_SYSCALL | CPUID_EXT2_LM)
target/i386/int_helper.c +21 -0
index 4dc5c65991..334469ca8c 100644
@@ -22,6 +22,8 @@
 #include "exec/exec-all.h"
 #include "qemu/host-utils.h"
 #include "exec/helper-proto.h"
+#include "qapi/error.h"
+#include "qemu/guest-random.h"
 
 //#define DEBUG_MULDIV
 
@@ -470,3 +472,22 @@ void helper_cr4_testbit(CPUX86State *env, uint32_t bit)
         raise_exception_ra(env, EXCP06_ILLOP, GETPC());
     }
 }
+
+target_ulong HELPER(rdrand)(CPUX86State *env)
+{
+    Error *err = NULL;
+    target_ulong ret;
+
+    if (qemu_guest_getrandom(&ret, sizeof(ret), &err) < 0) {
+        qemu_log_mask(LOG_UNIMP, "rdrand: Crypto failure: %s",
+                      error_get_pretty(err));
+        error_free(err);
+        /* Failure clears CF and all other flags, and returns 0.  */
+        env->cc_src = 0;
+        return 0;
+    }
+
+    /* Success sets CF and clears all others.  */
+    env->cc_src = CC_C;
+    return ret;
+}
target/i386/translate.c +40 -15

71 lines not on this page · raw message

Signature · 1 line
2.17.1