Skip to contentSkip to conversation

AWS Nitro Enclave emulation support

PATCH Superseded Dorjoy Chowdhury 3 participants 23 messages Aug 18, 2024 – Aug 22, 2024

Subsystems (3)

v4 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v4 cover AWS Nitro Enclave emulation support

This is v4 submission for AWS Nitro Enclave emulation in QEMU. From the QEMU side the implementation for nitro enclaves is complete. v3 is at:
https://mail.gnu.org/archive/html/qemu-devel/2024-08/msg01594.html

Changes in v4:
- fixed error_setv assertion failed. I could not reproduce this but I think
this was happening because I did not set Error *err = NULL in x86_load_eif
- qemu_cbor.. helpers moved to a separate file now
- libcbor version requirement reduced from 0.8.0 to 0.7.0
- replaced GChecksum uses with qcrypto apis
- timestamp multiplied by 1000 in virtio-nsm
- user_data and nonce are now included in attestation even when they are empty
- added x509-utils in crypto
- added G_CHECKSUM_SHA384 support in hash-glib.c
- PCR3 and PCR4 can be set from nitro-enclave machine options. I did not add
the options for virtio-nsm device though. I think the PCR states are set by machines so it made sense to add the options for machine only.

Changes in v3:
- Support for virtio-nsm device
- The EIF related logic has been removed from microvm.c i.e., the logic is
contained in enclave related code
- For vsock emulation in nitro-enclave, now vhost-user-vsock is being used
instead of vhost-vsock (more details in the cover-letter below)
- updated documentation accordingly

Changes in v2:
- moved eif.c and eif.h files from hw/i386 to hw/core

Hi,

Hope everyone is doing well. This is a patch series adding AWS Nitro Enclave[1] emulation support in QEMU. Alexander Graf is mentoring me on this work. I have a gitlab branch where you can view the patches in the gitlab web UI for each commit:
https://gitlab.com/dorjoy03/qemu/-/tree/nitro-enclave-emulation

AWS nitro enclaves is an Amazon EC2[2] feature that allows creating isolated execution environments, called enclaves, from Amazon EC2 instances, which are used for processing highly sensitive data. Enclaves have no persistent storage and no external networking. The enclave VMs are based on Firecracker microvm and have a vhost-vsock device for communication with the parent EC2 instance that spawned it and a Nitro Secure Module (NSM) device for cryptographic attestation. The parent instance VM always has CID 3 while the enclave VM gets a dynamic CID. The enclave VMs can communicate with the parent instance over various ports to CID 3, for example, the init process inside an enclave sends a heartbeat to port 9000 upon boot, expecting a heartbeat reply, letting the parent instance know that the enclave VM has successfully booted.

From inside an EC2 instance, nitro-cli[3] is used to spawn an enclave VM using an EIF (Enclave Image Format)[4] file. EIF files can be built using nitro-cli as well. The EIF specification can be found in the README of the github aws-nitro-enclaves-image-format repository[4]. An EIF file contains the kernel, cmdline and ramdisk(s) in different sections which are used to boot the enclave VM.

Adding nitro enclave emulation support in QEMU will make the life of AWS Nitro Enclave users easier as they will be able to test their EIF images locally without having to run real nitro enclaves which can be difficult for debugging due to its roots in security. This will also make quick prototyping easier.

In QEMU, the new nitro-enclave machine type is implemented based on the microvm machine type similar to how AWS Nitro Enclaves are based on Firecracker microvm.

The vsock emulation support is added using vhost-user-vsock device. This is needed as nitro VMs always talk to parent VM (CID 3) but there is no support for sibling VM communication in vhost-vsock. So to run nitro-enclave, a process that does vsock emulation in user-space like vhost-device-vsock[5] from rust-vmm must be run. I am working on adding proxying using vsock (right now it uses unix domain socket) to the host machine in vhost-device-vsock which I have already posted a PR[6] in rust-vmm repo. This will allow users to run the necessary parent VM applications in the host machine instead of a separate VM with CID 3.

A new device virtio-nsm support has been added to QEMU. This device is built-into the nitro-enclave VM. The virtio-nsm spec can be found here[7].

For local testing you need to generate a hello.eif image by first building nitro-cli locally[8]. Then you can use nitro-cli to build a hello.eif image[9]. More details about testing can be found in the docs/system/i386/nitro-enclave.rst file.

Thanks.

Regards,
Dorjoy

[1] https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html
[2] https://aws.amazon.com/ec2/
[3] https://docs.aws.amazon.com/enclaves/latest/user/getting-started.html
[4] https://github.com/aws/aws-nitro-enclaves-image-format?tab=readme-ov-file#enclave-image-file-eif-specification
[5] https://github.com/rust-vmm/vhost-device/tree/main/vhost-device-vsock
[6] https://github.com/rust-vmm/vhost-device/pull/706
[7] https://lists.oasis-open.org/archives/virtio-comment/202310/msg00387.html
[8] https://github.com/aws/aws-nitro-enclaves-cli/blob/main/docs/ubuntu_20.04_how_to_install_nitro_cli_from_github_sources.md
[9] https://github.com/aws/aws-nitro-enclaves-cli/blob/main/examples/x86_64/hello/README.md

Dorjoy Chowdhury (6):
machine/nitro-enclave: New machine type for AWS Nitro Enclaves machine/nitro-enclave: Add vhost-user-vsock device device/virtio-nsm: Support for Nitro Secure Module device machine/nitro-enclave: Add built-in Nitro Secure Module device
crypto: Support SHA384 hash when using glib docs/nitro-enclave: Documentation for nitro-enclave machine type

 MAINTAINERS                              |   19 +
 backends/hostmem-memfd.c                 |    2 -
 configs/devices/i386-softmmu/default.mak |    1 +
 crypto/hash-glib.c                       |    2 +-
 crypto/meson.build                       |    2 +-
 crypto/x509-utils.c                      |   73 +
 docs/system/i386/nitro-enclave.rst       |   82 ++
 hw/core/eif.c                            |  707 ++++++++++
 hw/core/eif.h                            |   22 +
 hw/core/machine.c                        |   71 +-
 hw/core/meson.build                      |    3 +
 hw/i386/Kconfig                          |    6 +
 hw/i386/meson.build                      |    1 +
 hw/i386/microvm.c                        |    6 +-
 hw/i386/nitro_enclave.c                  |  355 +++++
 hw/virtio/Kconfig                        |    5 +
 hw/virtio/cbor-helpers.c                 |  292 ++++
 hw/virtio/meson.build                    |    4 +
 hw/virtio/virtio-nsm-pci.c               |   73 +
 hw/virtio/virtio-nsm.c                   | 1648 ++++++++++++++++++++++
 include/crypto/x509-utils.h              |   22 +
 include/hw/boards.h                      |    2 +
 include/hw/i386/microvm.h                |    2 +
 include/hw/i386/nitro_enclave.h          |   63 +
 include/hw/virtio/cbor-helpers.h         |   43 +
 include/hw/virtio/virtio-nsm.h           |   59 +
 include/sysemu/hostmem.h                 |    2 +
 27 files changed, 3529 insertions(+), 38 deletions(-)
 create mode 100644 crypto/x509-utils.c
 create mode 100644 docs/system/i386/nitro-enclave.rst
 create mode 100644 hw/core/eif.c
 create mode 100644 hw/core/eif.h
 create mode 100644 hw/i386/nitro_enclave.c
 create mode 100644 hw/virtio/cbor-helpers.c
 create mode 100644 hw/virtio/virtio-nsm-pci.c
 create mode 100644 hw/virtio/virtio-nsm.c
 create mode 100644 include/crypto/x509-utils.h
 create mode 100644 include/hw/i386/nitro_enclave.h
 create mode 100644 include/hw/virtio/cbor-helpers.h
 create mode 100644 include/hw/virtio/virtio-nsm.h
Signature · 1 line
2.39.2
#1 lore raw

PATCH v4 1/6 machine/nitro-enclave: New machine type for AWS Nitro Enclaves

AWS nitro enclaves[1] is an Amazon EC2[2] feature that allows creating isolated execution environments, called enclaves, from Amazon EC2 instances which are used for processing highly sensitive data. Enclaves have no persistent storage and no external networking. The enclave VMs are based on Firecracker microvm with a vhost-vsock device for communication with the parent EC2 instance that spawned it and a Nitro Secure Module (NSM) device for cryptographic attestation. The parent instance VM always has CID 3 while the enclave VM gets a dynamic CID.

An EIF (Enclave Image Format)[3] file is used to boot an AWS nitro enclave virtual machine. The EIF file contains the necessary kernel, cmdline, ramdisk(s) sections to boot.

This commit adds support for limited AWS nitro enclave emulation using a new machine type option '-M nitro-enclave'. This new machine type is based on the 'microvm' machine type, similar to how real nitro enclave VMs are based on Firecracker microvm. For nitro-enclave to boot from an EIF file, the kernel and ramdisk(s) are extracted into a temporary kernel and a temporary initrd file which are then hooked into the regular x86 boot mechanism along with the extracted cmdline. The EIF file path should be provided using the '-kernel' QEMU option.

The vsock and NSM devices will be implemented so that they are available automatically in nitro-enclave machine type in the following commits.

[1] https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html
[2] https://aws.amazon.com/ec2/
[3] https://github.com/aws/aws-nitro-enclaves-image-format

---
 MAINTAINERS                              |   9 +
 configs/devices/i386-softmmu/default.mak |   1 +
 hw/core/eif.c                            | 514 +++++++++++++++++++++++
 hw/core/eif.h                            |  19 +
 hw/core/meson.build                      |   1 +
 hw/i386/Kconfig                          |   4 +
 hw/i386/meson.build                      |   1 +
 hw/i386/microvm.c                        |   6 +-
 hw/i386/nitro_enclave.c                  |  93 ++++
 include/hw/i386/microvm.h                |   2 +
 include/hw/i386/nitro_enclave.h          |  29 ++
 11 files changed, 678 insertions(+), 1 deletion(-)
 create mode 100644 hw/core/eif.c
 create mode 100644 hw/core/eif.h
 create mode 100644 hw/i386/nitro_enclave.c
 create mode 100644 include/hw/i386/nitro_enclave.h
MAINTAINERS +9 -0
index 3584d6a6c6..a59537c9c5 100644
@@ -1877,6 +1877,15 @@ F: hw/i386/microvm.c
 F: include/hw/i386/microvm.h
 F: pc-bios/bios-microvm.bin
 
+nitro-enclave
+M: Alexander Graf <[email protected]>
+M: Dorjoy Chowdhury <[email protected]>
+S: Maintained
+F: hw/core/eif.c
+F: hw/core/eif.h
+F: hw/i386/nitro_enclave.c
+F: include/hw/i386/nitro_enclave.h
+
 Machine core
 M: Eduardo Habkost <[email protected]>
 M: Marcel Apfelbaum <[email protected]>
configs/devices/i386-softmmu/default.mak +1 -0
index 448e3e3b1b..4faf2f0315 100644
@@ -29,3 +29,4 @@
 # CONFIG_I440FX=n
 # CONFIG_Q35=n
 # CONFIG_MICROVM=n
+# CONFIG_NITRO_ENCLAVE=n
hw/core/eif.c new file +514 -0

514 lines not on this page · raw message

hw/core/eif.h new file +19 -0
new file mode 100644
index 0000000000..7063974d93
@@ -0,0 +1,19 @@
+/*
+ * EIF (Enclave Image Format) related helpers
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.
+ */
+
+#ifndef HW_CORE_EIF_H
+#define HW_CORE_EIF_H
+
+bool read_eif_file(const char *eif_path, const char *machine_initrd,
+                   char **kernel_path, char **initrd_path,
+                   char **kernel_cmdline, Error **errp);
+
+#endif
+
hw/core/meson.build +1 -0
index a3d9bab9f4..f32d1ad943 100644
@@ -24,6 +24,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
 system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
 system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
 system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
 
 system_ss.add(files(
   'cpu-sysemu.c',
hw/i386/Kconfig +4 -0
index f4a33b6c08..eba8eaa960 100644
@@ -129,6 +129,10 @@ config MICROVM
     select USB_XHCI_SYSBUS
     select I8254
 
+config NITRO_ENCLAVE
+    default y
+    depends on MICROVM
+
 config X86_IOMMU
     bool
     depends on PC
hw/i386/meson.build +1 -0
index 03aad10df7..10bdfde27c 100644
@@ -15,6 +15,7 @@ i386_ss.add(when: 'CONFIG_AMD_IOMMU', if_true: files('amd_iommu.c'),
                                       if_false: files('amd_iommu-stub.c'))
 i386_ss.add(when: 'CONFIG_I440FX', if_true: files('pc_piix.c'))
 i386_ss.add(when: 'CONFIG_MICROVM', if_true: files('x86-common.c', 'microvm.c', 'acpi-microvm.c', 'microvm-dt.c'))
+i386_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: files('nitro_enclave.c'))
 i386_ss.add(when: 'CONFIG_Q35', if_true: files('pc_q35.c'))
 i386_ss.add(when: 'CONFIG_VMMOUSE', if_true: files('vmmouse.c'))
 i386_ss.add(when: 'CONFIG_VMPORT', if_true: files('vmport.c'))
hw/i386/microvm.c +5 -1
index 40edcee7af..869c177642 100644
@@ -283,6 +283,7 @@ static void microvm_devices_init(MicrovmMachineState *mms)
 
 static void microvm_memory_init(MicrovmMachineState *mms)
 {
+    MicrovmMachineClass *mmc = MICROVM_MACHINE_GET_CLASS(mms);
     MachineState *machine = MACHINE(mms);
     X86MachineState *x86ms = X86_MACHINE(mms);
     MemoryRegion *ram_below_4g, *ram_above_4g;
@@ -328,7 +329,7 @@ static void microvm_memory_init(MicrovmMachineState *mms)
     rom_set_fw(fw_cfg);
 
     if (machine->kernel_filename != NULL) {
-        x86_load_linux(x86ms, fw_cfg, 0, true);
+        mmc->x86_load_linux(x86ms, fw_cfg, 0, true);
     }
 
     if (mms->option_roms) {
@@ -637,9 +638,12 @@ GlobalProperty microvm_properties[] = {
 static void microvm_class_init(ObjectClass *oc, void *data)
 {
     X86MachineClass *x86mc = X86_MACHINE_CLASS(oc);
+    MicrovmMachineClass *mmc = MICROVM_MACHINE_CLASS(oc);
     MachineClass *mc = MACHINE_CLASS(oc);
     HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(oc);
 
+    mmc->x86_load_linux = x86_load_linux;
+
     mc->init = microvm_machine_state_init;
 
     mc->family = "microvm_i386";
hw/i386/nitro_enclave.c new file +93 -0

93 lines not on this page · raw message

include/hw/i386/microvm.h +2 -0
index fad97a891d..b9ac34a3ef 100644
@@ -78,6 +78,8 @@ struct MicrovmMachineClass {
     X86MachineClass parent;
     HotplugHandler *(*orig_hotplug_handler)(MachineState *machine,
                                            DeviceState *dev);
+    void (*x86_load_linux)(X86MachineState *x86ms, FWCfgState *fw_cfg,
+                        int acpi_data_size, bool pvh_enabled);
 };
 
 struct MicrovmMachineState {
include/hw/i386/nitro_enclave.h new file +29 -0
new file mode 100644
index 0000000000..a1dada9371
@@ -0,0 +1,29 @@
+/*
+ * AWS nitro-enclave machine
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.
+ */
+
+#ifndef HW_I386_NITRO_ENCLAVE_H
+#define HW_I386_NITRO_ENCLAVE_H
+
+#include "hw/i386/microvm.h"
+#include "qom/object.h"
+
+struct NitroEnclaveMachineClass {
+    MicrovmMachineClass parent;
+};
+
+struct NitroEnclaveMachineState {
+    MicrovmMachineState parent;
+};
+
+#define TYPE_NITRO_ENCLAVE_MACHINE MACHINE_TYPE_NAME("nitro-enclave")
+OBJECT_DECLARE_TYPE(NitroEnclaveMachineState, NitroEnclaveMachineClass,
+                    NITRO_ENCLAVE_MACHINE)
+
+#endif
Signature · 1 line
2.39.2
#2 lore raw

PATCH v4 2/6 machine/nitro-enclave: Add vhost-user-vsock device

In reply to Dorjoy Chowdhury

AWS Nitro Enclaves have built-in vhost-vsock device support which enables applications in enclave VMs to communicate with the parent EC2 VM over vsock. The enclave VMs have dynamic CID while the parent always has CID 3. In QEMU, the vsock emulation for nitro enclave is added using vhost-user-vsock as opposed to vhost-vsock. vhost-vsock doesn't support sibling VM communication which is needed for nitro enclaves.

In QEMU's nitro-enclave emulation, for the vsock communication to CID 3 to work, another process that does the vsock emulation in userspace must be run, for example, vhost-device-vsock[1] from rust-vmm, with necessary vsock communication support in another guest VM with CID 3. A new mandatory nitro-enclave machine option 'vsock' has been added. The value for this option should be the chardev id from the '-chardev' option for the vhost-user-vsock device to work.

Using vhost-user-vsock also enables the possibility to implement some proxying support in the vhost-user-vsock daemon that will forward all the packets to the host machine instead of CID 3 so that users of nitro-enclave can run the necessary applications in their host machine instead of running another whole VM with CID 3.

[1] https://github.com/rust-vmm/vhost-device/tree/main/vhost-device-vsock

---
 backends/hostmem-memfd.c        |   2 -
 hw/core/machine.c               |  71 +++++++++---------
 hw/i386/Kconfig                 |   1 +
 hw/i386/nitro_enclave.c         | 123 ++++++++++++++++++++++++++++++++
 include/hw/boards.h             |   2 +
 include/hw/i386/nitro_enclave.h |   8 +++
 include/sysemu/hostmem.h        |   2 +
 7 files changed, 174 insertions(+), 35 deletions(-)
backends/hostmem-memfd.c +0 -2
index 6a3c89a12b..9f890a813e 100644
@@ -18,8 +18,6 @@
 #include "qapi/error.h"
 #include "qom/object.h"
 
-#define TYPE_MEMORY_BACKEND_MEMFD "memory-backend-memfd"
-
 OBJECT_DECLARE_SIMPLE_TYPE(HostMemoryBackendMemfd, MEMORY_BACKEND_MEMFD)
 
 
hw/core/machine.c +38 -33

95 lines not on this page · raw message

hw/i386/Kconfig +1 -0
index eba8eaa960..821532c4c8 100644
@@ -132,6 +132,7 @@ config MICROVM
 config NITRO_ENCLAVE
     default y
     depends on MICROVM
+    select VHOST_USER_VSOCK
 
 config X86_IOMMU
     bool
hw/i386/nitro_enclave.c +123 -0

149 lines not on this page · raw message

include/hw/boards.h +2 -0
index 48ff6d8b93..c268e7f005 100644
@@ -308,6 +308,8 @@ struct MachineClass {
     int64_t (*get_default_cpu_node_id)(const MachineState *ms, int idx);
     ram_addr_t (*fixup_ram_size)(ram_addr_t size);
     uint64_t smbios_memory_device_size;
+    bool (*create_default_memdev)(MachineState *ms, const char *path,
+                                  Error **errp);
 };
 
 /**
include/hw/i386/nitro_enclave.h +8 -0
index a1dada9371..3e302de851 100644
@@ -14,12 +14,20 @@
 #include "hw/i386/microvm.h"
 #include "qom/object.h"
 
+/* Machine type options */
+#define NITRO_ENCLAVE_VSOCK_CHARDEV_ID "vsock"
+
 struct NitroEnclaveMachineClass {
     MicrovmMachineClass parent;
+
+    void (*parent_init)(MachineState *state);
 };
 
 struct NitroEnclaveMachineState {
     MicrovmMachineState parent;
+
+    /* Machine type options */
+    char *vsock;
 };
 
 #define TYPE_NITRO_ENCLAVE_MACHINE MACHINE_TYPE_NAME("nitro-enclave")
include/sysemu/hostmem.h +2 -0
index de47ae59e4..67f45abe39 100644
@@ -39,6 +39,8 @@ OBJECT_DECLARE_TYPE(HostMemoryBackend, HostMemoryBackendClass,
  */
 #define TYPE_MEMORY_BACKEND_FILE "memory-backend-file"
 
+#define TYPE_MEMORY_BACKEND_MEMFD "memory-backend-memfd"
+
 
 /**
  * HostMemoryBackendClass:
Signature · 1 line
2.39.2
#3 lore raw

PATCH v4 3/6 device/virtio-nsm: Support for Nitro Secure Module device

In reply to Dorjoy Chowdhury

Nitro Secure Module (NSM)[1] device is used in AWS Nitro Enclaves for stripped down TPM functionality like cryptographic attestation. The requests to and responses from NSM device are CBOR[2] encoded.

This commit adds support for NSM device in QEMU. Although related to AWS Nitro Enclaves, the virito-nsm device is independent and can be used in other machine types as well. The libcbor[3] library has been used for the CBOR encoding and decoding functionalities.

[1] https://lists.oasis-open.org/archives/virtio-comment/202310/msg00387.html
[2] http://cbor.io/
[3] https://libcbor.readthedocs.io/en/latest/

---
 MAINTAINERS                      |   10 +
 hw/virtio/Kconfig                |    5 +
 hw/virtio/cbor-helpers.c         |  292 ++++++
 hw/virtio/meson.build            |    4 +
 hw/virtio/virtio-nsm-pci.c       |   73 ++
 hw/virtio/virtio-nsm.c           | 1648 ++++++++++++++++++++++++++++++
 include/hw/virtio/cbor-helpers.h |   43 +
 include/hw/virtio/virtio-nsm.h   |   59 ++
 8 files changed, 2134 insertions(+)
 create mode 100644 hw/virtio/cbor-helpers.c
 create mode 100644 hw/virtio/virtio-nsm-pci.c
 create mode 100644 hw/virtio/virtio-nsm.c
 create mode 100644 include/hw/virtio/cbor-helpers.h
 create mode 100644 include/hw/virtio/virtio-nsm.h
MAINTAINERS +10 -0
index a59537c9c5..aa7846107e 100644
@@ -2349,6 +2349,16 @@ F: include/sysemu/rng*.h
 F: backends/rng*.c
 F: tests/qtest/virtio-rng-test.c
 
+virtio-nsm
+M: Alexander Graf <[email protected]>
+M: Dorjoy Chowdhury <[email protected]>
+S: Maintained
+F: hw/virtio/cbor-helpers.c
+F: hw/virtio/virtio-nsm.c
+F: hw/virtio/virtio-nsm-pci.c
+F: include/hw/virtio/cbor-helpers.h
+F: include/hw/virtio/virtio-nsm.h
+
 vhost-user-stubs
 M: Alex Bennée <[email protected]>
 S: Maintained
hw/virtio/Kconfig +5 -0
index aa63ff7fd4..29fee32035 100644
@@ -6,6 +6,11 @@ config VIRTIO_RNG
     default y
     depends on VIRTIO
 
+config VIRTIO_NSM
+   bool
+   default y
+   depends on VIRTIO
+
 config VIRTIO_IOMMU
     bool
     default y
hw/virtio/cbor-helpers.c new file +292 -0

292 lines not on this page · raw message

hw/virtio/meson.build +4 -0
index 621fc65454..7ccb61cf74 100644
@@ -48,12 +48,15 @@ else
   system_virtio_ss.add(files('vhost-stub.c'))
 endif
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
 specific_virtio_ss.add(when: 'CONFIG_VIRTIO_BALLOON', if_true: files('virtio-balloon.c'))
 specific_virtio_ss.add(when: 'CONFIG_VHOST_USER_FS', if_true: files('vhost-user-fs.c'))
 specific_virtio_ss.add(when: 'CONFIG_VIRTIO_PMEM', if_true: files('virtio-pmem.c'))
 specific_virtio_ss.add(when: 'CONFIG_VHOST_VSOCK', if_true: files('vhost-vsock.c'))
 specific_virtio_ss.add(when: 'CONFIG_VHOST_USER_VSOCK', if_true: files('vhost-user-vsock.c'))
 specific_virtio_ss.add(when: 'CONFIG_VIRTIO_RNG', if_true: files('virtio-rng.c'))
+specific_virtio_ss.add(when: 'CONFIG_VIRTIO_NSM', if_true: [files('virtio-nsm.c', 'cbor-helpers.c'), libcbor])
 specific_virtio_ss.add(when: 'CONFIG_VIRTIO_MEM', if_true: files('virtio-mem.c'))
 specific_virtio_ss.add(when: 'CONFIG_VHOST_USER_SCMI', if_true: files('vhost-user-scmi.c'))
 specific_virtio_ss.add(when: ['CONFIG_VIRTIO_PCI', 'CONFIG_VHOST_USER_SCMI'], if_true: files('vhost-user-scmi-pci.c'))
@@ -70,6 +73,7 @@ virtio_pci_ss.add(when: 'CONFIG_VIRTIO_CRYPTO', if_true: files('virtio-crypto-pc
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_INPUT_HOST', if_true: files('virtio-input-host-pci.c'))
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_INPUT', if_true: files('virtio-input-pci.c'))
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_RNG', if_true: files('virtio-rng-pci.c'))
+virtio_pci_ss.add(when: 'CONFIG_VIRTIO_NSM', if_true: [files('virtio-nsm-pci.c', 'cbor-helpers.c'), libcbor])
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_BALLOON', if_true: files('virtio-balloon-pci.c'))
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_9P', if_true: files('virtio-9p-pci.c'))
 virtio_pci_ss.add(when: 'CONFIG_VIRTIO_SCSI', if_true: files('virtio-scsi-pci.c'))
hw/virtio/virtio-nsm-pci.c new file +73 -0

73 lines not on this page · raw message

hw/virtio/virtio-nsm.c new file +1648 -0

1,648 lines not on this page · raw message

include/hw/virtio/cbor-helpers.h new file +43 -0

43 lines not on this page · raw message

include/hw/virtio/virtio-nsm.h new file +59 -0

59 lines not on this page · raw message

Signature · 1 line
2.39.2
#4 lore raw

Re: [PATCH v4 3/6] device/virtio-nsm: Support for Nitro Secure Module device

Quoted 14 lines · Dorjoy Chowdhury

Nitro Secure Module (NSM)[1] device is used in AWS Nitro Enclaves for stripped down TPM functionality like cryptographic attestation. The requests to and responses from NSM device are CBOR[2] encoded.

This commit adds support for NSM device in QEMU. Although related to AWS Nitro Enclaves, the virito-nsm device is independent and can be used in other machine types as well. The libcbor[3] library has been used for the CBOR encoding and decoding functionalities.

[1] https://lists.oasis-open.org/archives/virtio-comment/202310/msg00387.html
[2] http://cbor.io/
[3] https://libcbor.readthedocs.io/en/latest/

[...]

Quoted 14 lines
(quoted diff) +14 -0
+static bool add_payload_to_cose(cbor_item_t *cose, VirtIONSM *vnsm)
+{
+    cbor_item_t *root = NULL;
+    cbor_item_t *nested_map;
+    cbor_item_t *bs = NULL;
+    size_t locked_cnt;
+    uint8_t ind[NSM_MAX_PCRS];
+    size_t payload_map_size = 6;
+    size_t len;
+    struct PCRInfo *pcr;
+    uint8_t zero[64] = {0};
+    bool r = false;
+    size_t buf_len = 16384;
+    uint8_t *buf = g_malloc(buf_len);

Review

Quoted 10 lines
(quoted diff) +10 -0
+
+    if (vnsm->public_key_len > 0) {
+        payload_map_size++;
+    }
+    if (vnsm->user_data_len > 0) {
+        payload_map_size++;
+    }
+    if (vnsm->nonce_len > 0) {
+        payload_map_size++;
+    }

Now that you're always emitting user_data and nonce, you should include them in payload_map_size unconditionally as well; otherwise your map is too small to hold all members.

In addition, a real Nitro Enclave attestation document will return Null objects for these fields when they're not set instead of empty strings. With the patch below I was able to generate a doc that looks very similar to a real one:

hw/virtio/cbor-helpers.c +0 -0
index 5140020d4e..ffecc97c48 100644
@@ -140,7 +140,11 @@ bool qemu_cbor_add_bytestring_to_map(cbor_item_t *map, const char *key,

     if (!key_cbor) {
         goto cleanup;
     }
-    value_cbor = cbor_build_bytestring(arr, len);
+    if (len) {
+        value_cbor = cbor_build_bytestring(arr, len);
+    } else {
+        value_cbor = cbor_new_null();
+    }
     if (!value_cbor) {
         goto cleanup;
     }
@@ -241,7 +245,11 @@ bool qemu_cbor_add_uint8_key_bytestring_to_map(cbor_item_t *map, uint8_t key, if (!key_cbor) {
         goto cleanup;
     }
-    value_cbor = cbor_build_bytestring(buf, len);
+    if (len) {
+        value_cbor = cbor_build_bytestring(buf, len);
+    } else {
+        value_cbor = cbor_new_null();
+    }
     if (!value_cbor) {
         goto cleanup;
     }

hw/virtio/virtio-nsm.c +0 -0
index e91848a2b0..b45d97efe2 100644
@@ -1126,7 +1126,7 @@ static bool add_payload_to_cose(cbor_item_t *cose, VirtIONSM *vnsm)

     cbor_item_t *bs = NULL;
     size_t locked_cnt;
     uint8_t ind[NSM_MAX_PCRS];
-    size_t payload_map_size = 6;
+    size_t payload_map_size = 8;
     size_t len;
     struct PCRInfo *pcr;
     uint8_t zero[64] = {0};
@@ -1137,12 +1137,6 @@ static bool add_payload_to_cose(cbor_item_t *cose, VirtIONSM *vnsm) if (vnsm->public_key_len > 0) {
         payload_map_size++;
     }
-    if (vnsm->user_data_len > 0) {
-        payload_map_size++;
-    }
-    if (vnsm->nonce_len > 0) {
-        payload_map_size++;
-    }
     root = cbor_new_definite_map(payload_map_size);
     if (!root) {
         goto cleanup;

Alex

Amazon Web Services Development Center Germany GmbH Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B
Sitz: Berlin
Ust-ID: DE 365 538 597

#5 lore raw

Re: [PATCH v4 3/6] device/virtio-nsm: Support for Nitro Secure Module device

In reply to Dorjoy Chowdhury
Quoted 36 lines · Dorjoy Chowdhury

Nitro Secure Module (NSM)[1] device is used in AWS Nitro Enclaves for stripped down TPM functionality like cryptographic attestation. The requests to and responses from NSM device are CBOR[2] encoded.

This commit adds support for NSM device in QEMU. Although related to AWS Nitro Enclaves, the virito-nsm device is independent and can be used in other machine types as well. The libcbor[3] library has been used for the CBOR encoding and decoding functionalities.

[1] https://lists.oasis-open.org/archives/virtio-comment/202310/msg00387.html
[2] http://cbor.io/
[3] https://libcbor.readthedocs.io/en/latest/

---
 MAINTAINERS                      |   10 +
 hw/virtio/Kconfig                |    5 +
 hw/virtio/cbor-helpers.c         |  292 ++++++
 hw/virtio/meson.build            |    4 +
 hw/virtio/virtio-nsm-pci.c       |   73 ++
 hw/virtio/virtio-nsm.c           | 1648 ++++++++++++++++++++++++++++++
 include/hw/virtio/cbor-helpers.h |   43 +
 include/hw/virtio/virtio-nsm.h   |   59 ++
 8 files changed, 2134 insertions(+)
 create mode 100644 hw/virtio/cbor-helpers.c
 create mode 100644 hw/virtio/virtio-nsm-pci.c
 create mode 100644 hw/virtio/virtio-nsm.c
 create mode 100644 include/hw/virtio/cbor-helpers.h
 create mode 100644 include/hw/virtio/virtio-nsm.h
hw/virtio/meson.build +0 -0
index 621fc65454..7ccb61cf74 100644

hw/virtio/meson.build else · line 51

Quoted 4 lines
hw/virtio/meson.build +1 -0
@@ -48,12 +48,15 @@ else
   system_virtio_ss.add(files('vhost-stub.c'))
 endif
 
+libcbor = dependency('libcbor', version: '>=0.7.0')

In the following patch I suggest that we should have this at the top level meson.build. Now that I see you're referencing this twice in different places, we definitely want it in the top meson.build.

ALso the CI changes in Mention in the following patch should be in whatever patch first introduces the libcbor dependency.

Quoted 6 lines
hw/virtio/virtio-nsm.c new file +0 -0
new file mode 100644
index 0000000000..e91848a2b0
 

hw/virtio/virtio-nsm.c line 1010

Quoted 10 lines
hw/virtio/virtio-nsm.c new file +10 -0
+static bool add_protected_header_to_cose(cbor_item_t *cose)
+{
+    cbor_item_t *map = NULL;
+    cbor_item_t *key = NULL;
+    cbor_item_t *value = NULL;
+    cbor_item_t *bs = NULL;
+    size_t len;
+    bool r = false;
+    size_t buf_len = 4096;
+    uint8_t *buf = g_malloc(buf_len);

g_autofree avoids the manual g_free call.

Quoted 58 lines
hw/virtio/virtio-nsm.c new file +55 -0
+
+    map = cbor_new_definite_map(1);
+    if (!map) {
+        goto cleanup;
+    }
+    key = cbor_build_uint8(1);
+    if (!key) {
+        goto cleanup;
+    }
+    value = cbor_new_int8();
+    if (!value) {
+        goto cleanup;
+    }
+    cbor_mark_negint(value);
+    /* we don't actually sign the data, so we use -1 as the 'alg' value */
+    cbor_set_uint8(value, 0);
+
+    if (!qemu_cbor_map_add(map, key, value)) {
+        goto cleanup;
+    }
+
+    len = cbor_serialize(map, buf, buf_len);
+    if (len == 0) {
+        goto cleanup_map;
+    }
+
+    bs = cbor_build_bytestring(buf, len);
+    if (!bs) {
+        goto cleanup_map;
+    }
+    if (!qemu_cbor_array_push(cose, bs)) {
+        cbor_decref(&bs);
+        goto cleanup_map;
+    }
+    r = true;
+    goto cleanup_map;
+
+ cleanup:
+    if (key) {
+        cbor_decref(&key);
+    }
+    if (value) {
+        cbor_decref(&value);
+    }
+
+ cleanup_map:
+    if (map) {
+        cbor_decref(&map);
+    }
+    g_free(buf);
+    return r;
+}
+
 
 
 
+static bool handle_Attestation(VirtIONSM *vnsm, struct iovec *request,
+                               struct iovec *response, Error **errp)

hw/virtio/virtio-nsm.c line 1135

Quoted 10 lines
hw/virtio/virtio-nsm.c new file +10 -0
+{
+    cbor_item_t *root = NULL;
+    cbor_item_t *cose = NULL;
+    cbor_item_t *nested_map;
+    size_t len;
+    NSMAttestationReq nsm_req;
+    enum NSMResponseTypes type;
+    bool r = false;
+    size_t buf_len = 16384;
+    uint8_t *buf = g_malloc(buf_len);

Another suitable for g_autofree

Quoted 79 lines
hw/virtio/virtio-nsm.c new file +79 -0
+
+    type = get_nsm_attestation_req(request->iov_base, request->iov_len,
+                                   &nsm_req);
+    if (type != NSM_SUCCESS) {
+        if (error_response(response, type, errp)) {
+            r = true;
+        }
+        goto out;
+    }
+
+    cose = cbor_new_definite_array(4);
+    if (!cose) {
+        goto err;
+    }
+    if (!add_protected_header_to_cose(cose)) {
+        goto err;
+    }
+    if (!add_unprotected_header_to_cose(cose)) {
+        goto err;
+    }
+
+    if (nsm_req.public_key_len > 0) {
+        memcpy(vnsm->public_key, nsm_req.public_key, nsm_req.public_key_len);
+        vnsm->public_key_len = nsm_req.public_key_len;
+    }
+    if (nsm_req.user_data_len > 0) {
+        memcpy(vnsm->user_data, nsm_req.user_data, nsm_req.user_data_len);
+        vnsm->user_data_len = nsm_req.user_data_len;
+    }
+    if (nsm_req.nonce_len > 0) {
+        memcpy(vnsm->nonce, nsm_req.nonce, nsm_req.nonce_len);
+        vnsm->nonce_len = nsm_req.nonce_len;
+    }
+
+    if (!add_payload_to_cose(cose, vnsm)) {
+        goto err;
+    }
+
+    if (!add_signature_to_cose(cose)) {
+        goto err;
+    }
+
+    len = cbor_serialize(cose, buf, buf_len);
+    if (len == 0) {
+        goto err;
+    }
+
+    root = cbor_new_definite_map(1);
+    if (!root) {
+        goto err;
+    }
+    if (!qemu_cbor_add_map_to_map(root, "Attestation", 1, &nested_map)) {
+        goto err;
+    }
+    if (!qemu_cbor_add_bytestring_to_map(nested_map, "document", buf, len)) {
+        goto err;
+    }
+
+    len = cbor_serialize(root, response->iov_base, response->iov_len);
+    if (len == 0) {
+        if (error_response(response, NSM_BUFFER_TOO_SMALL, errp)) {
+            r = true;
+        }
+        goto out;
+    }
+
+    response->iov_len = len;
+    r = true;
+
+ out:
+    if (root) {
+        cbor_decref(&root);
+    }
+    if (cose) {
+        cbor_decref(&cose);
+    }
+    g_free(buf);
+    return r;
+

hw/virtio/virtio-nsm.c

Quoted 10 lines
hw/virtio/virtio-nsm.c new file +9 -0
+ err:
+    error_setg(errp, "Failed to initialize Attestation response");
+    goto out;
+}
+
 
+static void handle_input(VirtIODevice *vdev, VirtQueue *vq)
+{
+    VirtQueueElement *out_elem = NULL;
+    VirtQueueElement *in_elem = NULL;

Both can be 'g_autofree' , to remove the duplicated g_free calls

Quoted 73 lines
hw/virtio/virtio-nsm.c new file +51 -0
+    VirtIONSM *vnsm = VIRTIO_NSM(vdev);
+    Error *err = NULL;
+
+    out_elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
+    if (!out_elem) {
+        /* nothing in virtqueue */
+        return;
+    }
+
+    if (out_elem->out_num != 1) {
+        virtio_error(vdev, "Expected one request buffer first in virtqueue");
+        goto cleanup;
+    }
+
+    in_elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
+    if (!in_elem) {
+        virtio_error(vdev, "Expected response buffer after request buffer "
+                     "in virtqueue");
+        goto cleanup;
+    }
+    if (in_elem->in_num != 1) {
+        virtio_error(vdev, "Expected one response buffer after request buffer "
+                     "in virtqueue");
+        goto cleanup;
+    }
+
+    if (!get_nsm_request_response(vnsm, out_elem->out_sg, in_elem->in_sg,
+                                  &err)) {
+        error_report_err(err);
+        virtio_error(vdev, "Failed to get NSM request response");
+        goto cleanup;
+    }
+
+    virtqueue_push(vq, out_elem, 0);
+    virtqueue_push(vq, in_elem, in_elem->in_sg->iov_len);
+    g_free(out_elem);
+    g_free(in_elem);
+    virtio_notify(vdev, vq);
+    return;
+
+ cleanup:
+    if (out_elem) {
+        virtqueue_detach_element(vq, out_elem, 0);
+    }
+    if (in_elem) {
+        virtqueue_detach_element(vq, in_elem, 0);
+    }
+    g_free(out_elem);
+    g_free(in_elem);
+    return;
+}
include/hw/virtio/virtio-nsm.h new file +13 -0
new file mode 100644
index 0000000000..7901c19fe4
@@ -0,0 +1,59 @@
+/*
+ * AWS Nitro Secure Module (NSM) device
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.
+ */
+
+#ifndef QEMU_VIRTIO_NSM_H
+#define QEMU_VIRTIO_NSM_H
+

include/hw/virtio/virtio-nsm.h line 21

Quoted 10 lines
include/hw/virtio/virtio-nsm.h new file +8 -0
+#include "hw/virtio/virtio.h"
+#include "qom/object.h"
+
+#define NSM_MAX_PCRS 32
+#define NSM_USER_DATA_MAX_SIZE 512
+#define NSM_NONCE_MAX_SIZE 512
+#define NSM_PUBLIC_KEY_MAX_SIZE 1024
 
 
+#define SHA384_BYTE_LEN 48

Hmm, you've added this in two different headers now, which suggests we should have it in a common header. include/qcrypto/hash.h is the obvious place to put this, so how about adding

  #define QCRYPTO_HASH_DIGEST_LEN_MD5       16
  #define QCRYPTO_HASH_DIGEST_LEN_SHA1      20
  #define QCRYPTO_HASH_DIGEST_LEN_SHA224    28
  #define QCRYPTO_HASH_DIGEST_LEN_SHA256    32
  #define QCRYPTO_HASH_DIGEST_LEN_SHA384    48
  #define QCRYPTO_HASH_DIGEST_LEN_SHA512    64

#define QCRYPTO_HASH_DIGEST_LEN_RIPEMD160 20

then updating qcrypto_hash_alg_size table to use these constants too.

THis should be a standalone commit at the start of the series.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#6 lore raw

PATCH v4 4/6 machine/nitro-enclave: Add built-in Nitro Secure Module device

In reply to Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

---
 crypto/meson.build              |   2 +-
 crypto/x509-utils.c             |  73 +++++++++++
 hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
 hw/core/eif.h                   |   5 +-
 hw/core/meson.build             |   4 +-
 hw/i386/Kconfig                 |   1 +
 hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
 include/crypto/x509-utils.h     |  22 ++++
 include/hw/i386/nitro_enclave.h |  26 ++++
 9 files changed, 479 insertions(+), 20 deletions(-)
 create mode 100644 crypto/x509-utils.c
 create mode 100644 include/crypto/x509-utils.h
crypto/meson.build +1 -1
index c46f9c22a7..09633194ed 100644
@@ -62,7 +62,7 @@ endif
 if gcrypt.found()
   util_ss.add(gcrypt, files('random-gcrypt.c'))
 elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))
 elif get_option('rng_none')
   util_ss.add(files('random-none.c'))
 else
crypto/x509-utils.c new file +73 -0

73 lines not on this page · raw message

hw/core/eif.c +209 -16

342 lines not on this page · raw message

hw/core/eif.h +4 -1
index 7063974d93..fed3cb5514 100644
@@ -13,7 +13,10 @@
 
 bool read_eif_file(const char *eif_path, const char *machine_initrd,
                    char **kernel_path, char **initrd_path,
-                   char **kernel_cmdline, Error **errp);
+                   char **kernel_cmdline, uint8_t *image_sha384,
+                   uint8_t *bootstrap_sha384, uint8_t *app_sha384,
+                   uint8_t *fingerprint_sha384, bool *signature_found,
+                   Error **errp);
 
 #endif
 
hw/core/meson.build +3 -1
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
   'qdev-clock.c',
 ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
 common_ss.add(files('cpu-common.c'))
 common_ss.add(files('machine-smp.c'))
 system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
 system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
 system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
 system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])
 
 system_ss.add(files(
   'cpu-sysemu.c',
hw/i386/Kconfig +1 -0
index 821532c4c8..63271bf915 100644
@@ -133,6 +133,7 @@ config NITRO_ENCLAVE
     default y
     depends on MICROVM
     select VHOST_USER_VSOCK
+    select VIRTIO_NSM
 
 config X86_IOMMU
     bool
hw/i386/nitro_enclave.c +140 -1

192 lines not on this page · raw message

include/crypto/x509-utils.h new file +22 -0
new file mode 100644
index 0000000000..602a056764
@@ -0,0 +1,22 @@
+/*
+ * X.509 certificate related helpers
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.
+ */
+
+#ifndef QCRYPTO_X509_UTILS_H
+#define QCRYPTO_X509_UTILS_H
+
+#include "crypto/hash.h"
+
+int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
+                                      QCryptoHashAlgorithm hash,
+                                      uint8_t **result,
+                                      size_t *resultlen,
+                                      Error **errp);
+
+#endif
include/hw/i386/nitro_enclave.h +26 -0
index 3e302de851..0b82a2a628 100644
@@ -13,14 +13,21 @@
 
 #include "hw/i386/microvm.h"
 #include "qom/object.h"
+#include "hw/virtio/virtio-nsm.h"
+
+#define SHA384_BYTE_LEN 48
 
 /* Machine type options */
 #define NITRO_ENCLAVE_VSOCK_CHARDEV_ID "vsock"
+#define NITRO_ENCLAVE_ID    "id"
+#define NITRO_ENCLAVE_PARENT_ROLE "parent-role"
+#define NITRO_ENCLAVE_PARENT_ID "parent-id"
 
 struct NitroEnclaveMachineClass {
     MicrovmMachineClass parent;
 
     void (*parent_init)(MachineState *state);
+    void (*parent_reset)(MachineState *machine, ShutdownCause reason);
 };
 
 struct NitroEnclaveMachineState {
@@ -28,6 +35,25 @@ struct NitroEnclaveMachineState {
 
     /* Machine type options */
     char *vsock;
+    /* Enclave identifier */
+    char *id;
+    /* Parent instance IAM role ARN */
+    char *parent_role;
+    /* Parent instance identifier */
+    char *parent_id;
+
+    /* Machine state */
+    VirtIONSM *vnsm;
+
+    /* kernel + ramdisks + cmdline sha384 hash */
+    uint8_t image_sha384[SHA384_BYTE_LEN];
+    /* kernel + boot ramdisk + cmdline sha384 hash */
+    uint8_t bootstrap_sha384[SHA384_BYTE_LEN];
+    /* application ramdisk(s) hash */
+    uint8_t app_sha384[SHA384_BYTE_LEN];
+    /* certificate fingerprint hash */
+    uint8_t fingerprint_sha384[SHA384_BYTE_LEN];
+    bool signature_found;
 };
 
 #define TYPE_NITRO_ENCLAVE_MACHINE MACHINE_TYPE_NAME("nitro-enclave")
Signature · 1 line
2.39.2
#7 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

Quoted 291 lines
crypto/meson.build +0 -0
  elif get_option('rng_none')
    util_ss.add(files('random-none.c'))
  else
crypto/x509-utils.c new file +73 -0
new file mode 100644
index 0000000000..2422eb995c
@@ -0,0 +1,73 @@
+/*
+ * X.509 certificate related helpers
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.
+ */
+
+#include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "crypto/x509-utils.h"
+#include <gnutls/gnutls.h>
+#include <gnutls/crypto.h>
+#include <gnutls/x509.h>
+
+static int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
+    [QCRYPTO_HASH_ALG_MD5] = GNUTLS_DIG_MD5,
+    [QCRYPTO_HASH_ALG_SHA1] = GNUTLS_DIG_SHA1,
+    [QCRYPTO_HASH_ALG_SHA224] = GNUTLS_DIG_SHA224,
+    [QCRYPTO_HASH_ALG_SHA256] = GNUTLS_DIG_SHA256,
+    [QCRYPTO_HASH_ALG_SHA384] = GNUTLS_DIG_SHA384,
+    [QCRYPTO_HASH_ALG_SHA512] = GNUTLS_DIG_SHA512,
+    [QCRYPTO_HASH_ALG_RIPEMD160] = GNUTLS_DIG_RMD160,
+};
+
+int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
+                                      QCryptoHashAlgorithm alg,
+                                      uint8_t **result,
+                                      size_t *resultlen,
+                                      Error **errp)
+{
+    int ret;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    if (alg >= G_N_ELEMENTS(qcrypto_to_gnutls_hash_alg_map)) {
+        error_setg(errp, "Unknown hash algorithm");
+        return -1;
+    }
+
+    gnutls_x509_crt_init(&crt);
+
+    if (gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM) != 0) {
+        error_setg(errp, "Failed to import certificate");
+        goto cleanup;
+    }
+
+    ret = gnutls_hash_get_len(qcrypto_to_gnutls_hash_alg_map[alg]);
+    if (*resultlen == 0) {
+        *resultlen = ret;
+        *result = g_new0(uint8_t, *resultlen);
+    } else if (*resultlen < ret) {
+        error_setg(errp,
+                   "Result buffer size %zu is smaller than hash %d",
+                   *resultlen, ret);
+        goto cleanup;
+    }
+
+    if (gnutls_x509_crt_get_fingerprint(crt,
+                                        qcrypto_to_gnutls_hash_alg_map[alg],
+                                        *result, resultlen) != 0) {
+        error_setg(errp, "Failed to get fingerprint from certificate");
+        goto cleanup;
+    }
+
+    return 0;
+
+ cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return -1;
+}
hw/core/eif.c +112 -13
index 5558879a96..8e15142d36 100644
@@ -11,7 +11,10 @@
  #include "qemu/osdep.h"
  #include "qemu/bswap.h"
  #include "qapi/error.h"
+#include "crypto/hash.h"
+#include "crypto/x509-utils.h"
  #include <zlib.h> /* for crc32 */
+#include <cbor.h>
 
  #include "hw/core/eif.h"
 
@@ -180,11 +183,10 @@ static void safe_unlink(char *f)
   * Upon success, the caller is reponsible for unlinking and freeing *kernel_path
   */
  static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
-                            uint32_t *crc, Error **errp)
+                            uint8_t *kernel, uint32_t *crc, Error **errp)
  {
      size_t got;
      FILE *tmp_file = NULL;
-    uint8_t *kernel = NULL;
 
      *kernel_path = NULL;
      if (!get_tmp_file("eif-kernel-XXXXXX", kernel_path, errp)) {
@@ -198,7 +200,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
          goto cleanup;
      }
 
-    kernel = g_malloc(size);
      got = fread(kernel, 1, size, f);
      if ((uint64_t) got != size) {
          error_setg(errp, "Failed to read EIF kernel section data");
@@ -213,7 +214,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
      }
 
      *crc = crc32(*crc, kernel, size);
-    g_free(kernel);
      fclose(tmp_file);
 
      return true;
@@ -225,7 +225,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
      g_free(*kernel_path);
      *kernel_path = NULL;
 
-    g_free(kernel);
      return false;
  }
 
@@ -243,29 +242,115 @@ static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline,
  }
 
  static bool read_eif_ramdisk(FILE *eif, FILE *initrd, uint64_t size,
-                             uint32_t *crc, Error **errp)
+                             uint8_t *ramdisk, uint32_t *crc, Error **errp)
  {
      size_t got;
-    uint8_t *ramdisk = g_malloc(size);
 
      got = fread(ramdisk, 1, size, eif);
      if ((uint64_t) got != size) {
          error_setg(errp, "Failed to read EIF ramdisk section data");
-        goto cleanup;
+        return false;
      }
 
      got = fwrite(ramdisk, 1, size, initrd);
      if ((uint64_t) got != size) {
          error_setg(errp, "Failed to write EIF ramdisk data to temporary file");
-        goto cleanup;
+        return false;
      }
 
      *crc = crc32(*crc, ramdisk, size);
-    g_free(ramdisk);
+    return true;
+}
+
+static bool get_signature_fingerprint_sha384(FILE *eif, uint64_t size,
+                                             uint8_t *sha384,
+                                             uint32_t *crc,
+                                             Error **errp)
+{
+    size_t got;
+    uint8_t *sig = NULL;
+    uint8_t *cert = NULL;
+    cbor_item_t *item = NULL;
+    cbor_item_t *pcr0 = NULL;
+    size_t len;
+    size_t hash_len = 48;
+    struct cbor_pair *pair;
+    struct cbor_load_result result;
+
+    sig = g_malloc(size);
+    got = fread(sig, 1, size, eif);
+    if ((uint64_t) got != size) {
+        error_setg(errp, "Failed to read EIF signature section data");
+        goto cleanup;
+    }
+
+    *crc = crc32(*crc, sig, size);
+
+    item = cbor_load(sig, size, &result);
+    if (!item || result.error.code != CBOR_ERR_NONE) {
+        error_setg(errp, "Failed to load signature section data as CBOR");
+        goto cleanup;
+    }
+    if (!cbor_isa_array(item) || cbor_array_size(item) < 1) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    pcr0 = cbor_array_get(item, 0);
+    if (!pcr0) {
+        error_setg(errp, "Failed to get PCR0 signature");
+        goto cleanup;
+    }
+    if (!cbor_isa_map(pcr0) || cbor_map_size(pcr0) != 2) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    pair = cbor_map_handle(pcr0);
+    if (!cbor_isa_string(pair->key) || cbor_string_length(pair->key) != 19 ||
+        memcmp(cbor_string_handle(pair->key), "signing_certificate", 19) != 0) {
+        error_setg(errp, "Invalid signautre CBOR");
+        goto cleanup;
+    }
+    if (!cbor_isa_array(pair->value)) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    len = cbor_array_size(pair->value);
+    if (len == 0) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    cert = g_malloc(len);
+    for (int i = 0; i < len; ++i) {
+        cbor_item_t *tmp = cbor_array_get(pair->value, i);
+        if (!tmp) {
+            error_setg(errp, "Invalid signature CBOR");
+            goto cleanup;
+        }
+        if (!cbor_isa_uint(tmp) || cbor_int_get_width(tmp) != CBOR_INT_8) {
+            cbor_decref(&tmp);
+            error_setg(errp, "Invalid signature CBOR");
+            goto cleanup;
+        }
+        cert[i] = cbor_get_uint8(tmp);
+        cbor_decref(&tmp);
+    }
+
+    if (qcrypto_get_x509_cert_fingerprint(cert, len, QCRYPTO_HASH_ALG_SHA384,
+                                          &sha384, &hash_len, errp)) {
+        goto cleanup;
+    }
+
      return true;
 
   cleanup:
-    g_free(ramdisk);
+    g_free(sig);
+    g_free(cert);
+    if (pcr0) {
+        cbor_decref(&pcr0);
+    }
+    if (item) {
+        cbor_decref(&item);
+    }
      return false;
  }
 
@@ -299,7 +384,9 @@ static long get_file_size(FILE *f, Error **errp)
   */
  bool read_eif_file(const char *eif_path, const char *machine_initrd,
                     char **kernel_path, char **initrd_path, char **cmdline,
-                   Error **errp)
+                   uint8_t *image_sha384, uint8_t *bootstrap_sha384,
+                   uint8_t *app_sha384, uint8_t *fingerprint_sha384,
+                   bool *signature_found, Error **errp)
  {
      FILE *f = NULL;
      FILE *machine_initrd_f = NULL;
@@ -308,7 +395,19 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
      uint32_t crc = 0;
      EifHeader eif_header;
      bool seen_sections[EIF_SECTION_MAX] = {false};
-
+    /* kernel + ramdisks + cmdline sha384 hash */
+    struct iovec image_hash_iovecs[MAX_SECTIONS + 1];
+    int image_hash_iovec_cnt = 0;
+    /* kernel + boot ramdisk + cmdline sha384 hash */
+    struct iovec bootstrap_hash_iovecs[3];
+    int bootstrap_hash_iovec_cnt = 0;
+    /* application ramdisk(s) hash */
+    struct iovec app_hash_iovecs[MAX_SECTIONS + 1];
+    int app_hash_iovec_cnt = 0;
+    uint8_t *ptr = NULL;
+    size_t digest_len;
+
+    *signature_found = false;
      *kernel_path = *initrd_path = *cmdline = NULL;
 
      f = fopen(eif_path, "rb");
@@ -373,8 +472,18 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
                             "section");
                  goto cleanup;

hw/core/eif.c bool read_eif_file(const char *eif_path, const char *machine_initrd, · line 483

Quoted 10 lines
hw/core/eif.c +9 -0
              }
+
+            ptr = g_malloc(section_header.section_size);
+
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len =
+                section_header.section_size;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base = ptr;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len =
+                section_header.section_size;

These super long variable names make the code really difficult to read. How about "iov_PCR0"? Also, if you make this a GList, you don't need to keep track of the count and allocate a large chunk of memory on the stack.

Quoted 16 lines
hw/core/eif.c +3 -1
+
              if (!read_eif_kernel(f, section_header.section_size, kernel_path,
-                                 &crc, errp)) {
+                                 ptr, &crc, errp)) {
                  goto cleanup;
              }
 
@@ -382,6 +491,7 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
          case EIF_SECTION_CMDLINE:
          {
              uint64_t size;
+            uint8_t *cmdline_copy;
              if (seen_sections[EIF_SECTION_CMDLINE]) {
                  error_setg(errp, "Invalid EIF image. More than 1 cmdline "
                             "section");

hw/core/eif.c bool read_eif_file(const char *eif_path, const char *machine_initrd, · line 513

Quoted 10 lines
hw/core/eif.c +7 -0
@@ -394,6 +504,19 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
              }
              (*cmdline)[size] = '\0';
 
+            /*
+             * We make a copy of '*cmdline' for putting it in iovecs so that
+             * we can easily free all the iovec entries later as we cannot
+             * free '*cmdline' which is used by the caller.
+             */
+            cmdline_copy = g_malloc(size);
+            memcpy(cmdline_copy, *cmdline, size);

Is this g_memdup2()?

Quoted 16 lines
hw/core/eif.c +9 -0
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = cmdline_copy;
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len = size;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base =
+                cmdline_copy;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len = size;
+
              break;
          }
          case EIF_SECTION_RAMDISK:
@@ -414,13 +537,41 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
                  }
              }
 
+            ptr = g_malloc(section_header.section_size);
+
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;

hw/core/eif.c bool read_eif_file(const char *eif_path, const char *machine_initrd, · line 552

Quoted 10 lines
hw/core/eif.c +10 -0
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len =
+                section_header.section_size;
+            /*
+             * If it's the first ramdisk, we need to hash it into bootstrap,
+             * otherwise we need to hash it into app.
+             */
+            if (!seen_sections[EIF_SECTION_RAMDISK]) {
+                bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base = ptr;
+                bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len =
+                    section_header.section_size;

Seeing all these long lines: What if you just called "section_header" "section" or "hdr" and "section_size" "len"?

Quoted 118 lines
hw/core/eif.c +59 -2
+            } else {
+                app_hash_iovecs[app_hash_iovec_cnt].iov_base = ptr;
+                app_hash_iovecs[app_hash_iovec_cnt++].iov_len =
+                    section_header.section_size;
+            }
+
              if (!read_eif_ramdisk(f, initrd_path_f, section_header.section_size,
-                                  &crc, errp)) {
+                                  ptr, &crc, errp)) {
                  goto cleanup;
              }
 
              break;
          }
+        case EIF_SECTION_SIGNATURE:
+            *signature_found = true;
+            if (!get_signature_fingerprint_sha384(f,
+                                                  section_header.section_size,
+                                                  fingerprint_sha384, &crc,
+                                                  errp)) {
+                goto cleanup;
+            }
+            break;
          default:
              /* other sections including invalid or unknown sections */
          {
@@ -483,18 +634,60 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
              goto cleanup;
          }
 
+        ptr = g_malloc(machine_initrd_size);
+
+        image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;
+        image_hash_iovecs[image_hash_iovec_cnt++].iov_len = machine_initrd_size;
+        app_hash_iovecs[app_hash_iovec_cnt].iov_base = ptr;
+        app_hash_iovecs[app_hash_iovec_cnt++].iov_len = machine_initrd_size;
+
          if (!read_eif_ramdisk(machine_initrd_f, initrd_path_f,
-                              machine_initrd_size, &crc, errp)) {
+                              machine_initrd_size, ptr, &crc, errp)) {
              goto cleanup;
          }
      }
 
+    digest_len = 48;
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, image_hash_iovecs,
+                            image_hash_iovec_cnt, &image_sha384, &digest_len,
+                            errp) < 0) {
+        goto cleanup;
+
+    }
+
+    digest_len = 48;
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, bootstrap_hash_iovecs,
+                            bootstrap_hash_iovec_cnt, &bootstrap_sha384,
+                            &digest_len, errp) < 0) {
+        goto cleanup;
+
+    }
+
+    digest_len = 48;
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, app_hash_iovecs,
+                            app_hash_iovec_cnt, &app_sha384, &digest_len,
+                            errp) < 0) {
+        goto cleanup;
+
+    }
+
+    /*
+     * We only need to free image_hash_iovec entries because bootstrap and
+     * app iovec entries are subsets of image_hash_iovec entries.
+     */
+    for (int i = 0; i < image_hash_iovec_cnt; ++i) {
+        g_free(image_hash_iovecs[i].iov_base);
+    }
      fclose(f);
      fclose(initrd_path_f);
      safe_fclose(machine_initrd_f);
      return true;
 
   cleanup:
+    for (int i = 0; i < image_hash_iovec_cnt; ++i) {
+        g_free(image_hash_iovecs[i].iov_base);
+    }
+
      safe_fclose(f);
      safe_fclose(initrd_path_f);
      safe_fclose(machine_initrd_f);
hw/core/eif.h +4 -1
index 7063974d93..fed3cb5514 100644
@@ -13,7 +13,10 @@
 
  bool read_eif_file(const char *eif_path, const char *machine_initrd,
                     char **kernel_path, char **initrd_path,
-                   char **kernel_cmdline, Error **errp);
+                   char **kernel_cmdline, uint8_t *image_sha384,
+                   uint8_t *bootstrap_sha384, uint8_t *app_sha384,
+                   uint8_t *fingerprint_sha384, bool *signature_found,
+                   Error **errp);
 
  #endif
 
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 5 lines
hw/core/meson.build +1 -1
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

Alex

Amazon Web Services Development Center Germany GmbH Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B
Sitz: Berlin
Ust-ID: DE 365 538 597

#8 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Hey Alex,

Quoted 30 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 8 lines
Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Good point. I guess it should be possible if I have the virtio-nsm device commit first and then add the machine/nitro-enclave commit with full support with the devices. That will of course make the machine/nitro-enclave commit larger. What do you think?

Regards,
Dorjoy

#9 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 34 lines · Dorjoy Chowdhury

Hey Alex,

Quoted 31 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
   crypto/meson.build              |   2 +-
   crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
   hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
   hw/core/eif.h                   |   5 +-
Quoted 8 lines
Quoted 4 lines

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Good point. I guess it should be possible if I have the virtio-nsm device commit first and then add the machine/nitro-enclave commit with full support with the devices. That will of course make the machine/nitro-enclave commit larger. What do you think?

As long as nothing compiles the code, it can rely on not yet implemented functions. So it's perfectly legit to add all your code in individual commits and then at the end add the meson.build change that implements the config option. How about the order below?

* Crypto patch for SHA384
* Crypto patch for x509 fingerprint
* NSM device emulation (including libcbor check, introduces CONFIG_VIRTIO_NSM)
* EIF format parsing (not compiled yet)
* Nitro Enclaves machine (introduces CONFIG_NITRO_ENCLAVE)
* Nitro Enclaves docs

Alex

Amazon Web Services Development Center Germany GmbH Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 257764 B
Sitz: Berlin
Ust-ID: DE 365 538 597

#10 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 52 lines · Alexander Graf
Quoted 34 lines · Dorjoy Chowdhury

Hey Alex,

Quoted 31 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
   crypto/meson.build              |   2 +-
   crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
   hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
   hw/core/eif.h                   |   5 +-
Quoted 8 lines
Quoted 4 lines

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Good point. I guess it should be possible if I have the virtio-nsm device commit first and then add the machine/nitro-enclave commit with full support with the devices. That will of course make the machine/nitro-enclave commit larger. What do you think?

As long as nothing compiles the code, it can rely on not yet implemented functions. So it's perfectly legit to add all your code in individual commits and then at the end add the meson.build change that implements the config option. How about the order below?

Quoted 8 lines

* Crypto patch for SHA384
* Crypto patch for x509 fingerprint
* NSM device emulation (including libcbor check, introduces CONFIG_VIRTIO_NSM)
* EIF format parsing (not compiled yet)
* Nitro Enclaves machine (introduces CONFIG_NITRO_ENCLAVE)
* Nitro Enclaves docs

Sounds good to me. Thanks Alex!

Regards,
Dorjoy

#11 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

In reply to Alexander Graf
Quoted 64 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

[...]

Quoted 18 lines
Quoted 18 lines
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
Quoted 9 lines

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 2 lines
hw/core/meson.build +1 -1
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

I see gnutls is not a required dependency in the root meson.build. I am not sure what we should do here.

Hey Daniel, do you have any suggestions about how this dependency should be included?

Regards,
Dorjoy

#12 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 96 lines · Dorjoy Chowdhury
Quoted 64 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

[...]

Quoted 18 lines
Quoted 18 lines
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
Quoted 9 lines

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 2 lines
hw/core/meson.build +1 -1
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

Quoted 5 lines

I see gnutls is not a required dependency in the root meson.build. I am not sure what we should do here.

Hey Daniel, do you have any suggestions about how this dependency should be included?

Unconditionally build the crypto/x509-utils.c file, but in that put file #ifdef CONFIG_GNUTLS, and in the #else put a stub impl of the method that just calls error_setg().

That way you can compile everything without any hard dep on gnutls, but if someone tries to use it they'll get a runtime error when gnutls is not built

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#13 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 104 lines · Daniel P. Berrangé
Quoted 96 lines · Dorjoy Chowdhury
Quoted 64 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

[...]

Quoted 18 lines
Quoted 18 lines
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
Quoted 9 lines

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 2 lines
hw/core/meson.build +1 -1
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

Quoted 5 lines

I see gnutls is not a required dependency in the root meson.build. I am not sure what we should do here.

Hey Daniel, do you have any suggestions about how this dependency should be included?

Quoted 8 lines

Unconditionally build the crypto/x509-utils.c file, but in that put file #ifdef CONFIG_GNUTLS, and in the #else put a stub impl of the method that just calls error_setg().

That way you can compile everything without any hard dep on gnutls, but if someone tries to use it they'll get a runtime error when gnutls is not built

Understood. Thanks! What should I do about libcbor? That one is required for building nitro-enclave and virtio-nsm. Should I make that required in the root meson.build file?

Regards,
Dorjoy

#14 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 109 lines · Dorjoy Chowdhury
Quoted 108 lines · Daniel P. Berrangé
Quoted 96 lines · Dorjoy Chowdhury
Quoted 64 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

[...]

Quoted 18 lines
Quoted 18 lines
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
Quoted 9 lines

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 2 lines
hw/core/meson.build +1 -1
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

Quoted 5 lines

I see gnutls is not a required dependency in the root meson.build. I am not sure what we should do here.

Hey Daniel, do you have any suggestions about how this dependency should be included?

Unconditionally build the crypto/x509-utils.c file, but in that put file #ifdef CONFIG_GNUTLS, and in the #else put a stub impl of the method that just calls error_setg().

Quoted 8 lines
Quoted 4 lines

That way you can compile everything without any hard dep on gnutls, but if someone tries to use it they'll get a runtime error when gnutls is not built

Understood. Thanks! What should I do about libcbor? That one is required for building nitro-enclave and virtio-nsm. Should I make that required in the root meson.build file?

No, we can't introduce new mandatory dependancies for a such a niche use case.

In retrospect, I think you'll need to conditionalize meson.build to avoid building any of the nitro-enclave & virtio-nsm code, when either gnutls or cbor are missing.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#15 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Quoted 120 lines · Daniel P. Berrangé
Quoted 109 lines · Dorjoy Chowdhury
Quoted 108 lines · Daniel P. Berrangé
Quoted 96 lines · Dorjoy Chowdhury
Quoted 64 lines · Alexander Graf

Hey Dorjoy,

Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 4 lines
---
  crypto/meson.build              |   2 +-
  crypto/x509-utils.c             |  73 +++++++++++

Can you please put this new API into its own patch file?

Quoted 2 lines
  hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
  hw/core/eif.h                   |   5 +-

These changes to eif.c should ideally already be part of the patch that introduces eif.c (patch 1), no? In fact, do you think you can make the whole eif logic its own patch file?

Quoted 14 lines
  hw/core/meson.build             |   4 +-
  hw/i386/Kconfig                 |   1 +
  hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
  include/crypto/x509-utils.h     |  22 ++++
  include/hw/i386/nitro_enclave.h |  26 ++++
  9 files changed, 479 insertions(+), 20 deletions(-)

create mode 100644 crypto/x509-utils.c
create mode 100644 include/crypto/x509-utils.h

crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 65

Quoted 5 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
  if gcrypt.found()
    util_ss.add(gcrypt, files('random-gcrypt.c'))
  elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))

What if we don't have gnutls. Will everything still compile or do we need to add any dependencies?

[...]

Quoted 18 lines
Quoted 18 lines
hw/core/meson.build +2 -0
index f32d1ad943..8dc4552e35 100644
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
    'qdev-clock.c',
  ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')
+
  common_ss.add(files('cpu-common.c'))
  common_ss.add(files('machine-smp.c'))
  system_ss.add(when: 'CONFIG_FITLOADER', if_true: files('loader-fit.c'))
@@ -24,7 +26,7 @@ system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c'))
  system_ss.add(when: 'CONFIG_SPLIT_IRQ', if_true: files('split-irq.c'))
  system_ss.add(when: 'CONFIG_XILINX_AXI', if_true: files('stream.c'))
  system_ss.add(when: 'CONFIG_PLATFORM_BUS', if_true: files('sysbus-fdt.c'))
Quoted 9 lines

hw/core/meson.build system_ss.add(when: 'CONFIG_REGISTER', if_true: files('register.c')) · line 29

Quoted 2 lines
hw/core/meson.build +1 -1
-system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib])
+system_ss.add(when: 'CONFIG_NITRO_ENCLAVE', if_true: [files('eif.c'), zlib, libcbor, gnutls])

Ah, you add the gnutls dependency here. Great! However, this means we now make gnutls (and libcbor) a mandatory dependency for the default configuration. Does configure know about that? I believe before gnutls was optional, right?

Quoted 5 lines

I see gnutls is not a required dependency in the root meson.build. I am not sure what we should do here.

Hey Daniel, do you have any suggestions about how this dependency should be included?

Unconditionally build the crypto/x509-utils.c file, but in that put file #ifdef CONFIG_GNUTLS, and in the #else put a stub impl of the method that just calls error_setg().

Quoted 8 lines
Quoted 4 lines

That way you can compile everything without any hard dep on gnutls, but if someone tries to use it they'll get a runtime error when gnutls is not built

Understood. Thanks! What should I do about libcbor? That one is required for building nitro-enclave and virtio-nsm. Should I make that required in the root meson.build file?

Quoted 7 lines

No, we can't introduce new mandatory dependancies for a such a niche use case.

In retrospect, I think you'll need to conditionalize meson.build to avoid building any of the nitro-enclave & virtio-nsm code, when either gnutls or cbor are missing.

Got it. I will look into making the build conditional. Thank you!

Regards,
Dorjoy

#16 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Hey Daniel,
The libvirt-ci repository has been updated with the libcbor dependency. Should I just update my submodule locally to point to the new master branch and then do a separate commit i.e., "Updated submodule..." and _then_ do this[1] as part of whatever commit introduces the libcbor dependency in QEMU?

[1] https://www.qemu.org/docs/master/devel/testing.html#adding-new-build-pre-requisites

Regards,
Dorjoy

#17 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

In reply to Dorjoy Chowdhury
Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 5 lines
---
 crypto/meson.build              |   2 +-
 crypto/x509-utils.c             |  73 +++++++++++
 include/crypto/x509-utils.h     |  22 ++++

Preferrably add these 3 in a standlone commit, since its is good practice to separate commits adding infra, from commits adding usage of infra.

Quoted 15 lines
 hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
 hw/core/eif.h                   |   5 +-
 hw/core/meson.build             |   4 +-
 hw/i386/Kconfig                 |   1 +
 hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
 include/hw/i386/nitro_enclave.h |  26 ++++
 9 files changed, 479 insertions(+), 20 deletions(-)
 create mode 100644 crypto/x509-utils.c
 create mode 100644 include/crypto/x509-utils.h
crypto/meson.build +0 -0
index c46f9c22a7..09633194ed 100644

crypto/meson.build endif · line 68

Quoted 8 lines
crypto/meson.build +1 -1
@@ -62,7 +62,7 @@ endif
 if gcrypt.found()
   util_ss.add(gcrypt, files('random-gcrypt.c'))
 elif gnutls.found()
-  util_ss.add(gnutls, files('random-gnutls.c'))
+  util_ss.add(gnutls, files('random-gnutls.c', 'x509-utils.c'))
 elif get_option('rng_none')
   util_ss.add(files('random-none.c'))
 else

This logic block is handling preferences for the RNG impl.

We want to be compiling x509-utils.c *anytime* gnutls is found, regardless of what we prioritize for RNG backend. Also it should be added to crypto_ss, not util_ss.

So put this as its own standalone block

if gnutls.found()

    crypto_ss.add(files('x509-utils.c'))

endif

Quoted 14 lines
crypto/x509-utils.c new file +8 -0
new file mode 100644
index 0000000000..2422eb995c
@@ -0,0 +1,73 @@
+/*
+ * X.509 certificate related helpers
+ *
+ * Copyright (c) 2024 Dorjoy Chowdhury <[email protected]>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * (at your option) any later version.  See the COPYING file in the
+ * top-level directory.

crypto/x509-utils.c line 18

Quoted 10 lines
crypto/x509-utils.c new file +10 -0
+ */
+
+#include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "crypto/x509-utils.h"
+#include <gnutls/gnutls.h>
+#include <gnutls/crypto.h>
+#include <gnutls/x509.h>
+
+static int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {

Can make this 'const' too

Quoted 8 lines
crypto/x509-utils.c new file +8 -0
+    [QCRYPTO_HASH_ALG_MD5] = GNUTLS_DIG_MD5,
+    [QCRYPTO_HASH_ALG_SHA1] = GNUTLS_DIG_SHA1,
+    [QCRYPTO_HASH_ALG_SHA224] = GNUTLS_DIG_SHA224,
+    [QCRYPTO_HASH_ALG_SHA256] = GNUTLS_DIG_SHA256,
+    [QCRYPTO_HASH_ALG_SHA384] = GNUTLS_DIG_SHA384,
+    [QCRYPTO_HASH_ALG_SHA512] = GNUTLS_DIG_SHA512,
+    [QCRYPTO_HASH_ALG_RIPEMD160] = GNUTLS_DIG_RMD160,
+};

crypto/x509-utils.c line 36

Quoted 10 lines
crypto/x509-utils.c new file +10 -0
+
+int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
+                                      QCryptoHashAlgorithm alg,
+                                      uint8_t **result,
+                                      size_t *resultlen,
+                                      Error **errp)
+{
+    int ret;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};

Assign '*result = NULL' && '*resultlen = 0' here at the start, so we have clear semantics on failure.

Quoted 19 lines
crypto/x509-utils.c new file +19 -0
+
+    if (alg >= G_N_ELEMENTS(qcrypto_to_gnutls_hash_alg_map)) {
+        error_setg(errp, "Unknown hash algorithm");
+        return -1;
+    }
+
+    gnutls_x509_crt_init(&crt);
+
+    if (gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM) != 0) {
+        error_setg(errp, "Failed to import certificate");
+        goto cleanup;
+    }
+
+    ret = gnutls_hash_get_len(qcrypto_to_gnutls_hash_alg_map[alg]);
+    if (*resultlen == 0) {
+        *resultlen = ret;
+        *result = g_new0(uint8_t, *resultlen);
+    } else if (*resultlen < ret) {
+        error_setg(errp,

crypto/x509-utils.c line 65

Quoted 10 lines
crypto/x509-utils.c new file +10 -0
+                   "Result buffer size %zu is smaller than hash %d",
+                   *resultlen, ret);
+        goto cleanup;
+    }
+
+    if (gnutls_x509_crt_get_fingerprint(crt,
+                                        qcrypto_to_gnutls_hash_alg_map[alg],
+                                        *result, resultlen) != 0) {
+        error_setg(errp, "Failed to get fingerprint from certificate");
+        goto cleanup;

We should free(*result) and *result = NULL; && *resultlen = 0 here to undo the previous step.

Quoted 80 lines
crypto/x509-utils.c new file +8 -0
+    }
+
+    return 0;
+
+ cleanup:
 
 
+    gnutls_x509_crt_deinit(crt);
+    return -1;
+}
hw/core/eif.c +6 -8
index 5558879a96..8e15142d36 100644
@@ -11,7 +11,10 @@
 #include "qemu/osdep.h"
 #include "qemu/bswap.h"
 #include "qapi/error.h"
+#include "crypto/hash.h"
+#include "crypto/x509-utils.h"
 #include <zlib.h> /* for crc32 */
+#include <cbor.h>
 
 #include "hw/core/eif.h"
 
@@ -180,11 +183,10 @@ static void safe_unlink(char *f)
  * Upon success, the caller is reponsible for unlinking and freeing *kernel_path
  */
 static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
-                            uint32_t *crc, Error **errp)
+                            uint8_t *kernel, uint32_t *crc, Error **errp)
 {
     size_t got;
     FILE *tmp_file = NULL;
-    uint8_t *kernel = NULL;
 
     *kernel_path = NULL;
     if (!get_tmp_file("eif-kernel-XXXXXX", kernel_path, errp)) {
@@ -198,7 +200,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
         goto cleanup;
     }
 
-    kernel = g_malloc(size);
     got = fread(kernel, 1, size, f);
     if ((uint64_t) got != size) {
         error_setg(errp, "Failed to read EIF kernel section data");
@@ -213,7 +214,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
     }
 
     *crc = crc32(*crc, kernel, size);
-    g_free(kernel);
     fclose(tmp_file);
 
     return true;
@@ -225,7 +225,6 @@ static bool read_eif_kernel(FILE *f, uint64_t size, char **kernel_path,
     g_free(*kernel_path);
     *kernel_path = NULL;
 
-    g_free(kernel);
     return false;
 }
 
@@ -243,29 +242,115 @@ static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline,
 }
 
 static bool read_eif_ramdisk(FILE *eif, FILE *initrd, uint64_t size,
-                             uint32_t *crc, Error **errp)
+                             uint8_t *ramdisk, uint32_t *crc, Error **errp)
 {
     size_t got;
-    uint8_t *ramdisk = g_malloc(size);
 
     got = fread(ramdisk, 1, size, eif);
     if ((uint64_t) got != size) {
         error_setg(errp, "Failed to read EIF ramdisk section data");
-        goto cleanup;
+        return false;
     }
 
     got = fwrite(ramdisk, 1, size, initrd);

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 263

Quoted 10 lines
hw/core/eif.c +3 -2
     if ((uint64_t) got != size) {
         error_setg(errp, "Failed to write EIF ramdisk data to temporary file");
-        goto cleanup;
+        return false;
     }
 
     *crc = crc32(*crc, ramdisk, size);
-    g_free(ramdisk);
+    return true;
+}

Just fold this into the earlier commit in the series that added these functions.

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 272

Quoted 9 lines
hw/core/eif.c +9 -0
+
+static bool get_signature_fingerprint_sha384(FILE *eif, uint64_t size,
+                                             uint8_t *sha384,
+                                             uint32_t *crc,
+                                             Error **errp)
+{
+    size_t got;
+    uint8_t *sig = NULL;
+    uint8_t *cert = NULL;

Declare both of these with 'g_autofree' since they both are temporary buffers that need to be free on both success & failure paths.

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 278

Quoted 6 lines
hw/core/eif.c +6 -0
+    cbor_item_t *item = NULL;
+    cbor_item_t *pcr0 = NULL;
+    size_t len;
+    size_t hash_len = 48;
+    struct cbor_pair *pair;
+    struct cbor_load_result result;

Add 'bool ret = false' here

Quoted 53 lines
hw/core/eif.c +53 -0
+
+    sig = g_malloc(size);
+    got = fread(sig, 1, size, eif);
+    if ((uint64_t) got != size) {
+        error_setg(errp, "Failed to read EIF signature section data");
+        goto cleanup;
+    }
+
+    *crc = crc32(*crc, sig, size);
+
+    item = cbor_load(sig, size, &result);
+    if (!item || result.error.code != CBOR_ERR_NONE) {
+        error_setg(errp, "Failed to load signature section data as CBOR");
+        goto cleanup;
+    }
+    if (!cbor_isa_array(item) || cbor_array_size(item) < 1) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanu;p
+    }
+    pcr0 = cbor_array_get(item, 0);
+    if (!pcr0) {
+        error_setg(errp, "Failed to get PCR0 signature");
+        goto cleanup;
+    }
+    if (!cbor_isa_map(pcr0) || cbor_map_size(pcr0) != 2) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    pair = cbor_map_handle(pcr0);
+    if (!cbor_isa_string(pair->key) || cbor_string_length(pair->key) != 19 ||
+        memcmp(cbor_string_handle(pair->key), "signing_certificate", 19) != 0) {
+        error_setg(errp, "Invalid signautre CBOR");
+        goto cleanup;
+    }
+    if (!cbor_isa_array(pair->value)) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    len = cbor_array_size(pair->value);
+    if (len == 0) {
+        error_setg(errp, "Invalid signature CBOR");
+        goto cleanup;
+    }
+    cert = g_malloc(len);
+    for (int i = 0; i < len; ++i) {
+        cbor_item_t *tmp = cbor_array_get(pair->value, i);
+        if (!tmp) {
+            error_setg(errp, "Invalid signature CBOR");
+            goto cleanup;
+        }
+        if (!cbor_isa_uint(tmp) || cbor_int_get_width(tmp) != CBOR_INT_8) {
+            cbor_decref(&tmp);
+            error_setg(errp, "Invalid signature CBOR");

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 341

Quoted 10 lines
hw/core/eif.c +10 -0
+            goto cleanup;
+        }
+        cert[i] = cbor_get_uint8(tmp);
+        cbor_decref(&tmp);
+    }
+
+    if (qcrypto_get_x509_cert_fingerprint(cert, len, QCRYPTO_HASH_ALG_SHA384,
+                                          &sha384, &hash_len, errp)) {
+        goto cleanup;
+    }

Nothing is free'ing item & pcr0

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 343

Quoted 2 lines
hw/core/eif.c +1 -0
+
     return true;

Change this to

    ret = true;

and allow to fallthrough the cleanup: label, so we get the freeing of item & pcr0 on both success & failure

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 347

Quoted 5 lines
hw/core/eif.c +2 -1
  cleanup:
-    g_free(ramdisk);
+    g_free(sig);
+    g_free(cert);

Remove these two since we can g_autofree them[

hw/core/eif.c static bool read_eif_cmdline(FILE *f, uint64_t size, char *cmdline, · line 354

Quoted 7 lines
hw/core/eif.c +6 -0
+    if (pcr0) {
+        cbor_decref(&pcr0);
+    }
+    if (item) {
+        cbor_decref(&item);
+    }
     return false;

return ret;

Quoted 63 lines
hw/core/eif.c +28 -3
 }
 
@@ -299,7 +384,9 @@ static long get_file_size(FILE *f, Error **errp)
  */
 bool read_eif_file(const char *eif_path, const char *machine_initrd,
                    char **kernel_path, char **initrd_path, char **cmdline,
-                   Error **errp)
+                   uint8_t *image_sha384, uint8_t *bootstrap_sha384,
+                   uint8_t *app_sha384, uint8_t *fingerprint_sha384,
+                   bool *signature_found, Error **errp)
 {
     FILE *f = NULL;
     FILE *machine_initrd_f = NULL;
@@ -308,7 +395,19 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
     uint32_t crc = 0;
     EifHeader eif_header;
     bool seen_sections[EIF_SECTION_MAX] = {false};
-
+    /* kernel + ramdisks + cmdline sha384 hash */
+    struct iovec image_hash_iovecs[MAX_SECTIONS + 1];
+    int image_hash_iovec_cnt = 0;
+    /* kernel + boot ramdisk + cmdline sha384 hash */
+    struct iovec bootstrap_hash_iovecs[3];
+    int bootstrap_hash_iovec_cnt = 0;
+    /* application ramdisk(s) hash */
+    struct iovec app_hash_iovecs[MAX_SECTIONS + 1];
+    int app_hash_iovec_cnt = 0;
+    uint8_t *ptr = NULL;
+    size_t digest_len;
+
+    *signature_found = false;
     *kernel_path = *initrd_path = *cmdline = NULL;
 
     f = fopen(eif_path, "rb");
@@ -373,8 +472,18 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
                            "section");
                 goto cleanup;
             }
+
+            ptr = g_malloc(section_header.section_size);
+
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len =
+                section_header.section_size;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base = ptr;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len =
+                section_header.section_size;
+
             if (!read_eif_kernel(f, section_header.section_size, kernel_path,
-                                 &crc, errp)) {
+                                 ptr, &crc, errp)) {
                 goto cleanup;
             }
 
@@ -382,6 +491,7 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
         case EIF_SECTION_CMDLINE:
         {
             uint64_t size;
+            uint8_t *cmdline_copy;
             if (seen_sections[EIF_SECTION_CMDLINE]) {
                 error_setg(errp, "Invalid EIF image. More than 1 cmdline "
                            "section");

hw/core/eif.c bool read_eif_file(const char *eif_path, const char *machine_initrd, · line 513

Quoted 10 lines
hw/core/eif.c +7 -0
@@ -394,6 +504,19 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
             }
             (*cmdline)[size] = '\0';
 
+            /*
+             * We make a copy of '*cmdline' for putting it in iovecs so that
+             * we can easily free all the iovec entries later as we cannot
+             * free '*cmdline' which is used by the caller.
+             */
+            cmdline_copy = g_malloc(size);
+            memcpy(cmdline_copy, *cmdline, size);

Replace by 1 liner:

   cmdline_copy = g_memdup2(*cmdline, size);
Quoted 61 lines
hw/core/eif.c +40 -1
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = cmdline_copy;
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len = size;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base =
+                cmdline_copy;
+            bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len = size;
+
             break;
         }
         case EIF_SECTION_RAMDISK:
@@ -414,13 +537,41 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
                 }
             }
 
+            ptr = g_malloc(section_header.section_size);
+
+            image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;
+            image_hash_iovecs[image_hash_iovec_cnt++].iov_len =
+                section_header.section_size;
+            /*
+             * If it's the first ramdisk, we need to hash it into bootstrap,
+             * otherwise we need to hash it into app.
+             */
+            if (!seen_sections[EIF_SECTION_RAMDISK]) {
+                bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt].iov_base = ptr;
+                bootstrap_hash_iovecs[bootstrap_hash_iovec_cnt++].iov_len =
+                    section_header.section_size;
+            } else {
+                app_hash_iovecs[app_hash_iovec_cnt].iov_base = ptr;
+                app_hash_iovecs[app_hash_iovec_cnt++].iov_len =
+                    section_header.section_size;
+            }
+
             if (!read_eif_ramdisk(f, initrd_path_f, section_header.section_size,
-                                  &crc, errp)) {
+                                  ptr, &crc, errp)) {
                 goto cleanup;
             }
 
             break;
         }
+        case EIF_SECTION_SIGNATURE:
+            *signature_found = true;
+            if (!get_signature_fingerprint_sha384(f,
+                                                  section_header.section_size,
+                                                  fingerprint_sha384, &crc,
+                                                  errp)) {
+                goto cleanup;
+            }
+            break;
         default:
             /* other sections including invalid or unknown sections */
         {
@@ -483,18 +634,60 @@ bool read_eif_file(const char *eif_path, const char *machine_initrd,
             goto cleanup;
         }
 
+        ptr = g_malloc(machine_initrd_size);
+
+        image_hash_iovecs[image_hash_iovec_cnt].iov_base = ptr;
+        image_hash_iovecs[image_hash_iovec_cnt++].iov_len = machine_initrd_size;
+        app_hash_iovecs[app_hash_iovec_cnt].iov_base = ptr;

hw/core/eif.c bool read_eif_file(const char *eif_path, const char *machine_initrd, · line 650

Quoted 10 lines
hw/core/eif.c +4 -1
+        app_hash_iovecs[app_hash_iovec_cnt++].iov_len = machine_initrd_size;
+
         if (!read_eif_ramdisk(machine_initrd_f, initrd_path_f,
-                              machine_initrd_size, &crc, errp)) {
+                              machine_initrd_size, ptr, &crc, errp)) {
             goto cleanup;
         }
     }
 
+    digest_len = 48;

You might as well use the constant "SHA384_BYTE_LEN" this patch already adds.

Quoted 50 lines
hw/core/eif.c +34 -0
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, image_hash_iovecs,
+                            image_hash_iovec_cnt, &image_sha384, &digest_len,
+                            errp) < 0) {
+        goto cleanup;
+
+    }
+
+    digest_len = 48;
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, bootstrap_hash_iovecs,
+                            bootstrap_hash_iovec_cnt, &bootstrap_sha384,
+                            &digest_len, errp) < 0) {
+        goto cleanup;
+
+    }
+
+    digest_len = 48;
+    if (qcrypto_hash_bytesv(QCRYPTO_HASH_ALG_SHA384, app_hash_iovecs,
+                            app_hash_iovec_cnt, &app_sha384, &digest_len,
+                            errp) < 0) {
+        goto cleanup;
+
+    }
+
+    /*
+     * We only need to free image_hash_iovec entries because bootstrap and
+     * app iovec entries are subsets of image_hash_iovec entries.
+     */
+    for (int i = 0; i < image_hash_iovec_cnt; ++i) {
+        g_free(image_hash_iovecs[i].iov_base);
+    }
     fclose(f);
     fclose(initrd_path_f);
     safe_fclose(machine_initrd_f);
     return true;
 
  cleanup:
+    for (int i = 0; i < image_hash_iovec_cnt; ++i) {
+        g_free(image_hash_iovecs[i].iov_base);
+    }
+
     safe_fclose(f);
     safe_fclose(initrd_path_f);
     safe_fclose(machine_initrd_f);
hw/core/meson.build +0 -0
index f32d1ad943..8dc4552e35 100644

hw/core/meson.build hwcore_ss.add(files( · line 15

Quoted 4 lines
hw/core/meson.build +1 -0
@@ -12,6 +12,8 @@ hwcore_ss.add(files(
   'qdev-clock.c',
 ))
 
+libcbor = dependency('libcbor', version: '>=0.7.0')

Our pattern is to have all 'dependency()' listed in the top level meson.build. Not quite sure why we do that but best to follow the pattern IMHO.

Also, to be able to test this, we need to get libcbor added to our containers

Look at the "Adding new build pre-requisites" section in docs/devel/testing.rst

I'll review the submission to libvirt-ci.git that you'll need to do as part of this

Quoted 33 lines
hw/core/meson.build +33 -0
+static void nitro_enclave_machine_reset(MachineState *machine,
+                                        ShutdownCause reason)
+{
+    NitroEnclaveMachineClass *ne_class =
+        NITRO_ENCLAVE_MACHINE_GET_CLASS(machine);
+    NitroEnclaveMachineState *ne_state = NITRO_ENCLAVE_MACHINE(machine);
+
+    ne_class->parent_reset(machine, reason);
+
+    memset(ne_state->vnsm->pcrs, 0, sizeof(ne_state->vnsm->pcrs));
+
+    /* PCR0 */
+    ne_state->vnsm->extend_pcr(ne_state->vnsm, 0, ne_state->image_sha384,
+                               SHA384_BYTE_LEN);
+    /* PCR1 */
+    ne_state->vnsm->extend_pcr(ne_state->vnsm, 1, ne_state->bootstrap_sha384,
+                               SHA384_BYTE_LEN);
+    /* PCR2 */
+    ne_state->vnsm->extend_pcr(ne_state->vnsm, 2, ne_state->app_sha384,
+                               SHA384_BYTE_LEN);
+    /* PCR3 */
+    if (ne_state->parent_role) {
+        ne_state->vnsm->extend_pcr(ne_state->vnsm, 3,
+                                   (uint8_t *) ne_state->parent_role,
+                                   strlen(ne_state->parent_role));
+    }
+    /* PCR4 */
+    if (ne_state->parent_id) {
+        ne_state->vnsm->extend_pcr(ne_state->vnsm, 4,
+                                   (uint8_t *) ne_state->parent_id,
+                                   strlen(ne_state->parent_id));
+    }
+    /* PCR8 */

hw/core/meson.build hwcore_ss.add(files(

Quoted 10 lines
hw/core/meson.build +10 -0
+    if (ne_state->signature_found) {
+        ne_state->vnsm->extend_pcr(ne_state->vnsm, 8,
+                                   ne_state->fingerprint_sha384,
+                                   SHA384_BYTE_LEN);
+    }
+
+    /* First 16 PCRs are locked from boot and reserved for nitro enclave */
+    for (int i = 0; i < 16; ++i) {
+        ne_state->vnsm->lock_pcr(ne_state->vnsm, i);
+    }

Worth NITRO_PCR_MAX constant ?

hw/core/meson.build

Quoted 7 lines

static void nitro_enclave_machine_initfn(Object *obj)

 {
     MicrovmMachineState *mms = MICROVM_MACHINE(obj);
     X86MachineState *x86ms = X86_MACHINE(obj);
hw/core/meson.build +3 -0
+    NitroEnclaveMachineState *nems = NITRO_ENCLAVE_MACHINE(obj);
+
+    nems->id = g_strdup("i-234-enc5678");

Is this some magic string that the Nitro spec requires ? If so, probably worth a #define constant for it with a comment about rationale.

Quoted 19 lines
 
     /* AWS nitro enclaves have PCIE and ACPI disabled */
     mms->pcie = ON_OFF_AUTO_OFF;
hw/core/meson.build +5 -1
@@ -103,9 +170,13 @@ static void x86_load_eif(X86MachineState *x86ms, FWCfgState *fw_cfg,
     Error *err = NULL;
     char *eif_kernel, *eif_initrd, *eif_cmdline;
     MachineState *machine = MACHINE(x86ms);
+    NitroEnclaveMachineState *nems = NITRO_ENCLAVE_MACHINE(x86ms);
 
     if (!read_eif_file(machine->kernel_filename, machine->initrd_filename,
-                       &eif_kernel, &eif_initrd, &eif_cmdline, &err)) {
+                       &eif_kernel, &eif_initrd, &eif_cmdline,
+                       nems->image_sha384, nems->bootstrap_sha384,
+                       nems->app_sha384, nems->fingerprint_sha384,
+                       &(nems->signature_found), &err)) {
         error_report_err(err);
         exit(1);
     }

hw/core/meson.build static void nitro_enclave_set_vsock_chardev_id(Object *obj, const char *value, · line 248

Quoted 2 lines
hw/core/meson.build +0 -0
@@ -176,6 +247,54 @@ static void nitro_enclave_set_vsock_chardev_id(Object *obj, const char *value,
     nems->vsock = g_strdup(value);
 }

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#18 lore raw

Re: [PATCH v4 4/6] machine/nitro-enclave: Add built-in Nitro Secure Module device

Hi Daniel,

Quoted 38 lines · Daniel P. Berrangé
Quoted 17 lines · Dorjoy Chowdhury

AWS Nitro Enclaves have built-in Nitro Secure Module (NSM) device which is used for stripped down TPM functionality like attestation. This commit adds the built-in NSM device in the nitro-enclave machine type.

In Nitro Enclaves, all the PCRs start in a known zero state and the first 16 PCRs are locked from boot and reserved. The PCR0, PCR1, PCR2 and PCR8 contain the SHA384 hashes related to the EIF file used to boot the VM for validation.

Some optional nitro-enclave machine options have been added:
- 'id': Enclave identifier, reflected in the module-id of the NSM
device. If not provided, a default id will be set.
- 'parent-role': Parent instance IAM role ARN, reflected in PCR3
of the NSM device.
- 'parent-id': Parent instance identifier, reflected in PCR4 of the
NSM device.

Quoted 5 lines
---
 crypto/meson.build              |   2 +-
 crypto/x509-utils.c             |  73 +++++++++++
 include/crypto/x509-utils.h     |  22 ++++

Preferrably add these 3 in a standlone commit, since its is good practice to separate commits adding infra, from commits adding usage of infra.

Quoted 10 lines
 hw/core/eif.c                   | 225 +++++++++++++++++++++++++++++---
 hw/core/eif.h                   |   5 +-
 hw/core/meson.build             |   4 +-
 hw/i386/Kconfig                 |   1 +
 hw/i386/nitro_enclave.c         | 141 +++++++++++++++++++-
 include/hw/i386/nitro_enclave.h |  26 ++++
 9 files changed, 479 insertions(+), 20 deletions(-)
 create mode 100644 crypto/x509-utils.c
 create mode 100644 include/crypto/x509-utils.h

[...]

Quoted 8 lines

hw/i386/nitro_enclave.c static void nitro_enclave_machine_state_init(MachineState *machine) · line 151

Quoted 5 lines
hw/i386/nitro_enclave.c +5 -0
+
+    /* First 16 PCRs are locked from boot and reserved for nitro enclave */
+    for (int i = 0; i < 16; ++i) {
+        ne_state->vnsm->lock_pcr(ne_state->vnsm, i);
+    }

Worth NITRO_PCR_MAX constant ?

I kept the 16 for now.

Quoted 11 lines

hw/i386/nitro_enclave.c static void nitro_enclave_machine_state_init(MachineState *machine) · line 160

Quoted 7 lines

static void nitro_enclave_machine_initfn(Object *obj)

 {
     MicrovmMachineState *mms = MICROVM_MACHINE(obj);
     X86MachineState *x86ms = X86_MACHINE(obj);
hw/i386/nitro_enclave.c +3 -0
+    NitroEnclaveMachineState *nems = NITRO_ENCLAVE_MACHINE(obj);
+
+    nems->id = g_strdup("i-234-enc5678");

Is this some magic string that the Nitro spec requires ? If so, probably worth a #define constant for it with a comment about rationale.

It's just some default we provide, not related to Nitro spec. So kept it as is for now.

Regards,
Dorjoy

#19 lore raw

PATCH v4 5/6 crypto: Support SHA384 hash when using glib

In reply to Dorjoy Chowdhury

QEMU requires minimum glib version 2.66.0 as per the root meson.build file and per glib documentation[1] G_CHECKSUM_SHA384 is available since 2.51.

[1] https://docs.gtk.org/glib/enum.ChecksumType.html

---
 crypto/hash-glib.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
crypto/hash-glib.c +1 -1
index 82de9db705..18e64faa9c 100644
@@ -29,7 +29,7 @@ static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
     [QCRYPTO_HASH_ALG_SHA1] = G_CHECKSUM_SHA1,
     [QCRYPTO_HASH_ALG_SHA224] = -1,
     [QCRYPTO_HASH_ALG_SHA256] = G_CHECKSUM_SHA256,
-    [QCRYPTO_HASH_ALG_SHA384] = -1,
+    [QCRYPTO_HASH_ALG_SHA384] = G_CHECKSUM_SHA384,
     [QCRYPTO_HASH_ALG_SHA512] = G_CHECKSUM_SHA512,
     [QCRYPTO_HASH_ALG_RIPEMD160] = -1,
 };
Signature · 1 line
2.39.2
Reviewed-by on v4 5/6
#20 lore raw

Re: [PATCH v4 5/6] crypto: Support SHA384 hash when using glib

Quoted 10 lines · Dorjoy Chowdhury

QEMU requires minimum glib version 2.66.0 as per the root meson.build file and per glib documentation[1] G_CHECKSUM_SHA384 is available since 2.51.

[1] https://docs.gtk.org/glib/enum.ChecksumType.html

---
 crypto/hash-glib.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

crypto/hash-glib.c static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = { · line 35

Quoted 13 lines
crypto/hash-glib.c +1 -1
index 82de9db705..18e64faa9c 100644
@@ -29,7 +29,7 @@ static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
     [QCRYPTO_HASH_ALG_SHA1] = G_CHECKSUM_SHA1,
     [QCRYPTO_HASH_ALG_SHA224] = -1,
     [QCRYPTO_HASH_ALG_SHA256] = G_CHECKSUM_SHA256,
-    [QCRYPTO_HASH_ALG_SHA384] = -1,
+    [QCRYPTO_HASH_ALG_SHA384] = G_CHECKSUM_SHA384,
     [QCRYPTO_HASH_ALG_SHA512] = G_CHECKSUM_SHA512,
     [QCRYPTO_HASH_ALG_RIPEMD160] = -1,
 };

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#21 lore raw

PATCH v4 6/6 docs/nitro-enclave: Documentation for nitro-enclave machine type

In reply to Dorjoy Chowdhury
---
 docs/system/i386/nitro-enclave.rst | 82 ++++++++++++++++++++++++++++++
 1 file changed, 82 insertions(+)
 create mode 100644 docs/system/i386/nitro-enclave.rst
docs/system/i386/nitro-enclave.rst new file +82 -0
new file mode 100644
index 0000000000..291a8ae357
@@ -0,0 +1,82 @@
+'nitro-enclave' virtual machine (``nitro-enclave``)
+===================================================
+
+``nitro-enclave`` is a machine type which emulates an ``AWS nitro enclave``
+virtual machine. `AWS nitro enclaves`_ is an `Amazon EC2`_ feature that allows
+creating isolated execution environments, called enclaves, from Amazon EC2
+instances which are used for processing highly sensitive data. Enclaves have
+no persistent storage and no external networking. The enclave VMs are based
+on Firecracker microvm with a vhost-vsock device for communication with the
+parent EC2 instance that spawned it and a Nitro Secure Module (NSM) device
+for cryptographic attestation. The parent instance VM always has CID 3 while
+the enclave VM gets a dynamic CID. Enclaves use an EIF (`Enclave Image Format`_)
+file which contains the necessary kernel, cmdline and ramdisk(s) to boot.
+
+In QEMU, ``nitro-enclave`` is a machine type based on ``microvm`` similar to how
+``AWS nitro enclaves`` are based on ``Firecracker`` microvm. This is useful for
+local testing of EIF files using QEMU instead of running real AWS Nitro Enclaves
+which can be difficult for debugging due to its roots in security. The vsock
+device emulation is done using vhost-user-vsock which means another process that
+can do the userspace emulation, like `vhost-device-vsock`_ from rust-vmm crate,
+must be run alongside nitro-enclave for the vsock communication to work.
+
+.. _AWS nitro enlaves: https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html
+.. _Amazon EC2: https://aws.amazon.com/ec2/
+.. _Enclave Image Format: https://github.com/aws/aws-nitro-enclaves-image-format
+.. _vhost-device-vsock: https://github.com/rust-vmm/vhost-device/tree/main/vhost-device-vsock
+
+Using the nitro-enclave machine type
+------------------------------
+
+Machine-specific options
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+It supports the following machine-specific options:
+
+- nitro-enclave.vsock=string (required) (Id of the chardev from '-chardev' option that vhost-user-vsock device will use)
+- nitro-enclave.id=string (optional) (Set enclave identifier)
+- nitro-enclave.parent-role=string (optional) (Set parent instance IAM role ARN)
+- nitro-enclave.parent-id=string (optional) (Set parent instance identifier)
+
+
+Running a nitro-enclave VM
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+First, run vhost-device-vsock (or a similar tool that supports vhost-user-vsock)
+
+  $ vhost-device-vsock \
+     --vm guest-cid=4,uds-path=/tmp/vm4.vsock,socket=/tmp/vhost4.socket \
+     --vm guest-cid=3,uds-path=/tmp/vm3.vsock,socket=/tmp/vhost3.socket
+
+Then, run the parent VM that has the necessary vsock communication support.
+
+  $ qemu-system-x86_64 -machine q35,memory-backend=mem0 -enable-kvm -m 8G \
+     -nic user,model=virtio -drive file=test_vm.qcow2,media=disk,if=virtio \
+     --display sdl -object memory-backend-memfd,id=mem0,size=8G \
+     -chardev socket,id=char0,reconnect=0,path=/tmp/vhost3.socket \
+     -device vhost-user-vsock-pci,chardev=char0
+
+Inside this VM the necessary applications should be run so that the nitro-enclave
+VM applications' vsock communication works. For example, the nitro-enclave VM's
+init process connects to CID 3 and sends a single byte hello heartbeat (0xB7) to
+let the parent VM know that it booted expecting a heartbeat (0xB7) response.
+
+Now run the nitro-enclave VM using the following command where ``hello.eif`` is
+an EIF file you would use to spawn a real AWS nitro enclave virtual machine:
+
+  $ qemu-system-x86_64 -M nitro-enclave,vsock=c,id=hello-world \
+     -kernel hello-world.eif -nographic -m 4G --enable-kvm -cpu host \
+     -chardev socket,id=c,path=/tmp/vhost4.socket
+
+In this example, the nitro-enclave VM has CID 4.
+
+
+Limitations
+-----------
+
+AWS nitro enclave emulation support in QEMU requires users to run vhost-device-vsock
+or similar tool for vhost-user-vsock support and another VM with CID 3 with necessary
+vsock communication support. Requirement of running another VM and necessary applications
+inside it can be lifted if some proxying support is added to vhost-device-vsock to
+forward all packets to the host machine, in which case, users can run the necessary
+applications in the host machine instead of the parent VM with CID 3.
Signature · 1 line
2.39.2