Skip to contentSkip to conversation

Secure IPL Support for SCSI Scheme of virtio-blk/virtio-scsi Devices

PATCH Superseded Zhuoying Cai 7 participants 64 messages Aug 18, 2025 – Sep 16, 2025

Subsystems (2)

v5 of 17 Superseded Latest is v17 →

lore
Share & tools
lore
#0 lore raw

v5 cover Secure IPL Support for SCSI Scheme of virtio-blk/virtio-scsi Devices

Changelog v4->v5

- Segmented documentation by introducing them alongside the patches that add the relevant functionality
- Removed hash-type restriction from S390IPLCertificateStore

Add boot-certs to s390-ccw-virtio machine type option
- Added boot-certs property to the s390-ccw-virtio machine type

    - Changed to use an array property for passing certificate instead
      of colo-delimited strings.
    e.g. boot-certs.0.path=/path/to/dir,
         boot-certs.1.path=/to/other/dir,
         boot-certs.2.path=/some/...

crypto/x509-utils
- Refactored fallback handling into a separated commit
- Removed QCryptoKeyidFlags and qcrypto_x509_get_keyid_len() function
- Removed qcrypto_x509_get_cert_version() and qcrypto_x509_get_signature_algorithm()
- Passed QCryptoHashAlgo to qcrypto_x509_get_cert_key_id() instead of QCryptoKeyidFlags
- Improved memory cleanup

hw/s390x/ipl: Create certificate store
- Fixed error handling and memory management
- Added condition to only accept files with ".pem" extension

s390x: Guest support for Certificate Store Facility (CS)
- Renamed "S390_FEAT_DIAG_320" to "S390_FEAT_CERT_STORE"
- Merged this patch with s390x/diag: Introduce DIAG 320 for certificate store facility patch

s390x/diag: Introduce DIAG 320 for certificate store facility
- Added bit zero to indicate subcode 0 is supported
- Set response code to 0x0102 when the subcode is not supported
- Added check to ensure subcode fits within one byte

s390x/diag: Implement DIAG 320 subcode 1
- Refactored and moved implementation to a helper function
- Added check to ensure VCSSB length is set to a minimum of 128 bytes from the userspace
- Removed max_vce_len field from the VCSSB data structure

s390x/diag: Implement DIAG 320 subcode 2
- Refactored and split functions for extracting certificate information
- Set VCE length to 72 if certificate is invalid
- Returned VCE even if the certificate is invalid

pc-bios/s390-ccw: Refactor zipl_run()
- Refactor zipl_run_normal() to reduce duplicate code

pc-bios/s390-ccw: Add signature verification for secure IPL in audit mode
- Moved secure-boot related functions into secure-ipl.c/h files
- Rename zipl_handle_sig_entry() to zipl_load_signature()
- Refactored zipl_run_secure() to use switch cases for different entry types instead of a while loop
- Renamed ZiplBootMode enumerations with "ZIPL_BOOT_MODE" prefix
- Added meaningful file header to secure-ipl.c
- Renamed zipl_secure_print() to zipl_secure_handle()

-----------------------------------------------------------------------

# Description

This patch series is an external requirement by Linux distribution partners to verify secure IPL process. Additional secure IPL checks are also included in this series to address security holes in the original secure IPL design to prevent malicious actors to boot modified or unsigned code despite secure IPL being enforced.

Secure IPL is enabled when the QEMU options for secure IPL are specified in the command line.

During this process, additional security checks are performed to ensure system integrity.

As components are loaded from disk, DIAG 508 subcode 2 performs signature verification if a signature entry is identified. Upon successful verification, DIAG 320 subcode 2 will request the corresponding certificate from QEMU key store to the BIOS.

Secure IPL will continue until all the components are loaded if no error occurs during True secure IPL mode or in Audit mode (see explanation below).

After that, an IPL Information report block (IIRB) is initialized immediately following an IPL Parameter Information Block. The IIRB is populated with information about the components, verification results and certificate data.

Finally, the guest system proceeds to boot.

Only List-Directed-IPL contains the relevant zIPL data structures to perform secure IPL. This patch series only adds support for the SCSI scheme of virtio-blk/virtio-scsi devices. Secure IPL for other device types will be considered as follow-up work at a later date.

** Note: "secure IPL" and "secure boot" are used interchangeably throughout the design. **

# True Secure IPL Mode and Audit Mode

## True Secure IPL Mode

When secure IPL is enabled and certificates are provided, all the secure IPL checks will performed. The boot process will abort if any error occurs during the secure IPL checks.

## Audit Mode

When the secure IPL option is not selected and certificates are provided, all the secure IPL checks will still be performed. However, the boot process will continue if any errors occur, with messages logged to the console during the secure IPL checks.

The audit mode is also considered as simulated secure IPL because it is less pervasive, and allows the guest to boot regardless of the secure checking results.

# How to Enable Secure IPL

## QEMU Build Notes

When building QEMU, enable the cryptographic libraries.

Run configure script in QEMU repository with either parameter:

	./configure … --enable-gnutls

## Create Certificates via certtool

Generate and use an RSA private key for signing.

	certtool --generate-privkey > key.pem

A self-signed certificate requires the organization name. Use the cert.info template to pre-fill values and avoid interactive prompts from certtool.

	cat > cert.info <<EOF
	cn = "My Name"
	expiration_days = 36500
	cert_signing_key
	EOF

	certtool --generate-self-signed \
		 --load-privkey key.pem \
		 --template cert.info \
		 --hash=SHA256 \
		 --outfile cert.pem

It is recommended to store the certificate(s) in the /…/qemu/certs directory for easy identification.

## Sign Kernel and Prepare zipl

All actions must be performed on a KVM guest.

Copy the sign-file script (located in Linux source repository), generated private key(s), and certificate(s) to guest's file system.

Sign guest image(s) and stage3 binary:

	./sign-file sha256 key.pem cert.pem /boot/vmlinuz-…

	./sign-file sha256 key.pem cert.pem /usr/lib/s390-tools/stage3.bin

Run zipl with secure boot enabled.

	zipl --secure 1 -V

Guest image(s) are now signed, stored on disk, and can be verified.

## New QEMU Command Options for Secure IPL

New parameters have been added to the s390-ccw-virtio machine type to enable Secure IPL and provide certificates for signature verification.

This parameter enables or disables Secure IPL/boot. If not specified, it defaults to off.

	qemu-system-s390x -machine s390-ccw-virtio,secure-boot=on|off

This parameter specifies one or more paths to boot certificates, used for signature verification. You can provide a single certificate file or a directory.

	qemu-system-s390x -machine s390-ccw-virtio, \
                                   boot-certs.0.path=/.../qemu/certs, \
                                   boot-certs.1.path=/another/path/cert.pem

Example:

	qemu-system-s390x -machine s390-ccw-virtio,
	                           secure-boot=on, \
	                           boot-certs.0.path=/.../qemu/certs, \
                                   boot-certs.1.path=/another/path/cert.pem

Secure IPL command options overview:

If neither the -secure-boot nor the -boot-certs options are specified, the guest will boot in normal mode, and no security checks will be conducted.

If the -secure-boot option is not specified or is set to off, and the -boot-certs option is provided, the guest will boot in audit mode. In this mode, all security checks are performed; however, any errors encountered will not interrupt the boot process.

If the -secure-boot option is set to on and the -boot-certs option is provided, the guest will boot in true secure IPL mode. In this mode, all security checks are performed, and any errors encountered will terminate the boot process.
- If the -boot-certs option is not provided in true secure IPL mode, the boot process will fail for the corresponding device.

## Constraints

- z16 CPU model

- certificates must be in X.509 PEM format

- only support for SCSI scheme of virtio-blk/virtio-scsi devices
- The boot process will terminate if secure boot is enabled without
specifying a boot device.
- If enabling secure boot with multiple boot devices, any
unsupported devices or non-eligible devices will cause the entire boot process terminating early with an error logged to the console.

- attempting to perform secure IPL outside of these constraints will result in a failure.

# DIAGNOSE 508 - KVM IPL Extensions

Signature verification is performed during IPL via DIAG 508. Component address, component length, signature address and signature length are obtained in the BIOS and pass to DIAG 508 subcode 2 to perform signature verification in QEMU. If verification succeeds, DIAG 508 subcode 2 (signature verification) will return the length and index of the certificate in the QemuCertificateStore that was used for verification.

## Data Structures

Diag508SignatureVerificationBlock (SVB) — stores addresses and lengths of the component and signature to be used for signature verification. Upon verification, an index and the length of the certificate used is stored.

------------------------------------------------------------------------

Changelog v3->v4:

cyrpto/x590-utils
- Updated patch descriptions to summarize what each patch introduces.
- Restricted accepted certificate format on the QEMU command line to PEM only.
- Added internal conversion routines to handle PEM-to-DER and
DER-to-PEM as needed.
- Renamed crypto functions using the qcrypto_x509_ prefix.
- Replaced QAPI enums with plain C enums.
- Improved GNUTLS error propagation throughout the crypto API.
- Standardized error returns to -1 (instead of using errno values) for consistency.
- Removed unused helpers: qcrypto_check_x509_cert_fmt() and qcrypto_get_x509_hash_len().
- Added bounds checking before converting GNUTLS enums to internal crypto enums.
- Modified qcrypto_get_x509_cert_key_id() to dynamically allocate the result.
- Fixed a typo in the crypto API documentation.

hw/s390x/ipl: Create certificate store
- Removed max_size check when loading certificate.
- Removed check_path_type() and use the stat() & S_ISXXX checks inline where needed.
- Initialized all g_autofree variables.
- Refactored get_cert_paths()
- Used g_auto(GStrv) and g_autoptr(GPtrArray) for automatic cleanup.
- Renamed misleading variables and dropped unnecessary intermediates.
- Replaced check_path_type() with stat(), and treated failures as fatal.
- Treated empty path components as fatal configuration errors.
- Used GError with g_dir_open() and handled errors properly.
- Removed redundant casts and manual cleanup.
- Treated providing 65 or more certificates as a fatal error.
- Modified S390IPLCertificate
- Changed raw from char * to uint8_t * for API consistency.
- Added cert_der field to calculate certificate data buffer size for
DIAG 320 and format conversion.

s390x/diag
- Handled error propagation from crypto API correctly.
- Added g_autofree to variables to ensure proper memory cleanup.
- Initialized all g_autofree variables.

pc-bios/s390-ccw: Add signature verification for secure IPL in audit mode
- Allocated certificate buffer based on calculated size instead of static MAX_CERT_SIZE.

pc-bios/s390-ccw: Add additional security checks for secure boot
- Refactored to improve readability.
- Handled SCLAB Single Component/No Unsigned Component flags.

docs: Add secure IPL documentation
- Updated documentation.
- Illustrated with gnutls ‘certtool’ instead of ‘openssl’ for consistency with other certificate creation docs.

- Updated cover letter with corresponding changes.

Changelog v2->v3:

- Fixed typos in patches
- Edited and corrected patch description
- Enabled secure IPL feature in TCG
- Split crypto subsystem changes from s390x subsystem changes
- Added API documentation for each helper function
- Removed qcrypto_get_x509_cert_fmt()
- Reworked qcrypto_check_x509_cert_fmt() to return 0 on success and
negative error code on errors
- Rephrased error messages when GNUTLS is not enabled
- Changed dev cycle reference from 9.2 to 10.1

hw/s390x/ipl: Create certificate store
- Passed *cert_buf to g_file_get_contents() directly in cert2buf()
- Returned NULL for early returns
- Added check to only allow maximum of 64 certificates in the certificate store

s390x: Guest support for Certificate Store Facility (CS)
- Renamed “diag320” to “cstore”

s390x/diag: Implement DIAG 320 subcode 1
- Removed QEMU_PACKED from VCStorageSizeBlock
- Removed unnecessary error check from subcode 1 implementation

s390x/diag: Implement DIAG 320 subcode 2
- Removed QEMU_PACKED from VCBlock and VCEngtry
- Reworked diag_320_is_cert_valid() to return 0 on success and negative error code on errors
- Set *key_id_data and *hash_data to NULL after g_free()
- Moved DIAG_320_SUBC_STORE_VC case block implementation to a separate function

s390x/diag: Implement DIAG 508 subcode 1 for signature verification
- Added a reserved field to Diag508CertificateStoreInfo
- Removed QEMU_PACKED from Diag508CertificateStoreInfo and Diag508SignatureVerificationBlock
- Applied g_autofree to svb, svb_comp and svb_sig varaibles
- Moved DIAG_508_SUBC_SIG_VERIF case block implementation to a separate function

pc-bios/s390-ccw: Refactor zipl_load_segment function
- Removed casting when calculating comp_len

pc-bios/s390-ccw: Add signature verification for secure IPL in audit mode
- Used malloc() to allocate certificate buffer instead of statically allocating
- Reworked zipl_secure_print()

s390x: Guest support for Secure-IPL Code Loading Attributes Facility (SCLAF)
- Added check to make sure SIPL is enabled when SCLAF is enabled

docs: Add secure IPL documentation
- Split document into two parts:
- docs/specs/s390x-secure-ipl.rst (developer reference)
- docs/system/s390x/secure-ipl.rst (user guide)

Changelog v1->v2:

- Fixed typos in patches
- Edited cover letter
- Added secure IPL documentation

QEMU Command-Line Interface:
- Moved boot-certificates under the machine-type option for s390x-virtio-ccw
- Moved secure-boot under the machine-type option for s390x-virtio-ccw

hw/s390x/ipl: Create Certificate Store
- Defined internal GNUTLS-related APIs
- Added check to only accept certificates using SHA-256 hashing
- Recalculated data_buf_size to ensure word alignment
- Cleaned up memory allocation
- Refactored functions for clarity

s390x: Guest Support for Certificate Store Facility (CS)
- Updated patch description to clarify:
- Why Secure IPL is not available with Secure Execution
- Why this feature requires S390_FEAT_EXTENDED_LENGTH_SCCB
-Restricted features to z16 due to additional layers requiring z16

s390x/diag: Implement DIAG 320 Subcode 1
- Renamed VerificationCertificate prefix to VC
- Byte-swap written values for endianness correctness

s390x/diag: Implement DIAG 320 Subcode 2
- Edited commit message for clarity
- Defined internal GNUTLS-related APIs
- Renamed data structure variables
- Ensured length fields in VCE are word-aligned
- Handled the VC index 0 case
- General refactoring

s390x/diag: Implement DIAG 508 Subcode 2 for Signature Verification
- Defined subcode from 2 to 1
- Removed unused error codes
- Defined internal GNUTLS-related APIs
- Byte-swap read values

hw/s390x/ipl: Add IPIB Flags to IPL Parameter Block
- Moved DIAG308 flags to a new header file

s390x: Guest Support for Secure-IPL Facility
- Renamed SCLP variable from cbl to fac_ipl

pc-bios/s390-ccw: Add Signature Verification for Secure Boot (Audit Mode)
- Moved Secure IPL-related functions to pc-bios/s390-ccw/secure-ip.c|h
- Refactored code for clarity

Collin L. Walling (2):
s390x/diag: Introduce DIAG 508 for secure IPL operations s390x/diag: Implement DIAG 508 subcode 1 for signature verification

Zhuoying Cai (27):
Add boot-certs to s390-ccw-virtio machine type option crypto/x509-utils: Refactor with GNUTLS fallback crypto/x509-utils: Add helper functions for certificate store hw/s390x/ipl: Create certificate store
s390x/diag: Introduce DIAG 320 for Certificate Store Facility s390x/diag: Refactor address validation check from diag308_parm_check s390x/diag: Implement DIAG 320 subcode 1 crypto/x509-utils: Add helper functions for DIAG 320 subcode 2 s390x/diag: Implement DIAG 320 subcode 2 crypto/x509-utils: Add helper functions for DIAG 508 subcode 1 pc-bios/s390-ccw: Introduce IPL Information Report Block (IIRB) pc-bios/s390-ccw: Define memory for IPLB and convert IPLB to pointers hw/s390x/ipl: Add IPIB flags to IPL Parameter Block hw/s390x/ipl: Set iplb->len to maximum length of IPL Parameter Block
s390x: Guest support for Secure-IPL Facility pc-bios/s390-ccw: Refactor zipl_run()
pc-bios/s390-ccw: Rework zipl_load_segment function pc-bios/s390-ccw: Add signature verification for secure IPL in audit
mode
s390x: Guest support for Secure-IPL Code Loading Attributes Facility

    (SCLAF)

pc-bios/s390-ccw: Add additional security checks for secure boot Add secure-boot to s390-ccw-virtio machine type option hw/s390x/ipl: Set IPIB flags for secure IPL pc-bios/s390-ccw: Handle true secure IPL mode pc-bios/s390-ccw: Handle secure boot with multiple boot devices hw/s390x/ipl: Handle secure boot without specifying a boot device docs/specs: Add secure IPL documentation docs/system/s390x: Add secure IPL documentation

 crypto/meson.build                  |   5 +-
 crypto/x509-utils.c                 | 349 +++++++++++++
 docs/specs/s390x-secure-ipl.rst     | 163 ++++++
 docs/system/s390x/secure-ipl.rst    | 180 +++++++
 hw/s390x/cert-store.c               | 201 ++++++++
 hw/s390x/cert-store.h               |  38 ++
 hw/s390x/ipl.c                      |  61 ++-
 hw/s390x/ipl.h                      |  27 +-
 hw/s390x/meson.build                |   1 +
 hw/s390x/s390-virtio-ccw.c          |  52 ++
 hw/s390x/sclp.c                     |   2 +
 include/crypto/x509-utils.h         | 117 +++++
 include/hw/s390x/ipl/diag308.h      |  34 ++
 include/hw/s390x/ipl/diag320.h      |  91 ++++
 include/hw/s390x/ipl/diag508.h      |  38 ++
 include/hw/s390x/ipl/qipl.h         |   7 +-
 include/hw/s390x/s390-virtio-ccw.h  |   3 +
 include/hw/s390x/sclp.h             |   4 +-
 pc-bios/s390-ccw/Makefile           |   3 +-
 pc-bios/s390-ccw/bootmap.c          | 107 +++-
 pc-bios/s390-ccw/bootmap.h          |  11 +
 pc-bios/s390-ccw/iplb.h             |  96 +++-
 pc-bios/s390-ccw/jump2ipl.c         |   6 +-
 pc-bios/s390-ccw/main.c             | 111 +++-
 pc-bios/s390-ccw/netmain.c          |   8 +-
 pc-bios/s390-ccw/s390-ccw.h         |  19 +
 pc-bios/s390-ccw/sclp.c             |  52 ++
 pc-bios/s390-ccw/sclp.h             |   7 +
 pc-bios/s390-ccw/secure-ipl.c       | 767 ++++++++++++++++++++++++++++
 pc-bios/s390-ccw/secure-ipl.h       | 206 ++++++++
 qapi/machine-s390x.json             |  24 +
 qemu-options.hx                     |  10 +-
 target/s390x/cpu_features.c         |   7 +
 target/s390x/cpu_features.h         |   1 +
 target/s390x/cpu_features_def.h.inc |   5 +
 target/s390x/cpu_models.c           |   7 +
 target/s390x/diag.c                 | 523 ++++++++++++++++++-
 target/s390x/gen-features.c         |   7 +
 target/s390x/kvm/kvm.c              |  34 ++
 target/s390x/s390x-internal.h       |   4 +
 target/s390x/tcg/misc_helper.c      |  14 +
 41 files changed, 3329 insertions(+), 73 deletions(-)
 create mode 100644 docs/specs/s390x-secure-ipl.rst
 create mode 100644 docs/system/s390x/secure-ipl.rst
 create mode 100644 hw/s390x/cert-store.c
 create mode 100644 hw/s390x/cert-store.h
 create mode 100644 include/hw/s390x/ipl/diag308.h
 create mode 100644 include/hw/s390x/ipl/diag320.h
 create mode 100644 include/hw/s390x/ipl/diag508.h
 create mode 100644 pc-bios/s390-ccw/secure-ipl.c
 create mode 100644 pc-bios/s390-ccw/secure-ipl.h
Signature · 1 line
2.50.1
#1 lore raw

PATCH v5 1/29 Add boot-certs to s390-ccw-virtio machine type option

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +20 -0
new file mode 100644
index 0000000000..9b3fd25cc4
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
hw/s390x/s390-virtio-ccw.c +30 -0
index c294106a74..9ac425c695 100644
@@ -45,6 +45,7 @@
 #include "target/s390x/kvm/pv.h"
 #include "migration/blocker.h"
 #include "qapi/visitor.h"
+#include "qapi/qapi-visit-machine-s390x.h"
 #include "hw/s390x/cpu-topology.h"
 #include "kvm/kvm_s390x.h"
 #include "hw/virtio/virtio-md-pci.h"
@@ -798,6 +799,30 @@ static void machine_set_loadparm(Object *obj, Visitor *v,
     g_free(val);
 }
 
+static void machine_get_boot_certs(Object *obj, Visitor *v,
+                                   const char *name, void *opaque,
+                                   Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList **certs = &ms->boot_certs;
+
+    visit_type_BootCertPathList(v, name, certs, errp);
+}
+
+static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList *cert_list = NULL;
+
+    visit_type_BootCertPathList(v, name, &cert_list, errp);
+    if (!cert_list) {
+        return;
+    }
+
+    ms->boot_certs = cert_list;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);
@@ -851,6 +876,11 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
             "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"
             " to upper case) to pass to machine loader, boot manager,"
             " and guest kernel");
+
+    object_class_property_add(oc, "boot-certs", "BootCertPath",
+                              machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
+    object_class_property_set_description(oc, "boot-certs",
+            "provide paths to a directory and/or a certificate file for secure boot");
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +2 -0
index 526078a4e2..b90949355c 100644
@@ -14,6 +14,7 @@
 #include "hw/boards.h"
 #include "qom/object.h"
 #include "hw/s390x/sclp.h"
+#include "qapi/qapi-types-machine-s390x.h"
 
 #define TYPE_S390_CCW_MACHINE               "s390-ccw-machine"
 
@@ -31,6 +32,7 @@ struct S390CcwMachineState {
     uint8_t loadparm[8];
     uint64_t memory_limit;
     uint64_t max_pagesize;
+    BootCertPathList *boot_certs;
 
     SCLPDevice *sclp;
 };
qapi/machine-s390x.json +24 -0
index 966dbd61d2..3e89ef8320 100644
@@ -119,3 +119,27 @@
 { 'command': 'query-s390x-cpu-polarization', 'returns': 'CpuPolarizationInfo',
   'features': [ 'unstable' ]
 }
+
+##
+# @BootCertPath:
+#
+# Boot certificate path.
+#
+# @path: path of certificate(s)
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCertPath',
+  'data': {'path': 'str'} }
+
+##
+# @BootCerts:
+#
+# List of boot certificate paths.
+#
+# @boot-certs: List of BootCertPath
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCerts',
+  'data': {'boot-certs': ['BootCertPath'] } }
qemu-options.hx +5 -1
index ab23f14d21..ac497eb3a0 100644
@@ -44,7 +44,8 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \
 #endif
     "                memory-backend='backend-id' specifies explicitly provided backend for main RAM (default=none)\n"
     "                cxl-fmw.0.targets.0=firsttarget,cxl-fmw.0.targets.1=secondtarget,cxl-fmw.0.size=size[,cxl-fmw.0.interleave-granularity=granularity]\n"
-    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n",
+    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n"
+    "                boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file provides paths to a directory and/or a certificate file\n",
     QEMU_ARCH_ALL)
 SRST
 ``-machine [type=]name[,prop=value[,...]]``
@@ -205,6 +206,9 @@ SRST
         ::
 
             -machine smp-cache.0.cache=l1d,smp-cache.0.topology=core,smp-cache.1.cache=l1i,smp-cache.1.topology=core
+
+    ``boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file``
+        Provide paths to a directory and/or a certificate file on the host [s390x only].
 ERST
 
 DEF("M", HAS_ARG, QEMU_OPTION_M,
Signature · 1 line
2.50.1
#2 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 50 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
hw/s390x/s390-virtio-ccw.c +25 -0
index c294106a74..9ac425c695 100644
@@ -45,6 +45,7 @@
 #include "target/s390x/kvm/pv.h"
 #include "migration/blocker.h"
 #include "qapi/visitor.h"
+#include "qapi/qapi-visit-machine-s390x.h"
 #include "hw/s390x/cpu-topology.h"
 #include "kvm/kvm_s390x.h"
 #include "hw/virtio/virtio-md-pci.h"
@@ -798,6 +799,30 @@ static void machine_set_loadparm(Object *obj, Visitor *v,
     g_free(val);
 }
 
+static void machine_get_boot_certs(Object *obj, Visitor *v,
+                                   const char *name, void *opaque,
+                                   Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList **certs = &ms->boot_certs;
+
+    visit_type_BootCertPathList(v, name, certs, errp);
+}
+
+static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList *cert_list = NULL;
+
+    visit_type_BootCertPathList(v, name, &cert_list, errp);
+    if (!cert_list) {
+        return;
+    }
+
+    ms->boot_certs = cert_list;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);

hw/s390x/s390-virtio-ccw.c static void ccw_machine_class_init(ObjectClass *oc, const void *data) · line 880

Quoted 5 lines
hw/s390x/s390-virtio-ccw.c +2 -0
@@ -851,6 +876,11 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
             "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"
             " to upper case) to pass to machine loader, boot manager,"
             " and guest kernel");
+
+    object_class_property_add(oc, "boot-certs", "BootCertPath",

Isn't this a BootCertPathList, not a BootCertPath?

Quoted 34 lines
hw/s390x/s390-virtio-ccw.c +3 -0
+                              machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
+    object_class_property_set_description(oc, "boot-certs",
+            "provide paths to a directory and/or a certificate file for secure boot");
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +2 -0
index 526078a4e2..b90949355c 100644
@@ -14,6 +14,7 @@
 #include "hw/boards.h"
 #include "qom/object.h"
 #include "hw/s390x/sclp.h"
+#include "qapi/qapi-types-machine-s390x.h"
 
 #define TYPE_S390_CCW_MACHINE               "s390-ccw-machine"
 
@@ -31,6 +32,7 @@ struct S390CcwMachineState {
     uint8_t loadparm[8];
     uint64_t memory_limit;
     uint64_t max_pagesize;
+    BootCertPathList *boot_certs;
 
     SCLPDevice *sclp;
 };
qapi/machine-s390x.json +0 -0
index 966dbd61d2..3e89ef8320 100644
@@ -119,3 +119,27 @@
 { 'command': 'query-s390x-cpu-polarization', 'returns': 'CpuPolarizationInfo',
   'features': [ 'unstable' ]
 }

qapi/machine-s390x.json line 131

Quoted 10 lines
qapi/machine-s390x.json +10 -0
+
+##
+# @BootCertPath:
+#
+# Boot certificate path.
+#
+# @path: path of certificate(s)
+#
+# Since: 10.1
+##

No mention of file vs. directory.

Why do you wrap the file name in a struct? One possible reason is providing for future extensions. Can you think of any?

If you extend it, the name BootCertPath could become suboptimal. BootCertificate?

qapi/machine-s390x.json line 140

Quoted 9 lines
qapi/machine-s390x.json +9 -0
+{ 'struct': 'BootCertPath',
+  'data': {'path': 'str'} }
+
+##
+# @BootCerts:
+#
+# List of boot certificate paths.
+#
+# @boot-certs: List of BootCertPath

Anti-pattern: the description text restates the type.

qapi/machine-s390x.json line 145

Quoted 5 lines
qapi/machine-s390x.json +5 -0
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCerts',
+  'data': {'boot-certs': ['BootCertPath'] } }

Where is this type used?

Quoted 24 lines
qemu-options.hx +5 -1
index ab23f14d21..ac497eb3a0 100644
@@ -44,7 +44,8 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \
 #endif
     "                memory-backend='backend-id' specifies explicitly provided backend for main RAM (default=none)\n"
     "                cxl-fmw.0.targets.0=firsttarget,cxl-fmw.0.targets.1=secondtarget,cxl-fmw.0.size=size[,cxl-fmw.0.interleave-granularity=granularity]\n"
-    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n",
+    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n"
+    "                boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file provides paths to a directory and/or a certificate file\n",
     QEMU_ARCH_ALL)
 SRST
 ``-machine [type=]name[,prop=value[,...]]``
@@ -205,6 +206,9 @@ SRST
         ::
 
             -machine smp-cache.0.cache=l1d,smp-cache.0.topology=core,smp-cache.1.cache=l1i,smp-cache.1.topology=core
+
+    ``boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file``
+        Provide paths to a directory and/or a certificate file on the host [s390x only].
 ERST
 
 DEF("M", HAS_ARG, QEMU_OPTION_M,
#3 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 10 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

Quoted 49 lines
Quoted 49 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
hw/s390x/s390-virtio-ccw.c +25 -0
index c294106a74..9ac425c695 100644
@@ -45,6 +45,7 @@
 #include "target/s390x/kvm/pv.h"
 #include "migration/blocker.h"
 #include "qapi/visitor.h"
+#include "qapi/qapi-visit-machine-s390x.h"
 #include "hw/s390x/cpu-topology.h"
 #include "kvm/kvm_s390x.h"
 #include "hw/virtio/virtio-md-pci.h"
@@ -798,6 +799,30 @@ static void machine_set_loadparm(Object *obj, Visitor *v,
     g_free(val);
 }
 
+static void machine_get_boot_certs(Object *obj, Visitor *v,
+                                   const char *name, void *opaque,
+                                   Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList **certs = &ms->boot_certs;
+
+    visit_type_BootCertPathList(v, name, certs, errp);
+}
+
+static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList *cert_list = NULL;
+
+    visit_type_BootCertPathList(v, name, &cert_list, errp);
+    if (!cert_list) {
+        return;
+    }
+
+    ms->boot_certs = cert_list;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);
Quoted 9 lines

hw/s390x/s390-virtio-ccw.c static void ccw_machine_class_init(ObjectClass *oc, const void *data) · line 880

Quoted 6 lines
hw/s390x/s390-virtio-ccw.c +2 -0
@@ -851,6 +876,11 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
             "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"
             " to upper case) to pass to machine loader, boot manager,"
             " and guest kernel");
+
+    object_class_property_add(oc, "boot-certs", "BootCertPath",

Isn't this a BootCertPathList, not a BootCertPath?

If I understand correctly, would BootCerts also be the correct option to use here?

Quoted 47 lines
Quoted 34 lines
hw/s390x/s390-virtio-ccw.c +3 -0
+                              machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
+    object_class_property_set_description(oc, "boot-certs",
+            "provide paths to a directory and/or a certificate file for secure boot");
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +2 -0
index 526078a4e2..b90949355c 100644
@@ -14,6 +14,7 @@
 #include "hw/boards.h"
 #include "qom/object.h"
 #include "hw/s390x/sclp.h"
+#include "qapi/qapi-types-machine-s390x.h"
 
 #define TYPE_S390_CCW_MACHINE               "s390-ccw-machine"
 
@@ -31,6 +32,7 @@ struct S390CcwMachineState {
     uint8_t loadparm[8];
     uint64_t memory_limit;
     uint64_t max_pagesize;
+    BootCertPathList *boot_certs;
 
     SCLPDevice *sclp;
 };
qapi/machine-s390x.json +0 -0
index 966dbd61d2..3e89ef8320 100644
@@ -119,3 +119,27 @@
 { 'command': 'query-s390x-cpu-polarization', 'returns': 'CpuPolarizationInfo',
   'features': [ 'unstable' ]
 }

qapi/machine-s390x.json line 131

Quoted 10 lines
qapi/machine-s390x.json +10 -0
+
+##
+# @BootCertPath:
+#
+# Boot certificate path.
+#
+# @path: path of certificate(s)
+#
+# Since: 10.1
+##

No mention of file vs. directory.

Quoted 6 lines

Why do you wrap the file name in a struct? One possible reason is providing for future extensions. Can you think of any?

If you extend it, the name BootCertPath could become suboptimal. BootCertificate?

I wrapped the path in a struct to follow the array-style structure used by cxl-fmw and smp-cache options (as Daniel suggested).

```
  It would be something like this on the CLI:


boot-certs.0.path=/path/to/dir,boot-certs.1.path=/to/other/dir,boot-certs.2.path=/some/...
```

This could potentially leave room for future extensions, such as including details about the certificate (e.g., issuer, hashing algorithm, etc).

Quoted 12 lines

qapi/machine-s390x.json line 140

Quoted 9 lines
qapi/machine-s390x.json +9 -0
+{ 'struct': 'BootCertPath',
+  'data': {'path': 'str'} }
+
+##
+# @BootCerts:
+#
+# List of boot certificate paths.
+#
+# @boot-certs: List of BootCertPath

Anti-pattern: the description text restates the type.

Quoted 8 lines

qapi/machine-s390x.json line 145

Quoted 5 lines
qapi/machine-s390x.json +5 -0
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCerts',
+  'data': {'boot-certs': ['BootCertPath'] } }

Where is this type used?

Please correct me if I'm wrong, but from what I've seen, it is not used directly in the implementation. It provides a list property for BootCertPath, which makes the BootCertPathList definition valid and able to accept multiple paths. If BootCerts is removed, then BootCertPathList becomes underfined and results in compilation errors.

Quoted 25 lines
Quoted 24 lines
qemu-options.hx +5 -1
index ab23f14d21..ac497eb3a0 100644
@@ -44,7 +44,8 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \
 #endif
     "                memory-backend='backend-id' specifies explicitly provided backend for main RAM (default=none)\n"
     "                cxl-fmw.0.targets.0=firsttarget,cxl-fmw.0.targets.1=secondtarget,cxl-fmw.0.size=size[,cxl-fmw.0.interleave-granularity=granularity]\n"
-    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n",
+    "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n"
+    "                boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file provides paths to a directory and/or a certificate file\n",
     QEMU_ARCH_ALL)
 SRST
 ``-machine [type=]name[,prop=value[,...]]``
@@ -205,6 +206,9 @@ SRST
         ::
 
             -machine smp-cache.0.cache=l1d,smp-cache.0.topology=core,smp-cache.1.cache=l1i,smp-cache.1.topology=core
+
+    ``boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file``
+        Provide paths to a directory and/or a certificate file on the host [s390x only].
 ERST
 
 DEF("M", HAS_ARG, QEMU_OPTION_M,
#4 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 56 lines · Zhuoying Cai

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 9 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 2 lines

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

I figure when @path names a file, it's an error when the file doesn't contain a valid cetificate.

What is @path names a directory, and one of the directory's files doesn't contain a valid certificate?

Can a single file contain multiple certificates?

Quoted 58 lines
Quoted 49 lines
Quoted 49 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
hw/s390x/s390-virtio-ccw.c +25 -0
index c294106a74..9ac425c695 100644
@@ -45,6 +45,7 @@
 #include "target/s390x/kvm/pv.h"
 #include "migration/blocker.h"
 #include "qapi/visitor.h"
+#include "qapi/qapi-visit-machine-s390x.h"
 #include "hw/s390x/cpu-topology.h"
 #include "kvm/kvm_s390x.h"
 #include "hw/virtio/virtio-md-pci.h"
@@ -798,6 +799,30 @@ static void machine_set_loadparm(Object *obj, Visitor *v,
     g_free(val);
 }
 
+static void machine_get_boot_certs(Object *obj, Visitor *v,
+                                   const char *name, void *opaque,
+                                   Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList **certs = &ms->boot_certs;
+
+    visit_type_BootCertPathList(v, name, certs, errp);
+}
+
+static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList *cert_list = NULL;
+
+    visit_type_BootCertPathList(v, name, &cert_list, errp);
+    if (!cert_list) {
+        return;
+    }
+
+    ms->boot_certs = cert_list;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);
Quoted 8 lines

hw/s390x/s390-virtio-ccw.c static void ccw_machine_class_init(ObjectClass *oc, const void *data) · line 880

Quoted 6 lines
hw/s390x/s390-virtio-ccw.c +2 -0
@@ -851,6 +876,11 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
             "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"
             " to upper case) to pass to machine loader, boot manager,"
             " and guest kernel");
+
+    object_class_property_add(oc, "boot-certs", "BootCertPath",

Isn't this a BootCertPathList, not a BootCertPath?

Quoted 2 lines

If I understand correctly, would BootCerts also be the correct option to use here?

This is object_class_property_add()'s @type argument. It's an arbitrary string, not checked in any way. When the property's actual type is a QAPI type, like it is here, then the @type argument should be the name of the QAPI type.

Questions?

Quoted 64 lines
Quoted 47 lines
Quoted 34 lines
hw/s390x/s390-virtio-ccw.c +3 -0
+                              machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
+    object_class_property_set_description(oc, "boot-certs",
+            "provide paths to a directory and/or a certificate file for secure boot");
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +2 -0
index 526078a4e2..b90949355c 100644
@@ -14,6 +14,7 @@
 #include "hw/boards.h"
 #include "qom/object.h"
 #include "hw/s390x/sclp.h"
+#include "qapi/qapi-types-machine-s390x.h"
 
 #define TYPE_S390_CCW_MACHINE               "s390-ccw-machine"
 
@@ -31,6 +32,7 @@ struct S390CcwMachineState {
     uint8_t loadparm[8];
     uint64_t memory_limit;
     uint64_t max_pagesize;
+    BootCertPathList *boot_certs;
 
     SCLPDevice *sclp;
 };
qapi/machine-s390x.json +0 -0
index 966dbd61d2..3e89ef8320 100644
@@ -119,3 +119,27 @@
 { 'command': 'query-s390x-cpu-polarization', 'returns': 'CpuPolarizationInfo',
   'features': [ 'unstable' ]
 }

qapi/machine-s390x.json line 131

Quoted 10 lines
qapi/machine-s390x.json +10 -0
+
+##
+# @BootCertPath:
+#
+# Boot certificate path.
+#
+# @path: path of certificate(s)
+#
+# Since: 10.1
+##

No mention of file vs. directory.

Quoted 6 lines

Why do you wrap the file name in a struct? One possible reason is providing for future extensions. Can you think of any?

If you extend it, the name BootCertPath could become suboptimal. BootCertificate?

I wrapped the path in a struct to follow the array-style structure used by cxl-fmw and smp-cache options (as Daniel suggested).

```
  It would be something like this on the CLI:


boot-certs.0.path=/path/to/dir,boot-certs.1.path=/to/other/dir,boot-certs.2.path=/some/...
```
Quoted 3 lines

This could potentially leave room for future extensions, such as including details about the certificate (e.g., issuer, hashing algorithm, etc).

No objections to the wrapping. I'd prefer naming the struct BootCertificates.

Quoted 20 lines
Quoted 12 lines

qapi/machine-s390x.json line 140

Quoted 9 lines
qapi/machine-s390x.json +9 -0
+{ 'struct': 'BootCertPath',
+  'data': {'path': 'str'} }
+
+##
+# @BootCerts:
+#
+# List of boot certificate paths.
+#
+# @boot-certs: List of BootCertPath

Anti-pattern: the description text restates the type.

Quoted 7 lines

qapi/machine-s390x.json line 145

Quoted 5 lines
qapi/machine-s390x.json +5 -0
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCerts',
+  'data': {'boot-certs': ['BootCertPath'] } }

Where is this type used?

Quoted 5 lines

Please correct me if I'm wrong, but from what I've seen, it is not used directly in the implementation. It provides a list property for BootCertPath, which makes the BootCertPathList definition valid and able to accept multiple paths. If BootCerts is removed, then BootCertPathList becomes underfined and results in compilation errors.

Aha!

Your QOM property setter and getter need visit_type_BootCertPathList().

The QAPI generator generates code for BootCertPathList, including visit_type_BootCertPathList(), only when it knows it's actually used. It can only see uses within the QAPI schema. So, when ['BootCertPath'] doesn't occur there, visit_type_BootCertPathList() won't exist, and your QOM code won't compile.

Since you don't actually need BootCertPathList in the schema, you need to add an artifical use just to get it generated. The common way to do that is using it in a dummy type like this:

    ##
    # @DummyForceS390Arrays:
    #
    # Not used by QMP; hack to let us use BootCertPathList internally
    #
    # Since: 10.2
    ##
    { 'struct': 'DummyForceArrays',
      'data': { 'unused': ['BootCertPath'] } }

You also need to add it to pragme documentation-exceptions is pragma.json.

Yes, this is clunky. Sorry :)

[...]

#5 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 61 lines · Markus Armbruster
Quoted 56 lines · Zhuoying Cai

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 9 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 2 lines

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

Quoted 8 lines

I figure when @path names a file, it's an error when the file doesn't contain a valid cetificate.

What is @path names a directory, and one of the directory's files doesn't contain a valid certificate?

Can a single file contain multiple certificates?

A certificate file path is expected to contain exactly one certificate.

Certificates provided through the CLI, whether as individual files or within a directory, are validated before use. If a certificate is invalid (e.g., unsupported format), it will be skipped and not added to the S390 certificate store.

When iterating through the provided paths, the program will terminate on fatal configuration errors, such as when a specified path is neither a file nor a directory.

Quoted 132 lines
Quoted 58 lines
Quoted 49 lines
Quoted 49 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
hw/s390x/s390-virtio-ccw.c +25 -0
index c294106a74..9ac425c695 100644
@@ -45,6 +45,7 @@
 #include "target/s390x/kvm/pv.h"
 #include "migration/blocker.h"
 #include "qapi/visitor.h"
+#include "qapi/qapi-visit-machine-s390x.h"
 #include "hw/s390x/cpu-topology.h"
 #include "kvm/kvm_s390x.h"
 #include "hw/virtio/virtio-md-pci.h"
@@ -798,6 +799,30 @@ static void machine_set_loadparm(Object *obj, Visitor *v,
     g_free(val);
 }
 
+static void machine_get_boot_certs(Object *obj, Visitor *v,
+                                   const char *name, void *opaque,
+                                   Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList **certs = &ms->boot_certs;
+
+    visit_type_BootCertPathList(v, name, certs, errp);
+}
+
+static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
+                                   void *opaque, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+    BootCertPathList *cert_list = NULL;
+
+    visit_type_BootCertPathList(v, name, &cert_list, errp);
+    if (!cert_list) {
+        return;
+    }
+
+    ms->boot_certs = cert_list;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);
Quoted 8 lines

hw/s390x/s390-virtio-ccw.c static void ccw_machine_class_init(ObjectClass *oc, const void *data) · line 880

Quoted 6 lines
hw/s390x/s390-virtio-ccw.c +2 -0
@@ -851,6 +876,11 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
             "Up to 8 chars in set of [A-Za-z0-9. ] (lower case chars converted"
             " to upper case) to pass to machine loader, boot manager,"
             " and guest kernel");
+
+    object_class_property_add(oc, "boot-certs", "BootCertPath",

Isn't this a BootCertPathList, not a BootCertPath?

Quoted 2 lines

If I understand correctly, would BootCerts also be the correct option to use here?

This is object_class_property_add()'s @type argument. It's an arbitrary string, not checked in any way. When the property's actual type is a QAPI type, like it is here, then the @type argument should be the name of the QAPI type.

Questions?

Quoted 64 lines
Quoted 47 lines
Quoted 34 lines
hw/s390x/s390-virtio-ccw.c +3 -0
+                              machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
+    object_class_property_set_description(oc, "boot-certs",
+            "provide paths to a directory and/or a certificate file for secure boot");
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +2 -0
index 526078a4e2..b90949355c 100644
@@ -14,6 +14,7 @@
 #include "hw/boards.h"
 #include "qom/object.h"
 #include "hw/s390x/sclp.h"
+#include "qapi/qapi-types-machine-s390x.h"
 
 #define TYPE_S390_CCW_MACHINE               "s390-ccw-machine"
 
@@ -31,6 +32,7 @@ struct S390CcwMachineState {
     uint8_t loadparm[8];
     uint64_t memory_limit;
     uint64_t max_pagesize;
+    BootCertPathList *boot_certs;
 
     SCLPDevice *sclp;
 };
qapi/machine-s390x.json +0 -0
index 966dbd61d2..3e89ef8320 100644
@@ -119,3 +119,27 @@
 { 'command': 'query-s390x-cpu-polarization', 'returns': 'CpuPolarizationInfo',
   'features': [ 'unstable' ]
 }

qapi/machine-s390x.json line 131

Quoted 10 lines
qapi/machine-s390x.json +10 -0
+
+##
+# @BootCertPath:
+#
+# Boot certificate path.
+#
+# @path: path of certificate(s)
+#
+# Since: 10.1
+##

No mention of file vs. directory.

Quoted 6 lines

Why do you wrap the file name in a struct? One possible reason is providing for future extensions. Can you think of any?

If you extend it, the name BootCertPath could become suboptimal. BootCertificate?

I wrapped the path in a struct to follow the array-style structure used by cxl-fmw and smp-cache options (as Daniel suggested).

```
  It would be something like this on the CLI:


boot-certs.0.path=/path/to/dir,boot-certs.1.path=/to/other/dir,boot-certs.2.path=/some/...
```
Quoted 7 lines
Quoted 3 lines

This could potentially leave room for future extensions, such as including details about the certificate (e.g., issuer, hashing algorithm, etc).

No objections to the wrapping. I'd prefer naming the struct BootCertificates.

I'll update this in the next version.

Quoted 50 lines
Quoted 20 lines
Quoted 12 lines

qapi/machine-s390x.json line 140

Quoted 9 lines
qapi/machine-s390x.json +9 -0
+{ 'struct': 'BootCertPath',
+  'data': {'path': 'str'} }
+
+##
+# @BootCerts:
+#
+# List of boot certificate paths.
+#
+# @boot-certs: List of BootCertPath

Anti-pattern: the description text restates the type.

Quoted 7 lines

qapi/machine-s390x.json line 145

Quoted 5 lines
qapi/machine-s390x.json +5 -0
+#
+# Since: 10.1
+##
+{ 'struct': 'BootCerts',
+  'data': {'boot-certs': ['BootCertPath'] } }

Where is this type used?

Quoted 5 lines

Please correct me if I'm wrong, but from what I've seen, it is not used directly in the implementation. It provides a list property for BootCertPath, which makes the BootCertPathList definition valid and able to accept multiple paths. If BootCerts is removed, then BootCertPathList becomes underfined and results in compilation errors.

Aha!

Your QOM property setter and getter need visit_type_BootCertPathList().

The QAPI generator generates code for BootCertPathList, including visit_type_BootCertPathList(), only when it knows it's actually used. It can only see uses within the QAPI schema. So, when ['BootCertPath'] doesn't occur there, visit_type_BootCertPathList() won't exist, and your QOM code won't compile.

Since you don't actually need BootCertPathList in the schema, you need to add an artifical use just to get it generated. The common way to do that is using it in a dummy type like this:

    ##
    # @DummyForceS390Arrays:
    #
    # Not used by QMP; hack to let us use BootCertPathList internally
    #
    # Since: 10.2
    ##
    { 'struct': 'DummyForceArrays',
      'data': { 'unused': ['BootCertPath'] } }
Quoted 5 lines

You also need to add it to pragme documentation-exceptions is pragma.json.

Yes, this is clunky. Sorry :)

Thanks for all the explanations! I'll make the changes in the next version.

Quoted 2 lines

[...]

#6 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 68 lines · Zhuoying Cai
Quoted 67 lines · Markus Armbruster
Quoted 56 lines · Zhuoying Cai

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 9 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 2 lines

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

I figure when @path names a file, it's an error when the file doesn't contain a valid cetificate.

What is @path names a directory, and one of the directory's files doesn't contain a valid certificate?

Quoted 8 lines
Quoted 1 line

Can a single file contain multiple certificates?

A certificate file path is expected to contain exactly one certificate.

Certificates provided through the CLI, whether as individual files or within a directory, are validated before use. If a certificate is invalid (e.g., unsupported format), it will be skipped and not added to the S390 certificate store.

Hmm. What exactly happens when I configure a certificate file like

    -machine s390-ccw-virtio,boot-certs.0.path=/dev/null

or some other file that doesn't contain a valud certificate? Is it silently ignored, or is it an error?

Quoted 3 lines

When iterating through the provided paths, the program will terminate on fatal configuration errors, such as when a specified path is neither a file nor a directory.

[...]

#7 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 79 lines · Markus Armbruster
Quoted 68 lines · Zhuoying Cai
Quoted 67 lines · Markus Armbruster
Quoted 56 lines · Zhuoying Cai

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 9 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 2 lines

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

I figure when @path names a file, it's an error when the file doesn't contain a valid cetificate.

What is @path names a directory, and one of the directory's files doesn't contain a valid certificate?

Quoted 8 lines
Quoted 1 line

Can a single file contain multiple certificates?

A certificate file path is expected to contain exactly one certificate.

Certificates provided through the CLI, whether as individual files or within a directory, are validated before use. If a certificate is invalid (e.g., unsupported format), it will be skipped and not added to the S390 certificate store.

Quoted 11 lines

Hmm. What exactly happens when I configure a certificate file like

    -machine s390-ccw-virtio,boot-certs.0.path=/dev/null

or some other file that doesn't contain a valud certificate? Is it silently ignored, or is it an error?

Quoted 3 lines

When iterating through the provided paths, the program will terminate on fatal configuration errors, such as when a specified path is neither a file nor a directory.

If /dev/null is provided, the program will report an error and terminates.

qemu-system-s390x: Path '/dev/null' is neither a file nor a directory

If a file exists but doesn't contain a valid certificate, the program will report the error but continues validating other remaining certificates. For example, providing a certificate in DER format (cert.pem) is not supported; only PEM format certificates are accepted:

   -machine s390-ccw-virtio,boot-certs.0.path=/root/cert.pem, \
                            boot-certs.1.path=/root/pem-test/rsa.pem, \
                            boot-certs.2.path=/root/pem-test/rsa-oaep.pem

qemu-system-s390x: Failed to initialize certificate: /root/cert.pem:
Failed to import certificate: Base64 unexpected header error. Using virtio-blk.
SCSI boot device supports secure boot.
LOADPARM=[ ]

Using virtio-blk.
Using SCSI scheme.
....Verified component
...Verified component
...

In summary, QEMU first collects a list of .pem files from the CLI, and then validate each certificate in that list.

More specifically, QEMU first checks and normalizes the certificate paths - each path must be a non-empty string, must exist, and must be either a regular file or a directory. An invalid path will be reported and cause the program to terminate. Regular files with a .pem suffix, as well as .pem files inside directories, are added to the list.

Once the list is built, QEMU attempts to read and parse each certificate. Errors at this stage (such as an invalid certificate format) are reported, but the program continues validating the rest of certificate in the list.

(Further implementation details are provided in [PATCH v5 04/29] hw/s390x/ipl: Create certificate store.)

Quoted 2 lines

[...]

#8 lore raw

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Quoted 117 lines · Zhuoying Cai
Quoted 79 lines · Markus Armbruster
Quoted 68 lines · Zhuoying Cai
Quoted 67 lines · Markus Armbruster
Quoted 56 lines · Zhuoying Cai

Thanks for the feedback.

Quoted 43 lines · Markus Armbruster
Quoted 28 lines · Zhuoying Cai

Introduce a new boot-certs machine type option for the s390-ccw-virtio machine. This allows users to specify one or more certificate file paths or directories to be used during secure boot.

Each entry is specified using the syntax:
boot-certs.<index>.path=/path/to/cert.pem

Multiple paths can be specify using array properties:

	boot-certs.0.path=/path/to/cert.pem,
	boot-certs.1.path=/path/to/cert-dir,
	boot-certs.2.path=/path/to/another-dir...
---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++++++
 hw/s390x/s390-virtio-ccw.c         | 30 ++++++++++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  2 ++
 qapi/machine-s390x.json            | 24 ++++++++++++++++++++++++
 qemu-options.hx                    |  6 +++++-
 5 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 docs/system/s390x/secure-ipl.rst
docs/system/s390x/secure-ipl.rst new file +0 -0
new file mode 100644
index 0000000000..9b3fd25cc4

docs/system/s390x/secure-ipl.rst line 8

Quoted 8 lines
docs/system/s390x/secure-ipl.rst new file +8 -0
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Secure IPL Command Line Options
+===============================
+
+New parameters have been introduced to s390-ccw-virtio machine type option
+to support secure IPL. These parameters allow users to provide certificates
+and enable secure IPL directly via the command line.

All too soon these parameters will no longer be new. Consider something like "The s390-ccw-virtio machine type supports secure TPL. To enable it, you need to provide certificates."

Quoted 9 lines

docs/system/s390x/secure-ipl.rst line 14

Quoted 6 lines
docs/system/s390x/secure-ipl.rst new file +6 -0
+
+Providing Certificates
+----------------------
+
+The certificate store can be populated by supplying a list of certificate file
+paths or directories on the command-line:

File is clear enough (use the certificate found in the file). What does directory do?

Quoted 2 lines

A directory contains a list of certificate files, and allowing both files and directories could make the CLI more flexible.

I figure when @path names a file, it's an error when the file doesn't contain a valid cetificate.

What is @path names a directory, and one of the directory's files doesn't contain a valid certificate?

Quoted 8 lines
Quoted 1 line

Can a single file contain multiple certificates?

A certificate file path is expected to contain exactly one certificate.

Certificates provided through the CLI, whether as individual files or within a directory, are validated before use. If a certificate is invalid (e.g., unsupported format), it will be skipped and not added to the S390 certificate store.

Quoted 11 lines

Hmm. What exactly happens when I configure a certificate file like

    -machine s390-ccw-virtio,boot-certs.0.path=/dev/null

or some other file that doesn't contain a valud certificate? Is it silently ignored, or is it an error?

Quoted 3 lines

When iterating through the provided paths, the program will terminate on fatal configuration errors, such as when a specified path is neither a file nor a directory.

If /dev/null is provided, the program will report an error and terminates.

qemu-system-s390x: Path '/dev/null' is neither a file nor a directory

If a file exists but doesn't contain a valid certificate, the program will report the error but continues validating other remaining certificates. For example, providing a certificate in DER format (cert.pem) is not supported; only PEM format certificates are accepted:

   -machine s390-ccw-virtio,boot-certs.0.path=/root/cert.pem, \
                            boot-certs.1.path=/root/pem-test/rsa.pem, \
                            boot-certs.2.path=/root/pem-test/rsa-oaep.pem
   qemu-system-s390x: Failed to initialize certificate: /root/cert.pem:

Failed to import certificate: Base64 unexpected header error. Using virtio-blk.
SCSI boot device supports secure boot.
LOADPARM=[ ]

Using virtio-blk.
Using SCSI scheme.
....Verified component
...Verified component
...

Quoted 8 lines

In summary, QEMU first collects a list of .pem files from the CLI, and then validate each certificate in that list.

More specifically, QEMU first checks and normalizes the certificate paths - each path must be a non-empty string, must exist, and must be either a regular file or a directory. An invalid path will be reported and cause the program to terminate. Regular files with a .pem suffix, as well as .pem files inside directories, are added to the list.

IMHO we should be a bit more strict than this

* If pointing to a file - loading must succeed; errors must be fatal
* If pointing to a dir - the dir must exist, any file NOT ending in .pem should be ignored, any file ending in .pem must succeed, errors must be fatal
* If pointing to neither a file, nor dir - must be fatal

ie we should be assuming that the configuration is expected to work, and thus errors when loading are liable to be admin config mistakes that should be fatal.

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

Re: [PATCH v5 01/29] Add boot-certs to s390-ccw-virtio machine type option

Daniel P. Berrangé <[email protected]> writes:

[...]

Quoted 11 lines

IMHO we should be a bit more strict than this

* If pointing to a file - loading must succeed; errors must be fatal
* If pointing to a dir - the dir must exist, any file NOT ending in .pem should be ignored, any file ending in .pem must succeed, errors must be fatal
* If pointing to neither a file, nor dir - must be fatal

ie we should be assuming that the configuration is expected to work, and thus errors when loading are liable to be admin config mistakes that should be fatal.

Seconded. Thanks!

#10 lore raw

PATCH v5 2/29 crypto/x509-utils: Refactor with GNUTLS fallback

In reply to Zhuoying Cai

Always compile x509-utils.c and add a fallback when GNUTLS is unavailable.

---
 crypto/meson.build  |  5 +----
 crypto/x509-utils.c | 16 ++++++++++++++++
 2 files changed, 17 insertions(+), 4 deletions(-)
crypto/meson.build +1 -4
index 735635de1f..0614bfa914 100644
@@ -22,12 +22,9 @@ crypto_ss.add(files(
   'tlscredsx509.c',
   'tlssession.c',
   'rsakey.c',
+  'x509-utils.c',
 ))
 
-if gnutls.found()
-  crypto_ss.add(files('x509-utils.c'))
-endif
-
 if nettle.found()
   crypto_ss.add(nettle, files('hash-nettle.c', 'hmac-nettle.c', 'pbkdf-nettle.c'))
   if hogweed.found()
crypto/x509-utils.c +16 -0
index 39bb6d4d8c..6176a88653 100644
@@ -11,6 +11,8 @@
 #include "qemu/osdep.h"
 #include "qapi/error.h"
 #include "crypto/x509-utils.h"
+
+#ifdef CONFIG_GNUTLS
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
 #include <gnutls/x509.h>
@@ -78,3 +80,17 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     gnutls_x509_crt_deinit(crt);
     return ret;
 }
+
+#else /* ! CONFIG_GNUTLS */
+
+int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
+                                      QCryptoHashAlgo hash,
+                                      uint8_t *result,
+                                      size_t *resultlen,
+                                      Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to get fingerprint");
+    return -1;
+}
+
+#endif /* ! CONFIG_GNUTLS */
Signature · 1 line
2.50.1
#11 lore raw

PATCH v5 3/29 crypto/x509-utils: Add helper functions for certificate store

In reply to Zhuoying Cai

Introduce new helper functions for x509 certificate, which will be used by the certificate store:

qcrypto_x509_convert_cert_der() - converts a certificate from PEM to DER format

These functions provide support for certificate format conversion.

---
 crypto/x509-utils.c         | 51 +++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h | 20 +++++++++++++++
 2 files changed, 71 insertions(+)
crypto/x509-utils.c +51 -0
index 6176a88653..29d5146bb2 100644
@@ -81,6 +81,48 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return ret;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result, size_t *resultlen,
+                                  Error **errp)
+{
+    int ret = -1;
+    int rc;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    if (*resultlen == 0) {
+        error_setg(errp, "Invalid buffer size");
+        goto cleanup;
+    }
+
+    *result = g_malloc0(*resultlen);
+    rc = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_DER, *result, resultlen);
+    if (rc != 0) {
+        error_setg(errp, "Failed to convert certificate to DER format: %s",
+                   gnutls_strerror(rc));
+        g_clear_pointer(result, g_free);
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
 #else /* ! CONFIG_GNUTLS */
 
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
@@ -93,4 +135,13 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return -1;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to export X.509 certificate");
+    return -1;
+}
+
 #endif /* ! CONFIG_GNUTLS */
include/crypto/x509-utils.h +20 -0
index 1e99661a71..4239e3e55a 100644
@@ -19,4 +19,24 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
                                       size_t *resultlen,
                                       Error **errp);
 
+/**
+ * qcrypto_x509_convert_cert_der
+ * @cert: pointer to the raw certificate data in PEM format
+ * @size: size of the certificate
+ * @result: output location for the allocated buffer for the certificate in DER format
+            (the function allocates memory which must be freed by the caller)
+ * @resultlen: pointer to the size of the buffer
+               (will be updated with the actual size of the DER-encoded certificate)
+ * @errp: error pointer
+ *
+ * Convert the given @cert from PEM to DER format.
+ *
+ * Returns: 0 on success,
+ *         -1 on error.
+ */
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp);
+
 #endif
Signature · 1 line
2.50.1
#12 lore raw

Re: [PATCH v5 03/29] crypto/x509-utils: Add helper functions for certificate store

Quoted 36 lines · Zhuoying Cai

Introduce new helper functions for x509 certificate, which will be used by the certificate store:

qcrypto_x509_convert_cert_der() - converts a certificate from PEM to DER format

These functions provide support for certificate format conversion.

---
 crypto/x509-utils.c         | 51 +++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h | 20 +++++++++++++++
 2 files changed, 71 insertions(+)
crypto/x509-utils.c +15 -0
index 6176a88653..29d5146bb2 100644
@@ -81,6 +81,48 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return ret;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result, size_t *resultlen,
+                                  Error **errp)
+{
+    int ret = -1;
+    int rc;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+

crypto/x509-utils.c int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size, · line 108

Quoted 10 lines
crypto/x509-utils.c +10 -0
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    if (*resultlen == 0) {
+        error_setg(errp, "Invalid buffer size");
+        goto cleanup;
+    }

Requiring resultlen to be set as an input parameter is strange, when this function is allocating the buffer. It would be better if we ignore resultlen on input and....

crypto/x509-utils.c int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size, · line 111

Quoted 3 lines
crypto/x509-utils.c +3 -0
+
+    *result = g_malloc0(*resultlen);
+    rc = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_DER, *result, resultlen);

Use 'gnutls_x509_crt_export2' instead

     datum.data = NULL;
     datum.size = 0;
     rc = gnutls_x509_crt_export2(crt, GNUTLS_X509_FMT_DER, &datum);
     if (rc != 0) {
     ....
     }
     *result = g_new0(uint8_t, datum.size);
     *resultlen = datum.size;
     memcpy(result, datum.data, datum.size);
     gnutls_free(datum.data);
Quoted 63 lines
crypto/x509-utils.c +23 -0
+    if (rc != 0) {
+        error_setg(errp, "Failed to convert certificate to DER format: %s",
+                   gnutls_strerror(rc));
+        g_clear_pointer(result, g_free);
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
 #else /* ! CONFIG_GNUTLS */
 
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
@@ -93,4 +135,13 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return -1;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to export X.509 certificate");
+    return -1;
+}
+
 #endif /* ! CONFIG_GNUTLS */
include/crypto/x509-utils.h +20 -0
index 1e99661a71..4239e3e55a 100644
@@ -19,4 +19,24 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
                                       size_t *resultlen,
                                       Error **errp);
 
+/**
+ * qcrypto_x509_convert_cert_der
+ * @cert: pointer to the raw certificate data in PEM format
+ * @size: size of the certificate
+ * @result: output location for the allocated buffer for the certificate in DER format
+            (the function allocates memory which must be freed by the caller)
+ * @resultlen: pointer to the size of the buffer
+               (will be updated with the actual size of the DER-encoded certificate)
+ * @errp: error pointer
+ *
+ * Convert the given @cert from PEM to DER format.
+ *
+ * Returns: 0 on success,
+ *         -1 on error.
+ */
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp);
+
 #endif
Signature · 1 line
2.50.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 :|
#13 lore raw

Re: [PATCH v5 03/29] crypto/x509-utils: Add helper functions for certificate store

Quoted 59 lines · Daniel P. Berrangé
Quoted 36 lines · Zhuoying Cai

Introduce new helper functions for x509 certificate, which will be used by the certificate store:

qcrypto_x509_convert_cert_der() - converts a certificate from PEM to DER format

These functions provide support for certificate format conversion.

---
 crypto/x509-utils.c         | 51 +++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h | 20 +++++++++++++++
 2 files changed, 71 insertions(+)
crypto/x509-utils.c +15 -0
index 6176a88653..29d5146bb2 100644
@@ -81,6 +81,48 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return ret;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result, size_t *resultlen,
+                                  Error **errp)
+{
+    int ret = -1;
+    int rc;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+

crypto/x509-utils.c int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size, · line 108

Quoted 10 lines
crypto/x509-utils.c +10 -0
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    if (*resultlen == 0) {
+        error_setg(errp, "Invalid buffer size");
+        goto cleanup;
+    }

Requiring resultlen to be set as an input parameter is strange, when this function is allocating the buffer. It would be better if we ignore resultlen on input and....

crypto/x509-utils.c int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size, · line 111

Quoted 3 lines
crypto/x509-utils.c +3 -0
+
+    *result = g_malloc0(*resultlen);
+    rc = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_DER, *result, resultlen);

Use 'gnutls_x509_crt_export2' instead

Quoted 11 lines
     datum.data = NULL;
     datum.size = 0;
     rc = gnutls_x509_crt_export2(crt, GNUTLS_X509_FMT_DER, &datum);
     if (rc != 0) {
     ....
     }
     *result = g_new0(uint8_t, datum.size);
     *resultlen = datum.size;
     memcpy(result, datum.data, datum.size);
     gnutls_free(datum.data);

Thanks for the suggestion! I'll make the change in the next version.

Quoted 66 lines
Quoted 63 lines
crypto/x509-utils.c +23 -0
+    if (rc != 0) {
+        error_setg(errp, "Failed to convert certificate to DER format: %s",
+                   gnutls_strerror(rc));
+        g_clear_pointer(result, g_free);
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
 #else /* ! CONFIG_GNUTLS */
 
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
@@ -93,4 +135,13 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
     return -1;
 }
 
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to export X.509 certificate");
+    return -1;
+}
+
 #endif /* ! CONFIG_GNUTLS */
include/crypto/x509-utils.h +20 -0
index 1e99661a71..4239e3e55a 100644
@@ -19,4 +19,24 @@ int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
                                       size_t *resultlen,
                                       Error **errp);
 
+/**
+ * qcrypto_x509_convert_cert_der
+ * @cert: pointer to the raw certificate data in PEM format
+ * @size: size of the certificate
+ * @result: output location for the allocated buffer for the certificate in DER format
+            (the function allocates memory which must be freed by the caller)
+ * @resultlen: pointer to the size of the buffer
+               (will be updated with the actual size of the DER-encoded certificate)
+ * @errp: error pointer
+ *
+ * Convert the given @cert from PEM to DER format.
+ *
+ * Returns: 0 on success,
+ *         -1 on error.
+ */
+int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp);
+
 #endif
Signature · 1 line
2.50.1

With regards,
Daniel

#14 lore raw

PATCH v5 4/29 hw/s390x/ipl: Create certificate store

In reply to Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
 hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
 hw/s390x/cert-store.h       |  38 +++++++
 hw/s390x/ipl.c              |   9 ++
 hw/s390x/ipl.h              |   3 +
 hw/s390x/meson.build        |   1 +
 include/hw/s390x/ipl/qipl.h |   2 +
 6 files changed, 254 insertions(+)
 create mode 100644 hw/s390x/cert-store.c
 create mode 100644 hw/s390x/cert-store.h
hw/s390x/cert-store.c new file +201 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);
+            exit(1);
+        }
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +38 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
 #include "qemu/option.h"
 #include "qemu/ctype.h"
 #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
 #define KERN_IMAGE_START                0x010000UL
 #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
     }
 }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
 static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
 {
     CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
     if (!ipl->kernel || ipl->iplb_valid) {
         cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
         if (!ipl->iplb_valid) {
             ipl->iplb_valid = s390_init_all_iplbs(ipl);
         } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
 #ifndef HW_S390_IPL_H
 #define HW_S390_IPL_H
 
+#include "cert-store.h"
 #include "cpu.h"
 #include "exec/target_page.h"
 #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
 void s390_ipl_prepare_cpu(S390CPU *cpu);
 IplParameterBlock *s390_ipl_get_iplb(void);
 IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
 enum s390_reset {
     /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
     IplParameterBlock iplb;
     IplParameterBlock iplb_pv;
     QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
     uint64_t start_addr;
     uint64_t compat_start_addr;
     uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
   'sclpcpu.c',
   'sclpquiesce.c',
   'tod.c',
+  'cert-store.c',
 ))
 s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
   'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +2 -0
index 6824391111..e505f44020 100644
@@ -20,6 +20,8 @@
 #define LOADPARM_LEN    8
 #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
 /*
  * The QEMU IPL Parameters will be stored at absolute address
  * 204 (0xcc) which means it is 32-bit word aligned but not
Signature · 1 line
2.50.1
#15 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 105 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
  hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
  hw/s390x/cert-store.h       |  38 +++++++
  hw/s390x/ipl.c              |   9 ++
  hw/s390x/ipl.h              |   3 +
  hw/s390x/meson.build        |   1 +
  include/hw/s390x/ipl/qipl.h |   2 +
  6 files changed, 254 insertions(+)

create mode 100644 hw/s390x/cert-store.c
create mode 100644 hw/s390x/cert-store.h

hw/s390x/cert-store.c new file +79 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);

hw/s390x/cert-store.c line 89

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);

Missing free?

Quoted 68 lines
hw/s390x/cert-store.c new file +68 -0
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+

hw/s390x/cert-store.c line 167

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);

This looks like it should return an error?

Quoted 15 lines
hw/s390x/cert-store.c new file +15 -0
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;

hw/s390x/cert-store.c line 192

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);
+            exit(1);
+        }

Why not do this check before the loop, using cert_path_builder->len directly?

Also, I think there is a missing free in this error case?

Quoted 132 lines
hw/s390x/cert-store.c new file +9 -0
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +38 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
  #include "qemu/option.h"
  #include "qemu/ctype.h"
  #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
  #define KERN_IMAGE_START                0x010000UL
  #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
      }
  }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
  static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
  {
      CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
      if (!ipl->kernel || ipl->iplb_valid) {
          cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
          if (!ipl->iplb_valid) {
              ipl->iplb_valid = s390_init_all_iplbs(ipl);
          } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
  #ifndef HW_S390_IPL_H
  #define HW_S390_IPL_H
 
+#include "cert-store.h"
  #include "cpu.h"
  #include "exec/target_page.h"
  #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
  void s390_ipl_prepare_cpu(S390CPU *cpu);
  IplParameterBlock *s390_ipl_get_iplb(void);
  IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
  enum s390_reset {
      /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
      IplParameterBlock iplb;
      IplParameterBlock iplb_pv;
      QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
      uint64_t start_addr;
      uint64_t compat_start_addr;
      uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
    'sclpcpu.c',
    'sclpquiesce.c',
    'tod.c',
+  'cert-store.c',
  ))
  s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
    'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +0 -0
index 6824391111..e505f44020 100644

include/hw/s390x/ipl/qipl.h line 27

Quoted 8 lines
include/hw/s390x/ipl/qipl.h +2 -0
@@ -20,6 +20,8 @@
  #define LOADPARM_LEN    8
  #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
  /*
   * The QEMU IPL Parameters will be stored at absolute address
   * 204 (0xcc) which means it is 32-bit word aligned but not

Regards,
Jared Rossi

#16 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 111 lines · Jared Rossi
Quoted 108 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
  hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
  hw/s390x/cert-store.h       |  38 +++++++
  hw/s390x/ipl.c              |   9 ++
  hw/s390x/ipl.h              |   3 +
  hw/s390x/meson.build        |   1 +
  include/hw/s390x/ipl/qipl.h |   2 +
  6 files changed, 254 insertions(+)

create mode 100644 hw/s390x/cert-store.c
create mode 100644 hw/s390x/cert-store.h

hw/s390x/cert-store.c new file +82 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
Quoted 9 lines

hw/s390x/cert-store.c line 89

Quoted 7 lines
hw/s390x/cert-store.c new file +7 -0
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);

Missing free?

Since the ownership of the buf pointer is transferred to qcert after init_cert_x509() completes successfully, free() is not necessary here.

I'll add comments here to make things clearer.

Quoted 108 lines
Quoted 68 lines
hw/s390x/cert-store.c new file +68 -0
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+

hw/s390x/cert-store.c line 167

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);

This looks like it should return an error?

Quoted 15 lines
hw/s390x/cert-store.c new file +15 -0
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;

hw/s390x/cert-store.c line 192

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);
+            exit(1);
+        }

Why not do this check before the loop, using cert_path_builder->len directly?

Quoted 2 lines

Also, I think there is a missing free in this error case?

Thanks for the feedback. I'll address them in the next version.

Quoted 142 lines
Quoted 132 lines
hw/s390x/cert-store.c new file +9 -0
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +38 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
  #include "qemu/option.h"
  #include "qemu/ctype.h"
  #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
  #define KERN_IMAGE_START                0x010000UL
  #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
      }
  }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
  static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
  {
      CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
      if (!ipl->kernel || ipl->iplb_valid) {
          cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
          if (!ipl->iplb_valid) {
              ipl->iplb_valid = s390_init_all_iplbs(ipl);
          } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
  #ifndef HW_S390_IPL_H
  #define HW_S390_IPL_H
 
+#include "cert-store.h"
  #include "cpu.h"
  #include "exec/target_page.h"
  #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
  void s390_ipl_prepare_cpu(S390CPU *cpu);
  IplParameterBlock *s390_ipl_get_iplb(void);
  IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
  enum s390_reset {
      /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
      IplParameterBlock iplb;
      IplParameterBlock iplb_pv;
      QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
      uint64_t start_addr;
      uint64_t compat_start_addr;
      uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
    'sclpcpu.c',
    'sclpquiesce.c',
    'tod.c',
+  'cert-store.c',
  ))
  s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
    'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +0 -0
index 6824391111..e505f44020 100644

include/hw/s390x/ipl/qipl.h line 27

Quoted 8 lines
include/hw/s390x/ipl/qipl.h +2 -0
@@ -20,6 +20,8 @@
  #define LOADPARM_LEN    8
  #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
  /*
   * The QEMU IPL Parameters will be stored at absolute address
   * 204 (0xcc) which means it is 32-bit word aligned but not

Regards,
Jared Rossi

#17 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

In reply to Zhuoying Cai
Quoted 132 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
  hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
  hw/s390x/cert-store.h       |  38 +++++++
  hw/s390x/ipl.c              |   9 ++
  hw/s390x/ipl.h              |   3 +
  hw/s390x/meson.build        |   1 +
  include/hw/s390x/ipl/qipl.h |   2 +
  6 files changed, 254 insertions(+)

create mode 100644 hw/s390x/cert-store.c
create mode 100644 hw/s390x/cert-store.h

hw/s390x/cert-store.c new file +106 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;

hw/s390x/cert-store.c line 116

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+

Do we need to free qcert here after we copied the contents to cert_store->certs[cert_store->count]? Also AFAIU we copy the certificate file contents into QEMU memory, but don't free it. Just wanted to clarify, do we need the file contents in QEMU memory for ccw-bios and guest kernel use? Thanks Farhan

Quoted 216 lines
hw/s390x/cert-store.c new file +85 -0
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);
+            exit(1);
+        }
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +38 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
  #include "qemu/option.h"
  #include "qemu/ctype.h"
  #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
  #define KERN_IMAGE_START                0x010000UL
  #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
      }
  }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
  static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
  {
      CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
      if (!ipl->kernel || ipl->iplb_valid) {
          cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
          if (!ipl->iplb_valid) {
              ipl->iplb_valid = s390_init_all_iplbs(ipl);
          } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
  #ifndef HW_S390_IPL_H
  #define HW_S390_IPL_H
 
+#include "cert-store.h"
  #include "cpu.h"
  #include "exec/target_page.h"
  #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
  void s390_ipl_prepare_cpu(S390CPU *cpu);
  IplParameterBlock *s390_ipl_get_iplb(void);
  IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
  enum s390_reset {
      /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
      IplParameterBlock iplb;
      IplParameterBlock iplb_pv;
      QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
      uint64_t start_addr;
      uint64_t compat_start_addr;
      uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
    'sclpcpu.c',
    'sclpquiesce.c',
    'tod.c',
+  'cert-store.c',
  ))
  s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
    'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +2 -0
index 6824391111..e505f44020 100644
@@ -20,6 +20,8 @@
  #define LOADPARM_LEN    8
  #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
  /*
   * The QEMU IPL Parameters will be stored at absolute address
   * 204 (0xcc) which means it is 32-bit word aligned but not
#18 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 142 lines · Farhan Ali
Quoted 140 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
  hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
  hw/s390x/cert-store.h       |  38 +++++++
  hw/s390x/ipl.c              |   9 ++
  hw/s390x/ipl.h              |   3 +
  hw/s390x/meson.build        |   1 +
  include/hw/s390x/ipl/qipl.h |   2 +
  6 files changed, 254 insertions(+)

create mode 100644 hw/s390x/cert-store.c
create mode 100644 hw/s390x/cert-store.h

hw/s390x/cert-store.c new file +114 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
Quoted 10 lines

hw/s390x/cert-store.c line 116

Quoted 2 lines
hw/s390x/cert-store.c new file +2 -0
+}
+

Do we need to free qcert here after we copied the contents to cert_store->certs[cert_store->count]? Also AFAIU we copy the certificate file contents into QEMU memory, but don't free it. Just wanted to clarify, do we need the file contents in QEMU memory for ccw-bios and guest kernel use? Thanks Farhan

Yes, the file contents need to remain in QEMU memory for both ccw-bios and guest kernel use.

* ccw-bios: The certificate used to verify the component is retrieved in the BIOS via DIAG320, with its address stored in the IPL Information Report Block.

* guest kernel: Certificates can also be retrieved via DIAG320 and made available to the guest kernel keyring.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8cf57d7217c32133d25615324c0ab4aaacf4d9c4

Quoted 216 lines
Quoted 216 lines
hw/s390x/cert-store.c new file +85 -0
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);
+            exit(1);
+        }
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +38 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
  #include "qemu/option.h"
  #include "qemu/ctype.h"
  #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
  #define KERN_IMAGE_START                0x010000UL
  #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
      }
  }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
  static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
  {
      CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
      if (!ipl->kernel || ipl->iplb_valid) {
          cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
          if (!ipl->iplb_valid) {
              ipl->iplb_valid = s390_init_all_iplbs(ipl);
          } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
  #ifndef HW_S390_IPL_H
  #define HW_S390_IPL_H
 
+#include "cert-store.h"
  #include "cpu.h"
  #include "exec/target_page.h"
  #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
  void s390_ipl_prepare_cpu(S390CPU *cpu);
  IplParameterBlock *s390_ipl_get_iplb(void);
  IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
  enum s390_reset {
      /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
      IplParameterBlock iplb;
      IplParameterBlock iplb_pv;
      QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
      uint64_t start_addr;
      uint64_t compat_start_addr;
      uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
    'sclpcpu.c',
    'sclpquiesce.c',
    'tod.c',
+  'cert-store.c',
  ))
  s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
    'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +2 -0
index 6824391111..e505f44020 100644
@@ -20,6 +20,8 @@
  #define LOADPARM_LEN    8
  #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
  /*
   * The QEMU IPL Parameters will be stored at absolute address
   * 204 (0xcc) which means it is 32-bit word aligned but not
#19 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 93 lines · Zhuoying Cai
Quoted 82 lines · Farhan Ali

[snip...]

hw/s390x/cert-store.c new file +80 -0
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
Quoted 7 lines

Do we need to free qcert here after we copied the contents to cert_store->certs[cert_store->count]? Also AFAIU we copy the certificate file contents into QEMU memory, but don't free it. Just wanted to clarify, do we need the file contents in QEMU memory for ccw-bios and guest kernel use? Thanks Farhan

Yes, the file contents need to remain in QEMU memory for both ccw-bios and guest kernel use.

Quoted 7 lines

* ccw-bios: The certificate used to verify the component is retrieved in the BIOS via DIAG320, with its address stored in the IPL Information Report Block.

* guest kernel: Certificates can also be retrieved via DIAG320 and made available to the guest kernel keyring.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8cf57d7217c32133d25615324c0ab4aaacf4d9c4

Something still doesn't seem right to me.  As far as I can tell the cert store will be reinitialized each time the guest reboots, which sounds like it will cause problems if there is no corresponding free somewhere.

What is the expected behavior during a reboot?  Should the guest A)  parse the cert paths again and reinitialize, or B)  read the entries in the previously created cert store?

If A, then the cert store needs to be cleared/freed in some way each time.

If B, then the cert store should not be reinitialized.

Quoted 1 line

[snip...]

Regards,
Jared Rossi

#20 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 111 lines · Jared Rossi
Quoted 93 lines · Zhuoying Cai
Quoted 82 lines · Farhan Ali

[snip...]

hw/s390x/cert-store.c new file +80 -0
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
Quoted 7 lines

Do we need to free qcert here after we copied the contents to cert_store->certs[cert_store->count]? Also AFAIU we copy the certificate file contents into QEMU memory, but don't free it. Just wanted to clarify, do we need the file contents in QEMU memory for ccw-bios and guest kernel use? Thanks Farhan

Yes, the file contents need to remain in QEMU memory for both ccw-bios and guest kernel use.

Quoted 7 lines

* ccw-bios: The certificate used to verify the component is retrieved in the BIOS via DIAG320, with its address stored in the IPL Information Report Block.

* guest kernel: Certificates can also be retrieved via DIAG320 and made available to the guest kernel keyring.
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8cf57d7217c32133d25615324c0ab4aaacf4d9c4

Something still doesn't seem right to me.  As far as I can tell the cert store will be reinitialized each time the guest reboots, which sounds like it will cause problems if there is no corresponding free somewhere.

What is the expected behavior during a reboot?  Should the guest A) parse the cert paths again and reinitialize, or B)  read the entries in the previously created cert store?

Quoted 7 lines

If A, then the cert store needs to be cleared/freed in some way each time.

If B, then the cert store should not be reinitialized.

Quoted 1 line

[snip...]

Regards,
Jared Rossi

I think option B sounds more accurate. Since the cert store can't be modified during reboot, it's reasonable to read from the previously created cert store.

#21 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

In reply to Zhuoying Cai
Quoted 52 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
 hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
 hw/s390x/cert-store.h       |  38 +++++++
 hw/s390x/ipl.c              |   9 ++
 hw/s390x/ipl.h              |   3 +
 hw/s390x/meson.build        |   1 +
 include/hw/s390x/ipl/qipl.h |   2 +
 6 files changed, 254 insertions(+)
 create mode 100644 hw/s390x/cert-store.c
 create mode 100644 hw/s390x/cert-store.h
hw/s390x/cert-store.c new file +26 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+

hw/s390x/cert-store.c line 36

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}

Seems redundant to check if size == 0 here. If g_file_get_contents succeeds and size is set to 0, there's no difference between returning 0 or returning size.

hw/s390x/cert-store.c line 40

Quoted 4 lines
hw/s390x/cert-store.c new file +4 -0
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;

I think the term "q_cert" is from an older implementation when we called this a "QEMUCertStore". Since we're doing this for s390 right now, I think it makes sense to just to call it "cert".

Quoted 4 lines
hw/s390x/cert-store.c new file +4 -0
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+

hw/s390x/cert-store.c line 54

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;

Setting the sizes here doesn't seem right:
1. it's making an assumption about the cert's data, and
2. these fields are never accessed in any subsequent patch

Patch 9 will explicitly use this enum when retrieving the cert and fingerprint, but this data is neither checked nor extracted from the S390IPLCertificate var.

I think it makes sense to get rid of the above two lines and potentially the two S390IPLCertificate fields as well.

Quoted 126 lines
hw/s390x/cert-store.c new file +126 -0
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {

hw/s390x/cert-store.c line 190

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);

nit: reword to "Cert store exceeds maximum of %d certificates"

Quoted 30 lines
hw/s390x/cert-store.c new file +11 -0
+            exit(1);
+        }
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +13 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"

hw/s390x/cert-store.h line 23

Quoted 10 lines
hw/s390x/cert-store.h new file +10 -0
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;

From above: I don't think these two fields are needed?

Quoted 102 lines
hw/s390x/cert-store.h new file +15 -0
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
 #include "qemu/option.h"
 #include "qemu/ctype.h"
 #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
 #define KERN_IMAGE_START                0x010000UL
 #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
     }
 }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
 static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
 {
     CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
     if (!ipl->kernel || ipl->iplb_valid) {
         cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
         if (!ipl->iplb_valid) {
             ipl->iplb_valid = s390_init_all_iplbs(ipl);
         } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
 #ifndef HW_S390_IPL_H
 #define HW_S390_IPL_H
 
+#include "cert-store.h"
 #include "cpu.h"
 #include "exec/target_page.h"
 #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
 void s390_ipl_prepare_cpu(S390CPU *cpu);
 IplParameterBlock *s390_ipl_get_iplb(void);
 IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
 enum s390_reset {
     /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
     IplParameterBlock iplb;
     IplParameterBlock iplb_pv;
     QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
     uint64_t start_addr;
     uint64_t compat_start_addr;
     uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
   'sclpcpu.c',
   'sclpquiesce.c',
   'tod.c',
+  'cert-store.c',
 ))
 s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
   'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +2 -0
index 6824391111..e505f44020 100644
@@ -20,6 +20,8 @@
 #define LOADPARM_LEN    8
 #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
 /*
  * The QEMU IPL Parameters will be stored at absolute address
  * 204 (0xcc) which means it is 32-bit word aligned but not
Signature · 2 lines
Regards,
  Collin
#22 lore raw

Re: [PATCH v5 04/29] hw/s390x/ipl: Create certificate store

Quoted 96 lines · Collin Walling
Quoted 52 lines · Zhuoying Cai

Create a certificate store for boot certificates used for secure IPL.

Load certificates from the boot-certs parameter of s390-ccw-virtio machine type option into the cert store.

Currently, only X.509 certificates in PEM format are supported, as the QEMU command line accepts certificates in PEM format only.

---
 hw/s390x/cert-store.c       | 201 ++++++++++++++++++++++++++++++++++++
 hw/s390x/cert-store.h       |  38 +++++++
 hw/s390x/ipl.c              |   9 ++
 hw/s390x/ipl.h              |   3 +
 hw/s390x/meson.build        |   1 +
 include/hw/s390x/ipl/qipl.h |   2 +
 6 files changed, 254 insertions(+)
 create mode 100644 hw/s390x/cert-store.c
 create mode 100644 hw/s390x/cert-store.h
hw/s390x/cert-store.c new file +26 -0
new file mode 100644
index 0000000000..81e748a912
@@ -0,0 +1,201 @@
+/*
+ * S390 certificate store implementation
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "qemu/osdep.h"
+#include "cert-store.h"
+#include "qapi/error.h"
+#include "qemu/error-report.h"
+#include "qemu/option.h"
+#include "qemu/config-file.h"
+#include "hw/s390x/ebcdic.h"
+#include "hw/s390x/s390-virtio-ccw.h"
+#include "qemu/cutils.h"
+#include "crypto/x509-utils.h"
+#include "qapi/qapi-types-machine-s390x.h"
+
+static BootCertPathList *s390_get_boot_certs(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->boot_certs;
+}
+

hw/s390x/cert-store.c line 36

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+static size_t cert2buf(char *path, char **cert_buf)
+{
+    size_t size;
+
+    if (!g_file_get_contents(path, cert_buf, &size, NULL) || size == 0) {
+        return 0;
+    }
+
+    return size;
+}

Seems redundant to check if size == 0 here. If g_file_get_contents succeeds and size is set to 0, there's no difference between returning 0 or returning size.

hw/s390x/cert-store.c line 40

Quoted 4 lines
hw/s390x/cert-store.c new file +4 -0
+
+static S390IPLCertificate *init_cert_x509(size_t size, uint8_t *raw, Error **errp)
+{
+    S390IPLCertificate *q_cert = NULL;

I think the term "q_cert" is from an older implementation when we called this a "QEMUCertStore". Since we're doing this for s390 right now, I think it makes sense to just to call it "cert".

Quoted 4 lines
hw/s390x/cert-store.c new file +4 -0
+    g_autofree uint8_t *cert_der = NULL;
+    size_t der_len = size;
+    int rc;
+

hw/s390x/cert-store.c line 54

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+    rc = qcrypto_x509_convert_cert_der(raw, size, &cert_der, &der_len, errp);
+    if (rc != 0) {
+        return NULL;
+    }
+
+    q_cert = g_new0(S390IPLCertificate, 1);
+    q_cert->size = size;
+    q_cert->der_size = der_len;
+    q_cert->key_id_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;
+    q_cert->hash_size = QCRYPTO_HASH_DIGEST_LEN_SHA256;

Setting the sizes here doesn't seem right:
1. it's making an assumption about the cert's data, and
2. these fields are never accessed in any subsequent patch

Quoted 7 lines

Patch 9 will explicitly use this enum when retrieving the cert and fingerprint, but this data is neither checked nor extracted from the S390IPLCertificate var.

I think it makes sense to get rid of the above two lines and potentially the two S390IPLCertificate fields as well.

Thanks for the feedback! I agree that these two fields can be removed from S390IPLCertificate.

However, the values themselves are still needed. Since both the key ID and fingerprint (hash value) of the certificate are SHA-256 outputs (with the fingerprint specifically requiring it), their lengths should always be 32 bytes.

These values are also used in this patch when calculating the certificate data length (key ID, fingerprint, and certificate), and in patch 9 when computing the VCE length.

Given that, it might be clearer to define them as constants rather than storing them in the struct.

Quoted 286 lines
Quoted 126 lines
hw/s390x/cert-store.c new file +126 -0
+    q_cert->raw = raw;
+
+    return q_cert;
+}
+
+static S390IPLCertificate *init_cert(char *path)
+{
+    char *buf;
+    size_t size;
+    char vc_name[VC_NAME_LEN_BYTES];
+    g_autofree gchar *filename = NULL;
+    S390IPLCertificate *qcert = NULL;
+    Error *local_err = NULL;
+
+    filename = g_path_get_basename(path);
+
+    size = cert2buf(path, &buf);
+    if (size == 0) {
+        error_report("Failed to load certificate: %s", path);
+        return NULL;
+    }
+
+    qcert = init_cert_x509(size, (uint8_t *)buf, &local_err);
+    if (qcert == NULL) {
+        error_reportf_err(local_err, "Failed to initialize certificate: %s:  ", path);
+        g_free(buf);
+        return NULL;
+    }
+
+    /*
+     * Left justified certificate name with padding on the right with blanks.
+     * Convert certificate name to EBCDIC.
+     */
+    strpadcpy(vc_name, VC_NAME_LEN_BYTES, filename, ' ');
+    ebcdic_put(qcert->vc_name, vc_name, VC_NAME_LEN_BYTES);
+
+    return qcert;
+}
+
+static void update_cert_store(S390IPLCertificateStore *cert_store,
+                              S390IPLCertificate *qcert)
+{
+    size_t data_buf_size;
+    size_t keyid_buf_size;
+    size_t hash_buf_size;
+    size_t cert_buf_size;
+
+    /* length field is word aligned for later DIAG use */
+    keyid_buf_size = ROUND_UP(qcert->key_id_size, 4);
+    hash_buf_size = ROUND_UP(qcert->hash_size, 4);
+    cert_buf_size = ROUND_UP(qcert->der_size, 4);
+    data_buf_size = keyid_buf_size + hash_buf_size + cert_buf_size;
+
+    if (cert_store->max_cert_size < data_buf_size) {
+        cert_store->max_cert_size = data_buf_size;
+    }
+
+    cert_store->certs[cert_store->count] = *qcert;
+    cert_store->total_bytes += data_buf_size;
+    cert_store->count++;
+}
+
+static GPtrArray *get_cert_paths(void)
+{
+    BootCertPathList *path_list = NULL;
+    BootCertPathList *list = NULL;
+    gchar *cert_path;
+    GDir *dir = NULL;
+    const gchar *filename;
+    g_autoptr(GError) err = NULL;
+    g_autoptr(GPtrArray) cert_path_builder = g_ptr_array_new_full(0, g_free);
+
+    path_list = s390_get_boot_certs();
+    if (path_list == NULL) {
+        return g_steal_pointer(&cert_path_builder);
+    }
+
+    for (list = path_list; list; list = list->next) {
+        cert_path = list->value->path;
+
+        if (g_strcmp0(cert_path, "") == 0) {
+            error_report("Empty path in certificate path list is not allowed");
+            exit(1);
+        }
+
+        struct stat st;
+        if (stat(cert_path, &st) != 0) {
+            error_report("Failed to stat path '%s': %s", cert_path, g_strerror(errno));
+            exit(1);
+        }
+
+        if (S_ISREG(st.st_mode)) {
+            if (g_str_has_suffix(cert_path, ".pem")) {
+                g_ptr_array_add(cert_path_builder, g_strdup(cert_path));
+            }
+        } else if (S_ISDIR(st.st_mode)) {
+            dir = g_dir_open(cert_path, 0, &err);
+            if (dir == NULL) {
+                error_report("Failed to open directory '%s': %s",
+                             cert_path, err->message);
+                exit(1);
+            }
+
+            while ((filename = g_dir_read_name(dir))) {
+                if (g_str_has_suffix(filename, ".pem")) {
+                    g_ptr_array_add(cert_path_builder,
+                                    g_build_filename(cert_path, filename, NULL));
+                }
+            }
+
+            g_dir_close(dir);
+        } else {
+            error_report("Path '%s' is neither a file nor a directory", cert_path);
+        }
+    }
+
+    qapi_free_BootCertPathList(path_list);
+    return g_steal_pointer(&cert_path_builder);
+}
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store)
+{
+    GPtrArray *cert_path_builder;
+
+    cert_path_builder = get_cert_paths();
+    if (cert_path_builder->len == 0) {

hw/s390x/cert-store.c line 190

Quoted 10 lines
hw/s390x/cert-store.c new file +10 -0
+        g_ptr_array_free(cert_path_builder, TRUE);
+        return;
+    }
+
+    cert_store->max_cert_size = 0;
+    cert_store->total_bytes = 0;
+
+    for (int i = 0; i < cert_path_builder->len; i++) {
+        if (i > MAX_CERTIFICATES - 1) {
+            error_report("Maximum %d certificates are allowed", MAX_CERTIFICATES);

nit: reword to "Cert store exceeds maximum of %d certificates"

Quoted 30 lines
hw/s390x/cert-store.c new file +11 -0
+            exit(1);
+        }
+
+        S390IPLCertificate *qcert = init_cert((char *) cert_path_builder->pdata[i]);
+        if (qcert) {
+            update_cert_store(cert_store, qcert);
+        }
+    }
+
+    g_ptr_array_free(cert_path_builder, TRUE);
+}
hw/s390x/cert-store.h new file +13 -0
new file mode 100644
index 0000000000..f030c8846c
@@ -0,0 +1,38 @@
+/*
+ * S390 certificate store
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_S390_CERT_STORE_H
+#define HW_S390_CERT_STORE_H
+
+#include "hw/s390x/ipl/qipl.h"

hw/s390x/cert-store.h line 23

Quoted 10 lines
hw/s390x/cert-store.h new file +10 -0
+#include "crypto/x509-utils.h"
+
+#define VC_NAME_LEN_BYTES  64
+
+struct S390IPLCertificate {
+    uint8_t vc_name[VC_NAME_LEN_BYTES];
+    size_t  size;
+    size_t  der_size;
+    size_t  key_id_size;
+    size_t  hash_size;

From above: I don't think these two fields are needed?

Quoted 102 lines
hw/s390x/cert-store.h new file +15 -0
+    uint8_t *raw;
+};
+typedef struct S390IPLCertificate S390IPLCertificate;
+
+struct S390IPLCertificateStore {
+    uint16_t count;
+    size_t   max_cert_size;
+    size_t   total_bytes;
+    S390IPLCertificate certs[MAX_CERTIFICATES];
+} QEMU_PACKED;
+typedef struct S390IPLCertificateStore S390IPLCertificateStore;
+
+void s390_ipl_create_cert_store(S390IPLCertificateStore *cert_store);
+
+#endif
hw/s390x/ipl.c +9 -0
index 2f082396c7..186be923d7 100644
@@ -35,6 +35,7 @@
 #include "qemu/option.h"
 #include "qemu/ctype.h"
 #include "standard-headers/linux/virtio_ids.h"
+#include "cert-store.h"
 
 #define KERN_IMAGE_START                0x010000UL
 #define LINUX_MAGIC_ADDR                0x010008UL
@@ -422,6 +423,13 @@ void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp)
     }
 }
 
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return &ipl->cert_store;
+}
+
 static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
 {
     CcwDevice *ccw_dev = NULL;
@@ -717,6 +725,7 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
 
     if (!ipl->kernel || ipl->iplb_valid) {
         cpu->env.psw.addr = ipl->bios_start_addr;
+        s390_ipl_create_cert_store(&ipl->cert_store);
         if (!ipl->iplb_valid) {
             ipl->iplb_valid = s390_init_all_iplbs(ipl);
         } else {
hw/s390x/ipl.h +3 -0
index 8f83c7da29..bee72dfbb3 100644
@@ -13,6 +13,7 @@
 #ifndef HW_S390_IPL_H
 #define HW_S390_IPL_H
 
+#include "cert-store.h"
 #include "cpu.h"
 #include "exec/target_page.h"
 #include "system/address-spaces.h"
@@ -35,6 +36,7 @@ int s390_ipl_pv_unpack(struct S390PVResponse *pv_resp);
 void s390_ipl_prepare_cpu(S390CPU *cpu);
 IplParameterBlock *s390_ipl_get_iplb(void);
 IplParameterBlock *s390_ipl_get_iplb_pv(void);
+S390IPLCertificateStore *s390_ipl_get_certificate_store(void);
 
 enum s390_reset {
     /* default is a reset not triggered by a CPU e.g. issued by QMP */
@@ -64,6 +66,7 @@ struct S390IPLState {
     IplParameterBlock iplb;
     IplParameterBlock iplb_pv;
     QemuIplParameters qipl;
+    S390IPLCertificateStore cert_store;
     uint64_t start_addr;
     uint64_t compat_start_addr;
     uint64_t bios_start_addr;
hw/s390x/meson.build +1 -0
index 8866012ddc..80d3d4a74d 100644
@@ -17,6 +17,7 @@ s390x_ss.add(files(
   'sclpcpu.c',
   'sclpquiesce.c',
   'tod.c',
+  'cert-store.c',
 ))
 s390x_ss.add(when: 'CONFIG_KVM', if_true: files(
   'tod-kvm.c',
include/hw/s390x/ipl/qipl.h +2 -0
index 6824391111..e505f44020 100644
@@ -20,6 +20,8 @@
 #define LOADPARM_LEN    8
 #define NO_LOADPARM "\0\0\0\0\0\0\0\0"
 
+#define MAX_CERTIFICATES  64
+
 /*
  * The QEMU IPL Parameters will be stored at absolute address
  * 204 (0xcc) which means it is 32-bit word aligned but not
#23 lore raw

PATCH v5 5/29 s390x/diag: Introduce DIAG 320 for Certificate Store Facility

In reply to Zhuoying Cai

DIAGNOSE 320 is introduced to support Certificate Store (CS) Facility, which includes operations such as query certificate storage information and provide certificates in the certificate store.

Currently, only subcode 0 is supported with this patch, which is used to query the Installed Subcodes Mask (ISM).

This subcode is only supported when the CS facility is enabled.

Availability of CS facility is determined by byte 134 bit 5 of the SCLP Read Info block. Byte 134's facilities cannot be represented without the availability of the extended-length-SCCB, so add it as a check for consistency.

Note: secure IPL is not available for Secure Execution (SE) guests, as their images are already integrity protected, and an additional protection of the kernel by secure IPL is not necessary.

---
 docs/specs/s390x-secure-ipl.rst     | 25 ++++++++++++++++
 include/hw/s390x/ipl/diag320.h      | 20 +++++++++++++
 target/s390x/cpu_features.c         |  1 +
 target/s390x/cpu_features_def.h.inc |  1 +
 target/s390x/cpu_models.c           |  2 ++
 target/s390x/diag.c                 | 44 +++++++++++++++++++++++++++++
 target/s390x/gen-features.c         |  3 ++
 target/s390x/kvm/kvm.c              | 16 +++++++++++
 target/s390x/s390x-internal.h       |  2 ++
 target/s390x/tcg/misc_helper.c      |  7 +++++
 10 files changed, 121 insertions(+)
 create mode 100644 docs/specs/s390x-secure-ipl.rst
 create mode 100644 include/hw/s390x/ipl/diag320.h
docs/specs/s390x-secure-ipl.rst new file +25 -0
new file mode 100644
index 0000000000..70e9a66fe0
@@ -0,0 +1,25 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+s390 Certificate Store and Functions
+====================================
+
+s390 Certificate Store
+----------------------
+
+A certificate store is implemented for s390-ccw guests to retain within
+memory all certificates provided by the user via the command-line, which
+are expected to be stored somewhere on the host's file system. The store
+will keep track of the number of certificates, their respective size,
+and a summation of the sizes.
+
+DIAGNOSE function code 'X'320' - Certificate Store Facility
+-----------------------------------------------------------
+
+DIAGNOSE 'X'320' is used to provide support for userspace to directly
+query the s390 certificate store. Userspace may be the s390-ccw BIOS or
+the guest kernel.
+
+Subcode 0 - query installed subcodes
+    Returns a 256-bit installed subcodes mask (ISM) stored in the installed
+    subcodes block (ISB). This mask indicates which sucodes are currently
+    installed and available for use.
include/hw/s390x/ipl/diag320.h new file +20 -0
new file mode 100644
index 0000000000..aa04b699c6
@@ -0,0 +1,20 @@
+/*
+ * S/390 DIAGNOSE 320 definitions and structures
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef S390X_DIAG320_H
+#define S390X_DIAG320_H
+
+#define DIAG_320_SUBC_QUERY_ISM     0
+
+#define DIAG_320_RC_OK              0x0001
+#define DIAG_320_RC_NOT_SUPPORTED   0x0102
+
+#define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+
+#endif
target/s390x/cpu_features.c +1 -0
index 4b5be6798e..436471f4b4 100644
@@ -147,6 +147,7 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
         break;
     case S390_FEAT_TYPE_SCLP_FAC134:
         clear_be_bit(s390_feat_def(S390_FEAT_DIAG_318)->bit, data);
+        clear_be_bit(s390_feat_def(S390_FEAT_CERT_STORE)->bit, data);
         break;
     default:
         return;
target/s390x/cpu_features_def.h.inc +1 -0
index c017bffcdc..941a69e013 100644
@@ -138,6 +138,7 @@ DEF_FEAT(SIE_IBS, "ibs", SCLP_CONF_CHAR_EXT, 10, "SIE: Interlock-and-broadcast-s
 
 /* Features exposed via SCLP SCCB Facilities byte 134 (bit numbers relative to byte-134) */
 DEF_FEAT(DIAG_318, "diag318", SCLP_FAC134, 0, "Control program name and version codes")
+DEF_FEAT(CERT_STORE, "cstore", SCLP_FAC134, 5, "Provide Certificate Store functions")
 
 /* Features exposed via SCLP CPU info. */
 DEF_FEAT(SIE_F2, "sief2", SCLP_CPU, 4, "SIE: interception format 2 (Virtual SIE)")
target/s390x/cpu_models.c +2 -0
index 954a7a99a9..6b8471700e 100644
@@ -248,6 +248,7 @@ bool s390_has_feat(S390Feat feat)
     if (s390_is_pv()) {
         switch (feat) {
         case S390_FEAT_DIAG_318:
+        case S390_FEAT_CERT_STORE:
         case S390_FEAT_HPMA2:
         case S390_FEAT_SIE_F2:
         case S390_FEAT_SIE_SKEY:
@@ -505,6 +506,7 @@ static void check_consistency(const S390CPUModel *model)
         { S390_FEAT_PTFF_STOUE, S390_FEAT_MULTIPLE_EPOCH },
         { S390_FEAT_AP_QUEUE_INTERRUPT_CONTROL, S390_FEAT_AP },
         { S390_FEAT_DIAG_318, S390_FEAT_EXTENDED_LENGTH_SCCB },
+        { S390_FEAT_CERT_STORE, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_NNPA, S390_FEAT_VECTOR },
         { S390_FEAT_RDP, S390_FEAT_LOCAL_TLB_CLEARING },
         { S390_FEAT_UV_FEAT_AP, S390_FEAT_AP },
target/s390x/diag.c +44 -0

53 lines not on this page · raw message

target/s390x/gen-features.c +3 -0
index 8218e6470e..6c20c3a862 100644
@@ -720,6 +720,7 @@ static uint16_t full_GEN16_GA1[] = {
     S390_FEAT_PAIE,
     S390_FEAT_UV_FEAT_AP,
     S390_FEAT_UV_FEAT_AP_INTR,
+    S390_FEAT_CERT_STORE,
 };
 
 static uint16_t full_GEN17_GA1[] = {
@@ -919,6 +920,8 @@ static uint16_t qemu_MAX[] = {
     S390_FEAT_KIMD_SHA_512,
     S390_FEAT_KLMD_SHA_512,
     S390_FEAT_PRNO_TRNG,
+    S390_FEAT_EXTENDED_LENGTH_SCCB,
+    S390_FEAT_CERT_STORE,
 };
 
 /****** END FEATURE DEFS ******/
target/s390x/kvm/kvm.c +16 -0
index 8ee33924df..5510fc2fc5 100644
@@ -98,6 +98,7 @@
 #define DIAG_TIMEREVENT                 0x288
 #define DIAG_IPL                        0x308
 #define DIAG_SET_CONTROL_PROGRAM_CODES  0x318
+#define DIAG_CERT_STORE                 0x320
 #define DIAG_KVM_HYPERCALL              0x500
 #define DIAG_KVM_BREAKPOINT             0x501
 
@@ -1560,6 +1561,16 @@ static void handle_diag_318(S390CPU *cpu, struct kvm_run *run)
     }
 }
 
+static void kvm_handle_diag_320(S390CPU *cpu, struct kvm_run *run)
+{
+    uint64_t r1, r3;
+
+    r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
+    r3 = run->s390_sieic.ipa & 0x000f;
+
+    handle_diag_320(&cpu->env, r1, r3, RA_IGNORED);
+}
+
 #define DIAG_KVM_CODE_MASK 0x000000000000ffff
 
 static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
@@ -1590,6 +1601,9 @@ static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
     case DIAG_KVM_BREAKPOINT:
         r = handle_sw_breakpoint(cpu, run);
         break;
+    case DIAG_CERT_STORE:
+        kvm_handle_diag_320(cpu, run);
+        break;
     default:
         trace_kvm_insn_diag(func_code);
         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
@@ -2490,6 +2504,8 @@ bool kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
         set_bit(S390_FEAT_DIAG_318, model->features);
     }
 
+    set_bit(S390_FEAT_CERT_STORE, model->features);
+
     /* Test for Ultravisor features that influence secure guest behavior */
     query_uv_feat_guest(model->features);
 
target/s390x/s390x-internal.h +2 -0
index 56cce2e7f5..ecff2d07a1 100644
@@ -391,6 +391,8 @@ int mmu_translate_real(CPUS390XState *env, target_ulong raddr, int rw,
 int handle_diag_288(CPUS390XState *env, uint64_t r1, uint64_t r3);
 void handle_diag_308(CPUS390XState *env, uint64_t r1, uint64_t r3,
                      uintptr_t ra);
+void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3,
+                     uintptr_t ra);
 
 
 /* translate.c */
target/s390x/tcg/misc_helper.c +7 -0
index f7101be574..412c34ed93 100644
@@ -142,6 +142,13 @@ void HELPER(diag)(CPUS390XState *env, uint32_t r1, uint32_t r3, uint32_t num)
         /* time bomb (watchdog) */
         r = handle_diag_288(env, r1, r3);
         break;
+    case 0x320:
+        /* cert store */
+        bql_lock();
+        handle_diag_320(env, r1, r3, GETPC());
+        bql_unlock();
+        r = 0;
+        break;
     default:
         r = -1;
         break;
Signature · 1 line
2.50.1
Reviewed-by on v5 5/29
#24 lore raw

Re: [PATCH v5 05/29] s390x/diag: Introduce DIAG 320 for Certificate Store Facility

Quoted 9 lines · Zhuoying Cai

DIAGNOSE 320 is introduced to support Certificate Store (CS) Facility, which includes operations such as query certificate storage information and provide certificates in the certificate store.

Currently, only subcode 0 is supported with this patch, which is used to query the Installed Subcodes Mask (ISM).

This subcode is only supported when the CS facility is enabled.

Please add in the commit message that this feature is available starting with the gen16 CPU model.

Quoted 11 lines

Availability of CS facility is determined by byte 134 bit 5 of the SCLP Read Info block. Byte 134's facilities cannot be represented without the availability of the extended-length-SCCB, so add it as a check for consistency.

Note: secure IPL is not available for Secure Execution (SE) guests, as their images are already integrity protected, and an additional protection of the kernel by secure IPL is not necessary.

Other than the question below regarding the documentation, code LGTM!

Quoted 25 lines
---
 docs/specs/s390x-secure-ipl.rst     | 25 ++++++++++++++++
 include/hw/s390x/ipl/diag320.h      | 20 +++++++++++++
 target/s390x/cpu_features.c         |  1 +
 target/s390x/cpu_features_def.h.inc |  1 +
 target/s390x/cpu_models.c           |  2 ++
 target/s390x/diag.c                 | 44 +++++++++++++++++++++++++++++
 target/s390x/gen-features.c         |  3 ++
 target/s390x/kvm/kvm.c              | 16 +++++++++++
 target/s390x/s390x-internal.h       |  2 ++
 target/s390x/tcg/misc_helper.c      |  7 +++++
 10 files changed, 121 insertions(+)
 create mode 100644 docs/specs/s390x-secure-ipl.rst
 create mode 100644 include/hw/s390x/ipl/diag320.h
docs/specs/s390x-secure-ipl.rst new file +4 -0
new file mode 100644
index 0000000000..70e9a66fe0
@@ -0,0 +1,25 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+s390 Certificate Store and Functions
+====================================

docs/specs/s390x-secure-ipl.rst line 14

Quoted 10 lines
docs/specs/s390x-secure-ipl.rst new file +10 -0
+
+s390 Certificate Store
+----------------------
+
+A certificate store is implemented for s390-ccw guests to retain within
+memory all certificates provided by the user via the command-line, which
+are expected to be stored somewhere on the host's file system. The store
+will keep track of the number of certificates, their respective size,
+and a summation of the sizes.
+

Perhaps the above should go with patch #4, since that one introduces the cert store?

Quoted 240 lines
docs/specs/s390x-secure-ipl.rst new file +11 -0
+DIAGNOSE function code 'X'320' - Certificate Store Facility
+-----------------------------------------------------------
+
+DIAGNOSE 'X'320' is used to provide support for userspace to directly
+query the s390 certificate store. Userspace may be the s390-ccw BIOS or
+the guest kernel.
+
+Subcode 0 - query installed subcodes
+    Returns a 256-bit installed subcodes mask (ISM) stored in the installed
+    subcodes block (ISB). This mask indicates which sucodes are currently
+    installed and available for use.
include/hw/s390x/ipl/diag320.h new file +20 -0
new file mode 100644
index 0000000000..aa04b699c6
@@ -0,0 +1,20 @@
+/*
+ * S/390 DIAGNOSE 320 definitions and structures
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef S390X_DIAG320_H
+#define S390X_DIAG320_H
+
+#define DIAG_320_SUBC_QUERY_ISM     0
+
+#define DIAG_320_RC_OK              0x0001
+#define DIAG_320_RC_NOT_SUPPORTED   0x0102
+
+#define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+
+#endif
target/s390x/cpu_features.c +1 -0
index 4b5be6798e..436471f4b4 100644
@@ -147,6 +147,7 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
         break;
     case S390_FEAT_TYPE_SCLP_FAC134:
         clear_be_bit(s390_feat_def(S390_FEAT_DIAG_318)->bit, data);
+        clear_be_bit(s390_feat_def(S390_FEAT_CERT_STORE)->bit, data);
         break;
     default:
         return;
target/s390x/cpu_features_def.h.inc +1 -0
index c017bffcdc..941a69e013 100644
@@ -138,6 +138,7 @@ DEF_FEAT(SIE_IBS, "ibs", SCLP_CONF_CHAR_EXT, 10, "SIE: Interlock-and-broadcast-s
 
 /* Features exposed via SCLP SCCB Facilities byte 134 (bit numbers relative to byte-134) */
 DEF_FEAT(DIAG_318, "diag318", SCLP_FAC134, 0, "Control program name and version codes")
+DEF_FEAT(CERT_STORE, "cstore", SCLP_FAC134, 5, "Provide Certificate Store functions")
 
 /* Features exposed via SCLP CPU info. */
 DEF_FEAT(SIE_F2, "sief2", SCLP_CPU, 4, "SIE: interception format 2 (Virtual SIE)")
target/s390x/cpu_models.c +2 -0
index 954a7a99a9..6b8471700e 100644
@@ -248,6 +248,7 @@ bool s390_has_feat(S390Feat feat)
     if (s390_is_pv()) {
         switch (feat) {
         case S390_FEAT_DIAG_318:
+        case S390_FEAT_CERT_STORE:
         case S390_FEAT_HPMA2:
         case S390_FEAT_SIE_F2:
         case S390_FEAT_SIE_SKEY:
@@ -505,6 +506,7 @@ static void check_consistency(const S390CPUModel *model)
         { S390_FEAT_PTFF_STOUE, S390_FEAT_MULTIPLE_EPOCH },
         { S390_FEAT_AP_QUEUE_INTERRUPT_CONTROL, S390_FEAT_AP },
         { S390_FEAT_DIAG_318, S390_FEAT_EXTENDED_LENGTH_SCCB },
+        { S390_FEAT_CERT_STORE, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_NNPA, S390_FEAT_VECTOR },
         { S390_FEAT_RDP, S390_FEAT_LOCAL_TLB_CLEARING },
         { S390_FEAT_UV_FEAT_AP, S390_FEAT_AP },
target/s390x/diag.c +44 -0
index cff9fbc4b0..a35d808fd7 100644
@@ -18,6 +18,7 @@
 #include "hw/watchdog/wdt_diag288.h"
 #include "system/cpus.h"
 #include "hw/s390x/ipl.h"
+#include "hw/s390x/ipl/diag320.h"
 #include "hw/s390x/s390-virtio-ccw.h"
 #include "system/kvm.h"
 #include "kvm/kvm_s390x.h"
@@ -191,3 +192,46 @@ out:
         break;
     }
 }
+
+void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
+{
+    S390CPU *cpu = env_archcpu(env);
+    uint64_t subcode = env->regs[r3];
+    uint64_t addr = env->regs[r1];
+
+    if (env->psw.mask & PSW_MASK_PSTATE) {
+        s390_program_interrupt(env, PGM_PRIVILEGED, ra);
+        return;
+    }
+
+    if (!s390_has_feat(S390_FEAT_CERT_STORE)) {
+        s390_program_interrupt(env, PGM_SPECIFICATION, ra);
+        return;
+    }
+
+    if ((subcode & ~0x000ffULL) || (r1 & 1)) {
+        s390_program_interrupt(env, PGM_SPECIFICATION, ra);
+        return;
+    }
+
+    switch (subcode) {
+    case DIAG_320_SUBC_QUERY_ISM:
+        /*
+         * The Installed Subcode Block (ISB) can be up 8 words in size,
+         * but the current set of subcodes can fit within a single word
+         * for now.
+         */
+        uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES);
+
+        if (s390_cpu_virt_mem_write(cpu, addr, r1, &ism_word0, sizeof(ism_word0))) {
+            s390_cpu_virt_mem_handle_exc(cpu, ra);
+            return;
+        }
+
+        env->regs[r1 + 1] = DIAG_320_RC_OK;
+        break;
+    default:
+        env->regs[r1 + 1] = DIAG_320_RC_NOT_SUPPORTED;
+        break;
+    }
+}
target/s390x/gen-features.c +3 -0
index 8218e6470e..6c20c3a862 100644
@@ -720,6 +720,7 @@ static uint16_t full_GEN16_GA1[] = {
     S390_FEAT_PAIE,
     S390_FEAT_UV_FEAT_AP,
     S390_FEAT_UV_FEAT_AP_INTR,
+    S390_FEAT_CERT_STORE,
 };
 
 static uint16_t full_GEN17_GA1[] = {
@@ -919,6 +920,8 @@ static uint16_t qemu_MAX[] = {
     S390_FEAT_KIMD_SHA_512,
     S390_FEAT_KLMD_SHA_512,
     S390_FEAT_PRNO_TRNG,
+    S390_FEAT_EXTENDED_LENGTH_SCCB,
+    S390_FEAT_CERT_STORE,
 };
 
 /****** END FEATURE DEFS ******/
target/s390x/kvm/kvm.c +16 -0
index 8ee33924df..5510fc2fc5 100644
@@ -98,6 +98,7 @@
 #define DIAG_TIMEREVENT                 0x288
 #define DIAG_IPL                        0x308
 #define DIAG_SET_CONTROL_PROGRAM_CODES  0x318
+#define DIAG_CERT_STORE                 0x320
 #define DIAG_KVM_HYPERCALL              0x500
 #define DIAG_KVM_BREAKPOINT             0x501
 
@@ -1560,6 +1561,16 @@ static void handle_diag_318(S390CPU *cpu, struct kvm_run *run)
     }
 }
 
+static void kvm_handle_diag_320(S390CPU *cpu, struct kvm_run *run)
+{
+    uint64_t r1, r3;
+
+    r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
+    r3 = run->s390_sieic.ipa & 0x000f;
+
+    handle_diag_320(&cpu->env, r1, r3, RA_IGNORED);
+}
+
 #define DIAG_KVM_CODE_MASK 0x000000000000ffff
 
 static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
@@ -1590,6 +1601,9 @@ static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
     case DIAG_KVM_BREAKPOINT:
         r = handle_sw_breakpoint(cpu, run);
         break;
+    case DIAG_CERT_STORE:
+        kvm_handle_diag_320(cpu, run);
+        break;
     default:
         trace_kvm_insn_diag(func_code);
         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
@@ -2490,6 +2504,8 @@ bool kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
         set_bit(S390_FEAT_DIAG_318, model->features);
     }
 
+    set_bit(S390_FEAT_CERT_STORE, model->features);
+
     /* Test for Ultravisor features that influence secure guest behavior */
     query_uv_feat_guest(model->features);
 
target/s390x/s390x-internal.h +2 -0
index 56cce2e7f5..ecff2d07a1 100644
@@ -391,6 +391,8 @@ int mmu_translate_real(CPUS390XState *env, target_ulong raddr, int rw,
 int handle_diag_288(CPUS390XState *env, uint64_t r1, uint64_t r3);
 void handle_diag_308(CPUS390XState *env, uint64_t r1, uint64_t r3,
                      uintptr_t ra);
+void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3,
+                     uintptr_t ra);
 
 
 /* translate.c */
target/s390x/tcg/misc_helper.c +7 -0
index f7101be574..412c34ed93 100644
@@ -142,6 +142,13 @@ void HELPER(diag)(CPUS390XState *env, uint32_t r1, uint32_t r3, uint32_t num)
         /* time bomb (watchdog) */
         r = handle_diag_288(env, r1, r3);
         break;
+    case 0x320:
+        /* cert store */
+        bql_lock();
+        handle_diag_320(env, r1, r3, GETPC());
+        bql_unlock();
+        r = 0;
+        break;
     default:
         r = -1;
         break;
Signature · 2 lines
Regards,
  Collin
#25 lore raw

PATCH v5 6/29 s390x/diag: Refactor address validation check from diag308_parm_check

In reply to Zhuoying Cai

Create a function to validate the address parameter of DIAGNOSE.

Refactor the function for reuse in the next patch, which allows address validation in read or write operation of DIAGNOSE.

---
 hw/s390x/ipl.h      | 6 ++++++
 target/s390x/diag.c | 4 +---
 2 files changed, 7 insertions(+), 3 deletions(-)
hw/s390x/ipl.h +6 -0
index bee72dfbb3..e26fc1cd6a 100644
@@ -118,6 +118,12 @@ QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong");
 #define S390_IPLB_MIN_FCP_LEN 384
 #define S390_IPLB_MIN_QEMU_SCSI_LEN 200
 
+static inline bool diag_parm_addr_valid(uint64_t addr, size_t size, bool write)
+{
+    return address_space_access_valid(&address_space_memory, addr,
+                                      size, write, MEMTXATTRS_UNSPECIFIED);
+}
+
 static inline bool iplb_valid_len(IplParameterBlock *iplb)
 {
     return be32_to_cpu(iplb->len) <= sizeof(IplParameterBlock);
target/s390x/diag.c +1 -3
index a35d808fd7..e67ee57f01 100644
@@ -65,9 +65,7 @@ static int diag308_parm_check(CPUS390XState *env, uint64_t r1, uint64_t addr,
         s390_program_interrupt(env, PGM_SPECIFICATION, ra);
         return -1;
     }
-    if (!address_space_access_valid(&address_space_memory, addr,
-                                    sizeof(IplParameterBlock), write,
-                                    MEMTXATTRS_UNSPECIFIED)) {
+    if (!diag_parm_addr_valid(addr, sizeof(IplParameterBlock), write)) {
         s390_program_interrupt(env, PGM_ADDRESSING, ra);
         return -1;
     }
Signature · 1 line
2.50.1
#26 lore raw

PATCH v5 7/29 s390x/diag: Implement DIAG 320 subcode 1

In reply to Zhuoying Cai

DIAG 320 subcode 1 provides information needed to determine the amount of storage to store one or more certificates from the certificate store.

Upon successful completion, this subcode returns information of the current cert store, such as the number of certificates stored and allowed in the cert store, amount of space may need to be allocate to store a certificate, etc for verification-certificate blocks (VCBs).

The subcode value is denoted by setting the left-most bit of an 8-byte field.

The verification-certificate-storage-size block (VCSSB) contains the output data when the operation completes successfully. A VCSSB length of 4 indicates that no certificate are available in the cert store.

---
 docs/specs/s390x-secure-ipl.rst | 10 ++++++
 include/hw/s390x/ipl/diag320.h  | 22 +++++++++++++
 target/s390x/diag.c             | 56 ++++++++++++++++++++++++++++++++-
 3 files changed, 87 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +10 -0
index 70e9a66fe0..ddc15f0322 100644
@@ -23,3 +23,13 @@ Subcode 0 - query installed subcodes
     Returns a 256-bit installed subcodes mask (ISM) stored in the installed
     subcodes block (ISB). This mask indicates which sucodes are currently
     installed and available for use.
+
+Subcode 1 - query verification certificate storage information
+    Provides the information required to determine the amount of memory needed to
+    store one or more verification-certificates (VCs) from the certificate store (CS).
+
+    Upon successful completion, this subcode returns various storage size values for
+    verification-certificate blocks (VCBs).
+
+    The output is returned in the verification-certificate-storage-size block (VCSSB).
+    A VCSSB length of 4 indicates that no certificates are available in the CS.
include/hw/s390x/ipl/diag320.h +22 -0
index aa04b699c6..6e4779c699 100644
@@ -11,10 +11,32 @@
 #define S390X_DIAG320_H
 
 #define DIAG_320_SUBC_QUERY_ISM     0
+#define DIAG_320_SUBC_QUERY_VCSI    1
 
 #define DIAG_320_RC_OK              0x0001
 #define DIAG_320_RC_NOT_SUPPORTED   0x0102
+#define DIAG_320_RC_INVAL_VCSSB_LEN 0x0202
 
 #define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+#define DIAG_320_ISM_QUERY_VCSI     0x40000000
+
+#define VCSSB_NO_VC     4
+#define VCSSB_MIN_LEN   128
+#define VCE_HEADER_LEN  128
+#define VCB_HEADER_LEN  64
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];
+    uint8_t version;
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;
 
 #endif
target/s390x/diag.c +55 -1

79 lines not on this page · raw message

Signature · 1 line
2.50.1
#27 lore raw

Re: [PATCH v5 07/29] s390x/diag: Implement DIAG 320 subcode 1

Quoted 67 lines · Zhuoying Cai

DIAG 320 subcode 1 provides information needed to determine the amount of storage to store one or more certificates from the certificate store.

Upon successful completion, this subcode returns information of the current cert store, such as the number of certificates stored and allowed in the cert store, amount of space may need to be allocate to store a certificate, etc for verification-certificate blocks (VCBs).

The subcode value is denoted by setting the left-most bit of an 8-byte field.

The verification-certificate-storage-size block (VCSSB) contains the output data when the operation completes successfully. A VCSSB length of 4 indicates that no certificate are available in the cert store.

---
  docs/specs/s390x-secure-ipl.rst | 10 ++++++
  include/hw/s390x/ipl/diag320.h  | 22 +++++++++++++
  target/s390x/diag.c             | 56 ++++++++++++++++++++++++++++++++-
  3 files changed, 87 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +10 -0
index 70e9a66fe0..ddc15f0322 100644
@@ -23,3 +23,13 @@ Subcode 0 - query installed subcodes
      Returns a 256-bit installed subcodes mask (ISM) stored in the installed
      subcodes block (ISB). This mask indicates which sucodes are currently
      installed and available for use.
+
+Subcode 1 - query verification certificate storage information
+    Provides the information required to determine the amount of memory needed to
+    store one or more verification-certificates (VCs) from the certificate store (CS).
+
+    Upon successful completion, this subcode returns various storage size values for
+    verification-certificate blocks (VCBs).
+
+    The output is returned in the verification-certificate-storage-size block (VCSSB).
+    A VCSSB length of 4 indicates that no certificates are available in the CS.
include/hw/s390x/ipl/diag320.h +12 -0
index aa04b699c6..6e4779c699 100644
@@ -11,10 +11,32 @@
  #define S390X_DIAG320_H
 
  #define DIAG_320_SUBC_QUERY_ISM     0
+#define DIAG_320_SUBC_QUERY_VCSI    1
 
  #define DIAG_320_RC_OK              0x0001
  #define DIAG_320_RC_NOT_SUPPORTED   0x0102
+#define DIAG_320_RC_INVAL_VCSSB_LEN 0x0202
 
  #define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+#define DIAG_320_ISM_QUERY_VCSI     0x40000000
+
+#define VCSSB_NO_VC     4
+#define VCSSB_MIN_LEN   128
+#define VCE_HEADER_LEN  128
+#define VCB_HEADER_LEN  64
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];

include/hw/s390x/ipl/diag320.h line 40

Quoted 10 lines
include/hw/s390x/ipl/diag320.h +10 -0
+    uint8_t version;
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;

Previous versions included a build bug message for the size of this structure, was it dropped by mistake?

Quoted 78 lines
include/hw/s390x/ipl/diag320.h +0 -0
  #endif
target/s390x/diag.c +48 -1
index e67ee57f01..b42cf8fe98 100644
@@ -191,11 +191,47 @@ out:
      }
  }
 
+static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1,
+                                     uintptr_t ra, S390IPLCertificateStore *qcs)
+{
+    g_autofree VCStorageSizeBlock *vcssb = NULL;
+
+    vcssb = g_new0(VCStorageSizeBlock, 1);
+    if (s390_cpu_virt_mem_read(cpu, addr, r1, vcssb, sizeof(*vcssb))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    if (be32_to_cpu(vcssb->length) < VCSSB_MIN_LEN) {
+        return DIAG_320_RC_INVAL_VCSSB_LEN;
+    }
+
+    if (!qcs->count) {
+        vcssb->length = cpu_to_be32(VCSSB_NO_VC);
+    } else {
+        vcssb->version = 0;
+        vcssb->total_vc_ct = cpu_to_be16(qcs->count);
+        vcssb->max_vc_ct = cpu_to_be16(MAX_CERTIFICATES);
+        vcssb->max_single_vcb_len = cpu_to_be32(VCB_HEADER_LEN + VCE_HEADER_LEN +
+                                                qcs->max_cert_size);
+        vcssb->total_vcb_len = cpu_to_be32(VCB_HEADER_LEN + qcs->count * VCE_HEADER_LEN +
+                                           qcs->total_bytes);
+    }
+
+    if (s390_cpu_virt_mem_write(cpu, addr, r1, vcssb, be32_to_cpu(vcssb->length))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+    return DIAG_320_RC_OK;
+}
+
  void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
      S390CPU *cpu = env_archcpu(env);
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
      uint64_t addr = env->regs[r1];
+    int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
          s390_program_interrupt(env, PGM_PRIVILEGED, ra);
@@ -219,7 +255,8 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
           * but the current set of subcodes can fit within a single word
           * for now.
           */
-        uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES);
+        uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES |
+                                         DIAG_320_ISM_QUERY_VCSI);
 
          if (s390_cpu_virt_mem_write(cpu, addr, r1, &ism_word0, sizeof(ism_word0))) {
              s390_cpu_virt_mem_handle_exc(cpu, ra);
@@ -228,6 +265,23 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
          env->regs[r1 + 1] = DIAG_320_RC_OK;
          break;
+    case DIAG_320_SUBC_QUERY_VCSI:
+        if (!diag_parm_addr_valid(addr, sizeof(VCStorageSizeBlock), true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        if (addr & 0x7) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 287

Quoted 10 lines
target/s390x/diag.c +7 -0
+
+        rc = handle_diag320_query_vcsi(cpu, addr, r1, ra, qcs);
+        if (rc == -1) {
+            return;
+        }
+        env->regs[r1 + 1] = rc;
+        break;
      default:
          env->regs[r1 + 1] = DIAG_320_RC_NOT_SUPPORTED;
          break;

Regards,
Jared rossi

#28 lore raw

Re: [PATCH v5 07/29] s390x/diag: Implement DIAG 320 subcode 1

Quoted 75 lines · Jared Rossi
Quoted 72 lines · Zhuoying Cai

DIAG 320 subcode 1 provides information needed to determine the amount of storage to store one or more certificates from the certificate store.

Upon successful completion, this subcode returns information of the current cert store, such as the number of certificates stored and allowed in the cert store, amount of space may need to be allocate to store a certificate, etc for verification-certificate blocks (VCBs).

The subcode value is denoted by setting the left-most bit of an 8-byte field.

The verification-certificate-storage-size block (VCSSB) contains the output data when the operation completes successfully. A VCSSB length of 4 indicates that no certificate are available in the cert store.

---
  docs/specs/s390x-secure-ipl.rst | 10 ++++++
  include/hw/s390x/ipl/diag320.h  | 22 +++++++++++++
  target/s390x/diag.c             | 56 ++++++++++++++++++++++++++++++++-
  3 files changed, 87 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +10 -0
index 70e9a66fe0..ddc15f0322 100644
@@ -23,3 +23,13 @@ Subcode 0 - query installed subcodes
      Returns a 256-bit installed subcodes mask (ISM) stored in the installed
      subcodes block (ISB). This mask indicates which sucodes are currently
      installed and available for use.
+
+Subcode 1 - query verification certificate storage information
+    Provides the information required to determine the amount of memory needed to
+    store one or more verification-certificates (VCs) from the certificate store (CS).
+
+    Upon successful completion, this subcode returns various storage size values for
+    verification-certificate blocks (VCBs).
+
+    The output is returned in the verification-certificate-storage-size block (VCSSB).
+    A VCSSB length of 4 indicates that no certificates are available in the CS.
include/hw/s390x/ipl/diag320.h +17 -0
index aa04b699c6..6e4779c699 100644
@@ -11,10 +11,32 @@
  #define S390X_DIAG320_H
 
  #define DIAG_320_SUBC_QUERY_ISM     0
+#define DIAG_320_SUBC_QUERY_VCSI    1
 
  #define DIAG_320_RC_OK              0x0001
  #define DIAG_320_RC_NOT_SUPPORTED   0x0102
+#define DIAG_320_RC_INVAL_VCSSB_LEN 0x0202
 
  #define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+#define DIAG_320_ISM_QUERY_VCSI     0x40000000
+
+#define VCSSB_NO_VC     4
+#define VCSSB_MIN_LEN   128
+#define VCE_HEADER_LEN  128
+#define VCB_HEADER_LEN  64
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];
+    uint8_t version;
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
Quoted 9 lines

include/hw/s390x/ipl/diag320.h line 40

Quoted 5 lines
include/hw/s390x/ipl/diag320.h +5 -0
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;

Previous versions included a build bug message for the size of this structure,
was it dropped by mistake?

Thanks for pointing it out. The use of the build error message was misunderstood as unnecessary in the last version.

I'll add it back in the next version.

Quoted 90 lines
Quoted 78 lines
include/hw/s390x/ipl/diag320.h +0 -0
  #endif
target/s390x/diag.c +48 -1
index e67ee57f01..b42cf8fe98 100644
@@ -191,11 +191,47 @@ out:
      }
  }
 
+static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1,
+                                     uintptr_t ra, S390IPLCertificateStore *qcs)
+{
+    g_autofree VCStorageSizeBlock *vcssb = NULL;
+
+    vcssb = g_new0(VCStorageSizeBlock, 1);
+    if (s390_cpu_virt_mem_read(cpu, addr, r1, vcssb, sizeof(*vcssb))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    if (be32_to_cpu(vcssb->length) < VCSSB_MIN_LEN) {
+        return DIAG_320_RC_INVAL_VCSSB_LEN;
+    }
+
+    if (!qcs->count) {
+        vcssb->length = cpu_to_be32(VCSSB_NO_VC);
+    } else {
+        vcssb->version = 0;
+        vcssb->total_vc_ct = cpu_to_be16(qcs->count);
+        vcssb->max_vc_ct = cpu_to_be16(MAX_CERTIFICATES);
+        vcssb->max_single_vcb_len = cpu_to_be32(VCB_HEADER_LEN + VCE_HEADER_LEN +
+                                                qcs->max_cert_size);
+        vcssb->total_vcb_len = cpu_to_be32(VCB_HEADER_LEN + qcs->count * VCE_HEADER_LEN +
+                                           qcs->total_bytes);
+    }
+
+    if (s390_cpu_virt_mem_write(cpu, addr, r1, vcssb, be32_to_cpu(vcssb->length))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+    return DIAG_320_RC_OK;
+}
+
  void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
      S390CPU *cpu = env_archcpu(env);
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
      uint64_t addr = env->regs[r1];
+    int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
          s390_program_interrupt(env, PGM_PRIVILEGED, ra);
@@ -219,7 +255,8 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
           * but the current set of subcodes can fit within a single word
           * for now.
           */
-        uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES);
+        uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES |
+                                         DIAG_320_ISM_QUERY_VCSI);
 
          if (s390_cpu_virt_mem_write(cpu, addr, r1, &ism_word0, sizeof(ism_word0))) {
              s390_cpu_virt_mem_handle_exc(cpu, ra);
@@ -228,6 +265,23 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
          env->regs[r1 + 1] = DIAG_320_RC_OK;
          break;
+    case DIAG_320_SUBC_QUERY_VCSI:
+        if (!diag_parm_addr_valid(addr, sizeof(VCStorageSizeBlock), true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        if (addr & 0x7) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 287

Quoted 10 lines
target/s390x/diag.c +7 -0
+
+        rc = handle_diag320_query_vcsi(cpu, addr, r1, ra, qcs);
+        if (rc == -1) {
+            return;
+        }
+        env->regs[r1 + 1] = rc;
+        break;
      default:
          env->regs[r1 + 1] = DIAG_320_RC_NOT_SUPPORTED;
          break;

Regards,
Jared rossi

#29 lore raw

Re: [PATCH v5 07/29] s390x/diag: Implement DIAG 320 subcode 1

Quoted 4 lines · Zhuoying Cai
Quoted 3 lines · Jared Rossi

On 8/18/25 5:43 PM, Zhuoying Cai wrote:

[...]

Quoted 19 lines
Quoted 9 lines
Quoted 9 lines
include/hw/s390x/ipl/diag320.h +9 -0
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];
+    uint8_t version;
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
Quoted 9 lines

include/hw/s390x/ipl/diag320.h line 40

Quoted 5 lines
include/hw/s390x/ipl/diag320.h +5 -0
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;

Previous versions included a build bug message for the size of this structure,
was it dropped by mistake?

Quoted 5 lines

Thanks for pointing it out. The use of the build error message was misunderstood as unnecessary in the last version.

I'll add it back in the next version.

Yes, this was my call and I should've asked for clarity on it before claiming it wasn't needed. That was my bad.

[...]

Signature · 2 lines
Regards,
  Collin
#30 lore raw

Re: [PATCH v5 07/29] s390x/diag: Implement DIAG 320 subcode 1

In reply to Zhuoying Cai
Quoted 68 lines · Zhuoying Cai

DIAG 320 subcode 1 provides information needed to determine the amount of storage to store one or more certificates from the certificate store.

Upon successful completion, this subcode returns information of the current cert store, such as the number of certificates stored and allowed in the cert store, amount of space may need to be allocate to store a certificate, etc for verification-certificate blocks (VCBs).

The subcode value is denoted by setting the left-most bit of an 8-byte field.

The verification-certificate-storage-size block (VCSSB) contains the output data when the operation completes successfully. A VCSSB length of 4 indicates that no certificate are available in the cert store.

---
  docs/specs/s390x-secure-ipl.rst | 10 ++++++
  include/hw/s390x/ipl/diag320.h  | 22 +++++++++++++
  target/s390x/diag.c             | 56 ++++++++++++++++++++++++++++++++-
  3 files changed, 87 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +10 -0
index 70e9a66fe0..ddc15f0322 100644
@@ -23,3 +23,13 @@ Subcode 0 - query installed subcodes
      Returns a 256-bit installed subcodes mask (ISM) stored in the installed
      subcodes block (ISB). This mask indicates which sucodes are currently
      installed and available for use.
+
+Subcode 1 - query verification certificate storage information
+    Provides the information required to determine the amount of memory needed to
+    store one or more verification-certificates (VCs) from the certificate store (CS).
+
+    Upon successful completion, this subcode returns various storage size values for
+    verification-certificate blocks (VCBs).
+
+    The output is returned in the verification-certificate-storage-size block (VCSSB).
+    A VCSSB length of 4 indicates that no certificates are available in the CS.
include/hw/s390x/ipl/diag320.h +13 -0
index aa04b699c6..6e4779c699 100644
@@ -11,10 +11,32 @@
  #define S390X_DIAG320_H
 
  #define DIAG_320_SUBC_QUERY_ISM     0
+#define DIAG_320_SUBC_QUERY_VCSI    1
 
  #define DIAG_320_RC_OK              0x0001
  #define DIAG_320_RC_NOT_SUPPORTED   0x0102
+#define DIAG_320_RC_INVAL_VCSSB_LEN 0x0202
 
  #define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+#define DIAG_320_ISM_QUERY_VCSI     0x40000000
+
+#define VCSSB_NO_VC     4
+#define VCSSB_MIN_LEN   128
+#define VCE_HEADER_LEN  128
+#define VCB_HEADER_LEN  64
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];
+    uint8_t version;

include/hw/s390x/ipl/diag320.h line 41

Quoted 10 lines
include/hw/s390x/ipl/diag320.h +9 -0
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;
 

Should this be a packed structure? The Linux kernel defines it as packed https://elixir.bootlin.com/linux/v6.17-rc3/source/arch/s390/kernel/cert_store.c#L81

Thanks
Farhan

#31 lore raw

Re: [PATCH v5 07/29] s390x/diag: Implement DIAG 320 subcode 1

Quoted 74 lines · Farhan Ali
Quoted 72 lines · Zhuoying Cai

DIAG 320 subcode 1 provides information needed to determine the amount of storage to store one or more certificates from the certificate store.

Upon successful completion, this subcode returns information of the current cert store, such as the number of certificates stored and allowed in the cert store, amount of space may need to be allocate to store a certificate, etc for verification-certificate blocks (VCBs).

The subcode value is denoted by setting the left-most bit of an 8-byte field.

The verification-certificate-storage-size block (VCSSB) contains the output data when the operation completes successfully. A VCSSB length of 4 indicates that no certificate are available in the cert store.

---
  docs/specs/s390x-secure-ipl.rst | 10 ++++++ include/hw/s390x/ipl/diag320.h  | 22 +++++++++++++ target/s390x/diag.c             | 56 ++++++++++++++++++++++++++++++++-

  3 files changed, 87 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +0 -0
index 70e9a66fe0..ddc15f0322 100644
@@ -23,3 +23,13 @@ Subcode 0 - query installed subcodes

      Returns a 256-bit installed subcodes mask (ISM) stored in the installed subcodes block (ISB). This mask indicates which sucodes are currently installed and available for use.

docs/specs/s390x-secure-ipl.rst +3 -0
+
+Subcode 1 - query verification certificate storage information
+    Provides the information required to determine the amount of memory 

needed to
+    store one or more verification-certificates (VCs) from the certificate store (CS).
+
+    Upon successful completion, this subcode returns various storage size values for
+    verification-certificate blocks (VCBs).
+
+    The output is returned in the verification-certificate-storage-size block (VCSSB).
+    A VCSSB length of 4 indicates that no certificates are available in the CS.

include/hw/s390x/ipl/diag320.h +15 -0
index aa04b699c6..6e4779c699 100644
@@ -11,10 +11,32 @@
   #define S390X_DIAG320_H
   #define DIAG_320_SUBC_QUERY_ISM     0
+#define DIAG_320_SUBC_QUERY_VCSI    1
   #define DIAG_320_RC_OK              0x0001
   #define DIAG_320_RC_NOT_SUPPORTED   0x0102
+#define DIAG_320_RC_INVAL_VCSSB_LEN 0x0202
   #define DIAG_320_ISM_QUERY_SUBCODES 0x80000000
+#define DIAG_320_ISM_QUERY_VCSI     0x40000000
+
+#define VCSSB_NO_VC     4
+#define VCSSB_MIN_LEN   128
+#define VCE_HEADER_LEN  128
+#define VCB_HEADER_LEN  64
+
+struct VCStorageSizeBlock {
+    uint32_t length;
+    uint8_t reserved0[3];
+    uint8_t version;
+    uint32_t reserved1[6];
+    uint16_t total_vc_ct;
Quoted 8 lines

include/hw/s390x/ipl/diag320.h line 40

Quoted 7 lines
include/hw/s390x/ipl/diag320.h +7 -0
+    uint16_t max_vc_ct;
+    uint32_t reserved3[11];
+    uint32_t max_single_vcb_len;
+    uint32_t total_vcb_len;
+    uint32_t reserved4[10];
+};
+typedef struct VCStorageSizeBlock VCStorageSizeBlock;

Should this be a packed structure? The Linux kernel defines it as packed https://elixir.bootlin.com/linux/v6.17-rc3/source/arch/s390/kernel/ cert_store.c#L81

Packed structs should be avoided in user space code that might get compiled on different host architectures, we've hit related problems a couple of times in the past already (doing a quick search, I came up with https://lists.gnu.org/archive/html/qemu-devel//2017-03/msg05316.html for example, but I remember we had similar problems in the s390x code once, too).

In this struct here, all fields are naturally aligned, so the packed should not be necessary. Just add a size check with QEMU_BUILD_BUG_ON to make sure that there is really no unexpected padding here.

Thomas

#32 lore raw

PATCH v5 8/29 crypto/x509-utils: Add helper functions for DIAG 320 subcode 2

In reply to Zhuoying Cai

Introduce new helper functions to extract certificate metadata needed for DIAG 320 subcode 2:

qcrypto_x509_check_cert_times() - validates the certificate's validity period against the current time qcrypto_x509_get_pk_algorithm() - returns the public key algorithm used in the certificate qcrypto_x509_get_cert_key_id() - extracts the key ID from the certificate

These functions provide support for metadata extraction and validity checking for X.509 certificates.

---
 crypto/x509-utils.c         | 174 ++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h |  58 ++++++++++++
 2 files changed, 232 insertions(+)
crypto/x509-utils.c +174 -0
index 29d5146bb2..67b42aad1f 100644
@@ -27,6 +27,21 @@ static const int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALGO__MAX] = {
     [QCRYPTO_HASH_ALGO_RIPEMD160] = GNUTLS_DIG_RMD160,
 };
 
+static const int gnutls_to_qcrypto_pk_alg_map[] = {
+    [GNUTLS_PK_RSA] = QCRYPTO_PK_ALGO_RSA,
+    [GNUTLS_PK_DSA] = QCRYPTO_PK_ALGO_DSA,
+    [GNUTLS_PK_ECDSA] = QCRYPTO_PK_ALGO_ECDSA,
+    [GNUTLS_PK_RSA_OAEP] = QCRYPTO_PK_ALGO_RSA_OAEP,
+    [GNUTLS_PK_EDDSA_ED25519] = QCRYPTO_PK_ALGO_ED25519,
+    [GNUTLS_PK_EDDSA_ED448] = QCRYPTO_PK_ALGO_ED448,
+};
+
+static const int qcrypto_to_gnutls_keyid_flags_map[] = {
+    [QCRYPTO_HASH_ALGO_SHA1] = GNUTLS_KEYID_USE_SHA1,
+    [QCRYPTO_HASH_ALGO_SHA256] = GNUTLS_KEYID_USE_SHA256,
+    [QCRYPTO_HASH_ALGO_SHA512] = GNUTLS_KEYID_USE_SHA512,
+};
+
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
                                       QCryptoHashAlgo alg,
                                       uint8_t *result,
@@ -123,6 +138,143 @@ cleanup:
     return ret;
 }
 
+int qcrypto_x509_check_cert_times(uint8_t *cert, size_t size, Error **errp)
+{
+    int rc;
+    int ret = -1;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+    time_t now = time(0);
+    time_t exp_time;
+    time_t act_time;
+
+    if (now == ((time_t)-1)) {
+        error_setg_errno(errp, errno, "Cannot get current time");
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    exp_time = gnutls_x509_crt_get_expiration_time(crt);
+    if (exp_time == ((time_t)-1)) {
+        error_setg(errp, "Failed to get certificate expiration time");
+        goto cleanup;
+    }
+    if (exp_time < now) {
+        error_setg(errp, "The certificate has expired");
+        goto cleanup;
+    }
+
+    act_time = gnutls_x509_crt_get_activation_time(crt);
+    if (act_time == ((time_t)-1)) {
+        error_setg(errp, "Failed to get certificate activation time");
+        goto cleanup;
+    }
+    if (act_time > now) {
+        error_setg(errp, "The certificate is not yet active");
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
+int qcrypto_x509_get_pk_algorithm(uint8_t *cert, size_t size, Error **errp)
+{
+    int rc;
+    int ret = -1;
+    unsigned int bits;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_x509_crt_get_pk_algorithm(crt, &bits);
+    if (rc >= G_N_ELEMENTS(gnutls_to_qcrypto_pk_alg_map)) {
+        error_setg(errp, "Unknown public key algorithm %d", rc);
+        goto cleanup;
+    }
+
+    ret = gnutls_to_qcrypto_pk_alg_map[rc];
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
+int qcrypto_x509_get_cert_key_id(uint8_t *cert, size_t size,
+                                 QCryptoHashAlgo hash_alg,
+                                 uint8_t **result,
+                                 size_t *resultlen,
+                                 Error **errp)
+{
+    int rc;
+    int ret = -1;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    if (hash_alg >= G_N_ELEMENTS(qcrypto_to_gnutls_keyid_flags_map)) {
+        error_setg(errp, "Unknow hash algorithm %d", hash_alg);
+        return ret;
+     }
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    *resultlen = gnutls_hash_get_len(qcrypto_to_gnutls_hash_alg_map[hash_alg]);
+    if (*resultlen == 0) {
+        error_setg(errp, "Failed to get hash algorithn length: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    *result = g_malloc0(*resultlen);
+    if (gnutls_x509_crt_get_key_id(crt,
+                                   qcrypto_to_gnutls_keyid_flags_map[hash_alg],
+                                   *result, resultlen) != 0) {
+        error_setg(errp, "Failed to get key ID from certificate");
+        g_clear_pointer(result, g_free);
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
 #else /* ! CONFIG_GNUTLS */
 
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
@@ -144,4 +296,26 @@ int qcrypto_x509_convert_cert_der(uint8_t *cert, size_t size,
     return -1;
 }
 
+int qcrypto_x509_check_cert_times(uint8_t *cert, size_t size, Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to get certificate times");
+    return -1;
+}
+
+int qcrypto_x509_get_pk_algorithm(uint8_t *cert, size_t size, Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to get public key algorithm");
+    return -1;
+}
+
+int qcrypto_x509_get_cert_key_id(uint8_t *cert, size_t size,
+                                 QCryptoHashAlgo hash_alg,
+                                 uint8_t **result,
+                                 size_t *resultlen,
+                                 Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to get key ID");
+    return -1;
+}
+
 #endif /* ! CONFIG_GNUTLS */
include/crypto/x509-utils.h +58 -0

68 lines not on this page · raw message

Signature · 1 line
2.50.1
#33 lore raw

Re: [PATCH v5 08/29] crypto/x509-utils: Add helper functions for DIAG 320 subcode 2

Quoted 83 lines · Zhuoying Cai

Introduce new helper functions to extract certificate metadata needed for DIAG 320 subcode 2:

qcrypto_x509_check_cert_times() - validates the certificate's validity period against the current time qcrypto_x509_get_pk_algorithm() - returns the public key algorithm used in the certificate qcrypto_x509_get_cert_key_id() - extracts the key ID from the certificate

These functions provide support for metadata extraction and validity checking for X.509 certificates.

---
 crypto/x509-utils.c         | 174 ++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h |  58 ++++++++++++
 2 files changed, 232 insertions(+)
crypto/x509-utils.c +51 -0
index 29d5146bb2..67b42aad1f 100644
@@ -27,6 +27,21 @@ static const int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALGO__MAX] = {
     [QCRYPTO_HASH_ALGO_RIPEMD160] = GNUTLS_DIG_RMD160,
 };
 
+static const int gnutls_to_qcrypto_pk_alg_map[] = {
+    [GNUTLS_PK_RSA] = QCRYPTO_PK_ALGO_RSA,
+    [GNUTLS_PK_DSA] = QCRYPTO_PK_ALGO_DSA,
+    [GNUTLS_PK_ECDSA] = QCRYPTO_PK_ALGO_ECDSA,
+    [GNUTLS_PK_RSA_OAEP] = QCRYPTO_PK_ALGO_RSA_OAEP,
+    [GNUTLS_PK_EDDSA_ED25519] = QCRYPTO_PK_ALGO_ED25519,
+    [GNUTLS_PK_EDDSA_ED448] = QCRYPTO_PK_ALGO_ED448,
+};
+
+static const int qcrypto_to_gnutls_keyid_flags_map[] = {
+    [QCRYPTO_HASH_ALGO_SHA1] = GNUTLS_KEYID_USE_SHA1,
+    [QCRYPTO_HASH_ALGO_SHA256] = GNUTLS_KEYID_USE_SHA256,
+    [QCRYPTO_HASH_ALGO_SHA512] = GNUTLS_KEYID_USE_SHA512,
+};
+
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
                                       QCryptoHashAlgo alg,
                                       uint8_t *result,
@@ -123,6 +138,143 @@ cleanup:
     return ret;
 }
 
 
+
+int qcrypto_x509_get_pk_algorithm(uint8_t *cert, size_t size, Error **errp)
+{
+    int rc;
+    int ret = -1;
+    unsigned int bits;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_x509_crt_get_pk_algorithm(crt, &bits);
+    if (rc >= G_N_ELEMENTS(gnutls_to_qcrypto_pk_alg_map)) {
+        error_setg(errp, "Unknown public key algorithm %d", rc);
+        goto cleanup;
+    }
+
+    ret = gnutls_to_qcrypto_pk_alg_map[rc];
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+
+int qcrypto_x509_get_cert_key_id(uint8_t *cert, size_t size,
+                                 QCryptoHashAlgo hash_alg,

crypto/x509-utils.c cleanup: · line 187

Quoted 10 lines
crypto/x509-utils.c +10 -0
+                                 uint8_t **result,
+                                 size_t *resultlen,
+                                 Error **errp)
+{
+    int rc;
+    int ret = -1;
+    gnutls_x509_crt_t crt;
+    gnutls_datum_t datum = {.data = cert, .size = size};
+
+    if (hash_alg >= G_N_ELEMENTS(qcrypto_to_gnutls_keyid_flags_map)) {

Must also check qcrypto_to_gnutls_hash_alg_map bounds.

crypto/x509-utils.c cleanup: · line 240

Quoted 1 line
crypto/x509-utils.c +1 -0
+        error_setg(errp, "Unknow hash algorithm %d", hash_alg);

's/Unknow/Unknown/'

Quoted 27 lines
crypto/x509-utils.c +27 -0
+        return ret;
+     }
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        return ret;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    *resultlen = gnutls_hash_get_len(qcrypto_to_gnutls_hash_alg_map[hash_alg]);
+    if (*resultlen == 0) {
+        error_setg(errp, "Failed to get hash algorithn length: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    *result = g_malloc0(*resultlen);
+    if (gnutls_x509_crt_get_key_id(crt,
+                                   qcrypto_to_gnutls_keyid_flags_map[hash_alg],
+                                   *result, resultlen) != 0) {
+        error_setg(errp, "Failed to get key ID from certificate");
+        g_clear_pointer(result, g_free);

crypto/x509-utils.c cleanup: · line 277

Quoted 10 lines
crypto/x509-utils.c +10 -0
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    return ret;
+}
+

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

PATCH v5 9/29 s390x/diag: Implement DIAG 320 subcode 2

In reply to Zhuoying Cai

DIAG 320 subcode 2 provides verification-certificates (VCs) that are in the certificate store. Only X509 certificates in DER format and SHA-256 hash type are recognized.

The subcode value is denoted by setting the second-left-most bit of an 8-byte field.

The Verification Certificate Block (VCB) contains the output data when the operation completes successfully. It includes a common header followed by zero or more Verification Certificate Entries (VCEs), depending on the VCB input length and the VC range (from the first VC index to the last VC index) in the certificate store.

Each VCE contains information about a certificate retrieved from the S390IPLCertificateStore, such as the certificate name, key type, key ID length, hash length, and the raw certificate data.
The key ID and hash are extracted from the raw certificate by the crypto API.

Note: SHA2-256 VC hash type is required for retrieving the hash (fingerprint) of the certificate.

---
 docs/specs/s390x-secure-ipl.rst |  13 ++
 include/hw/s390x/ipl/diag320.h  |  49 ++++++
 target/s390x/diag.c             | 286 +++++++++++++++++++++++++++++++-
 3 files changed, 347 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +13 -0
index ddc15f0322..16868aa823 100644
@@ -33,3 +33,16 @@ Subcode 1 - query verification certificate storage information
 
     The output is returned in the verification-certificate-storage-size block (VCSSB).
     A VCSSB length of 4 indicates that no certificates are available in the CS.
+
+Subcode 2 - store verification certificates
+    Provides VCs that are in the certificate store.
+
+    The output is provided in a VCB, which includes a common header followed by zero
+    or more verification-certificate entries (VCEs).
+
+    The first-VC index and last-VC index fields of VCB specify the range of VCs
+    to be stored by subcode 2. Stored count and remained count fields specify the
+    number of VCs stored and could not be stored in the VCB due to insufficient
+    storage specified in the VCB input length field.
+
+    VCE contains various information of a VC from the CS.
include/hw/s390x/ipl/diag320.h +49 -0

72 lines not on this page · raw message

target/s390x/diag.c +285 -1

316 lines not on this page · raw message

Signature · 1 line
2.50.1
#35 lore raw

Re: [PATCH v5 09/29] s390x/diag: Implement DIAG 320 subcode 2

Quoted 28 lines · Zhuoying Cai

DIAG 320 subcode 2 provides verification-certificates (VCs) that are in the certificate store. Only X509 certificates in DER format and SHA-256 hash type are recognized.

The subcode value is denoted by setting the second-left-most bit of an 8-byte field.

The Verification Certificate Block (VCB) contains the output data when the operation completes successfully. It includes a common header followed by zero or more Verification Certificate Entries (VCEs), depending on the VCB input length and the VC range (from the first VC index to the last VC index) in the certificate store.

Each VCE contains information about a certificate retrieved from the S390IPLCertificateStore, such as the certificate name, key type, key ID length, hash length, and the raw certificate data.
The key ID and hash are extracted from the raw certificate by the crypto API.

Note: SHA2-256 VC hash type is required for retrieving the hash (fingerprint) of the certificate.

---
  docs/specs/s390x-secure-ipl.rst |  13 ++
  include/hw/s390x/ipl/diag320.h  |  49 ++++++
  target/s390x/diag.c             | 286 +++++++++++++++++++++++++++++++-
  3 files changed, 347 insertions(+), 1 deletion(-)

[snip...]

Quoted 85 lines
target/s390x/diag.c +85 -0
+static VCEntry *diag_320_build_vce(S390IPLCertificate qcert, uint32_t vce_len, int idx)
+{
+    g_autofree VCEntry *vce = NULL;
+    int rc;
+
+    /*
+     * Construct VCE
+     * Allocate enough memory for all certificate data (key id, hash and certificate).
+     * Unused area following the VCE field contains zeros.
+     */
+    vce = g_malloc0(vce_len);
+    rc = build_vce_header(vce, qcert, idx);
+    if (rc) {
+        vce->len = cpu_to_be32(VCE_INVALID_LEN);
+        goto out;
+    }
+    vce->len = cpu_to_be32(VCE_HEADER_LEN);
+
+    rc = build_vce_data(vce, qcert);
+    if (rc) {
+        vce->len = cpu_to_be32(VCE_INVALID_LEN);
+    }
+
+out:
+    return g_steal_pointer(&vce);
+}
+
+static int handle_diag320_store_vc(S390CPU *cpu, uint64_t addr, uint64_t r1, uintptr_t ra,
+                                   S390IPLCertificateStore *qcs)
+{
+    g_autofree VCBlock *vcb = NULL;
+    size_t vce_offset;
+    size_t remaining_space;
+    uint32_t vce_len;
+    uint16_t first_vc_index;
+    uint16_t last_vc_index;
+    uint32_t in_len;
+
+    vcb = g_new0(VCBlock, 1);
+    if (s390_cpu_virt_mem_read(cpu, addr, r1, vcb, sizeof(*vcb))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    in_len = be32_to_cpu(vcb->in_len);
+    first_vc_index = be16_to_cpu(vcb->first_vc_index);
+    last_vc_index = be16_to_cpu(vcb->last_vc_index);
+
+    if (in_len % TARGET_PAGE_SIZE != 0) {
+        return DIAG_320_RC_INVAL_VCB_LEN;
+    }
+
+    if (first_vc_index > last_vc_index) {
+        return DIAG_320_RC_BAD_RANGE;
+    }
+
+    if (first_vc_index == 0) {
+        /*
+         * Zero is a valid index for the first and last VC index.
+         * Zero index results in the VCB header and zero certificates returned.
+         */
+        if (last_vc_index == 0) {
+            goto out;
+        }
+
+        /* DIAG320 certificate store remains a one origin for cert entries */
+        vcb->first_vc_index = 1;
+        first_vc_index = 1;
+    }
+
+    vce_offset = VCB_HEADER_LEN;
+    vcb->out_len = VCB_HEADER_LEN;
+    remaining_space = in_len - VCB_HEADER_LEN;
+
+    for (int i = first_vc_index - 1; i < last_vc_index && i < qcs->count; i++) {
+        VCEntry *vce;
+        S390IPLCertificate qcert = qcs->certs[i];
+        /*
+         * Each VCE is word aligned.
+         * Each variable length field within the VCE is also word aligned.
+         */
+        vce_len = VCE_HEADER_LEN +
+                  ROUND_UP(qcert.key_id_size, 4) +
+                  ROUND_UP(qcert.hash_size, 4) +
+                  ROUND_UP(qcert.der_size, 4);

target/s390x/diag.c static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1, · line 468

Quoted 10 lines
target/s390x/diag.c +10 -0
+
+        /*
+         * If there is no more space to store the cert,
+         * set the remaining verification cert count and
+         * break early.
+         */
+        if (remaining_space < vce_len) {
+            vcb->remain_ct = cpu_to_be16(last_vc_index - i);
+            break;
+        }

What is the significance of remain_ct != 0?

Should there be an error or warning that there was not enough space?

target/s390x/diag.c static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1, · line 476

Quoted 8 lines
target/s390x/diag.c +8 -0
+
+        vce = diag_320_build_vce(qcert, vce_len, i);
+
+        /* Write VCE */
+        if (s390_cpu_virt_mem_write(cpu, addr + vce_offset, r1,
+                                    vce, be32_to_cpu(vce->len))) {
+            s390_cpu_virt_mem_handle_exc(cpu, ra);
+            return -1;

Missing vce free in this early return?

Quoted 44 lines
target/s390x/diag.c +29 -1
+        }
+
+        vce_offset += be32_to_cpu(vce->len);
+        vcb->out_len += be32_to_cpu(vce->len);
+        remaining_space -= be32_to_cpu(vce->len);
+        vcb->stored_ct++;
+
+        g_free(vce);
+    }
+
+    vcb->out_len = cpu_to_be32(vcb->out_len);
+    vcb->stored_ct = cpu_to_be16(vcb->stored_ct);
+
+out:
+    /*
+     * Write VCB header
+     * All VCEs have been populated with the latest information
+     * and write VCB header last.
+     */
+    if (s390_cpu_virt_mem_write(cpu, addr, r1, vcb, VCB_HEADER_LEN)) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    return DIAG_320_RC_OK;
+}
+
  void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
      S390CPU *cpu = env_archcpu(env);
@@ -256,7 +532,8 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
           * for now.
           */
          uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES |
-                                         DIAG_320_ISM_QUERY_VCSI);
+                                         DIAG_320_ISM_QUERY_VCSI |
+                                         DIAG_320_ISM_STORE_VC);
 
          if (s390_cpu_virt_mem_write(cpu, addr, r1, &ism_word0, sizeof(ism_word0))) {
              s390_cpu_virt_mem_handle_exc(cpu, ra);
@@ -282,6 +559,13 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
          }
          env->regs[r1 + 1] = rc;
          break;

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 571

Quoted 10 lines
target/s390x/diag.c +7 -0
+    case DIAG_320_SUBC_STORE_VC:
+        rc = handle_diag320_store_vc(cpu, addr, r1, ra, qcs);
+        if (rc == -1) {
+            return;
+        }
+        env->regs[r1 + 1] = rc;
+        break;
      default:
          env->regs[r1 + 1] = DIAG_320_RC_NOT_SUPPORTED;
          break;

Regards,
Jared Rossi

#36 lore raw

Re: [PATCH v5 09/29] s390x/diag: Implement DIAG 320 subcode 2

Quoted 128 lines · Jared Rossi
Quoted 28 lines · Zhuoying Cai

DIAG 320 subcode 2 provides verification-certificates (VCs) that are in the certificate store. Only X509 certificates in DER format and SHA-256 hash type are recognized.

The subcode value is denoted by setting the second-left-most bit of an 8-byte field.

The Verification Certificate Block (VCB) contains the output data when the operation completes successfully. It includes a common header followed by zero or more Verification Certificate Entries (VCEs), depending on the VCB input length and the VC range (from the first VC index to the last VC index) in the certificate store.

Each VCE contains information about a certificate retrieved from the S390IPLCertificateStore, such as the certificate name, key type, key ID length, hash length, and the raw certificate data.
The key ID and hash are extracted from the raw certificate by the crypto API.

Note: SHA2-256 VC hash type is required for retrieving the hash (fingerprint) of the certificate.

---
  docs/specs/s390x-secure-ipl.rst |  13 ++
  include/hw/s390x/ipl/diag320.h  |  49 ++++++
  target/s390x/diag.c             | 286 +++++++++++++++++++++++++++++++-
  3 files changed, 347 insertions(+), 1 deletion(-)

[snip...]

Quoted 85 lines
target/s390x/diag.c +85 -0
+static VCEntry *diag_320_build_vce(S390IPLCertificate qcert, uint32_t vce_len, int idx)
+{
+    g_autofree VCEntry *vce = NULL;
+    int rc;
+
+    /*
+     * Construct VCE
+     * Allocate enough memory for all certificate data (key id, hash and certificate).
+     * Unused area following the VCE field contains zeros.
+     */
+    vce = g_malloc0(vce_len);
+    rc = build_vce_header(vce, qcert, idx);
+    if (rc) {
+        vce->len = cpu_to_be32(VCE_INVALID_LEN);
+        goto out;
+    }
+    vce->len = cpu_to_be32(VCE_HEADER_LEN);
+
+    rc = build_vce_data(vce, qcert);
+    if (rc) {
+        vce->len = cpu_to_be32(VCE_INVALID_LEN);
+    }
+
+out:
+    return g_steal_pointer(&vce);
+}
+
+static int handle_diag320_store_vc(S390CPU *cpu, uint64_t addr, uint64_t r1, uintptr_t ra,
+                                   S390IPLCertificateStore *qcs)
+{
+    g_autofree VCBlock *vcb = NULL;
+    size_t vce_offset;
+    size_t remaining_space;
+    uint32_t vce_len;
+    uint16_t first_vc_index;
+    uint16_t last_vc_index;
+    uint32_t in_len;
+
+    vcb = g_new0(VCBlock, 1);
+    if (s390_cpu_virt_mem_read(cpu, addr, r1, vcb, sizeof(*vcb))) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    in_len = be32_to_cpu(vcb->in_len);
+    first_vc_index = be16_to_cpu(vcb->first_vc_index);
+    last_vc_index = be16_to_cpu(vcb->last_vc_index);
+
+    if (in_len % TARGET_PAGE_SIZE != 0) {
+        return DIAG_320_RC_INVAL_VCB_LEN;
+    }
+
+    if (first_vc_index > last_vc_index) {
+        return DIAG_320_RC_BAD_RANGE;
+    }
+
+    if (first_vc_index == 0) {
+        /*
+         * Zero is a valid index for the first and last VC index.
+         * Zero index results in the VCB header and zero certificates returned.
+         */
+        if (last_vc_index == 0) {
+            goto out;
+        }
+
+        /* DIAG320 certificate store remains a one origin for cert entries */
+        vcb->first_vc_index = 1;
+        first_vc_index = 1;
+    }
+
+    vce_offset = VCB_HEADER_LEN;
+    vcb->out_len = VCB_HEADER_LEN;
+    remaining_space = in_len - VCB_HEADER_LEN;
+
+    for (int i = first_vc_index - 1; i < last_vc_index && i < qcs->count; i++) {
+        VCEntry *vce;
+        S390IPLCertificate qcert = qcs->certs[i];
+        /*
+         * Each VCE is word aligned.
+         * Each variable length field within the VCE is also word aligned.
+         */
+        vce_len = VCE_HEADER_LEN +
+                  ROUND_UP(qcert.key_id_size, 4) +
+                  ROUND_UP(qcert.hash_size, 4) +
+                  ROUND_UP(qcert.der_size, 4);

target/s390x/diag.c static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1, · line 468

Quoted 10 lines
target/s390x/diag.c +10 -0
+
+        /*
+         * If there is no more space to store the cert,
+         * set the remaining verification cert count and
+         * break early.
+         */
+        if (remaining_space < vce_len) {
+            vcb->remain_ct = cpu_to_be16(last_vc_index - i);
+            break;
+        }

What is the significance of remain_ct != 0?

Quoted 2 lines

Should there be an error or warning that there was not enough space?

remain_ct != 0 indicates insufficient memory to acquire all requested certificates.

I'll add a check in the caller function and report an error if not all certificates can be retrieved.

Quoted 66 lines

target/s390x/diag.c static int handle_diag320_query_vcsi(S390CPU *cpu, uint64_t addr, uint64_t r1, · line 476

Quoted 8 lines
target/s390x/diag.c +8 -0
+
+        vce = diag_320_build_vce(qcert, vce_len, i);
+
+        /* Write VCE */
+        if (s390_cpu_virt_mem_write(cpu, addr + vce_offset, r1,
+                                    vce, be32_to_cpu(vce->len))) {
+            s390_cpu_virt_mem_handle_exc(cpu, ra);
+            return -1;

Missing vce free in this early return?

Quoted 44 lines
target/s390x/diag.c +29 -1
+        }
+
+        vce_offset += be32_to_cpu(vce->len);
+        vcb->out_len += be32_to_cpu(vce->len);
+        remaining_space -= be32_to_cpu(vce->len);
+        vcb->stored_ct++;
+
+        g_free(vce);
+    }
+
+    vcb->out_len = cpu_to_be32(vcb->out_len);
+    vcb->stored_ct = cpu_to_be16(vcb->stored_ct);
+
+out:
+    /*
+     * Write VCB header
+     * All VCEs have been populated with the latest information
+     * and write VCB header last.
+     */
+    if (s390_cpu_virt_mem_write(cpu, addr, r1, vcb, VCB_HEADER_LEN)) {
+        s390_cpu_virt_mem_handle_exc(cpu, ra);
+        return -1;
+    }
+
+    return DIAG_320_RC_OK;
+}
+
  void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
      S390CPU *cpu = env_archcpu(env);
@@ -256,7 +532,8 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
           * for now.
           */
          uint32_t ism_word0 = cpu_to_be32(DIAG_320_ISM_QUERY_SUBCODES |
-                                         DIAG_320_ISM_QUERY_VCSI);
+                                         DIAG_320_ISM_QUERY_VCSI |
+                                         DIAG_320_ISM_STORE_VC);
 
          if (s390_cpu_virt_mem_write(cpu, addr, r1, &ism_word0, sizeof(ism_word0))) {
              s390_cpu_virt_mem_handle_exc(cpu, ra);
@@ -282,6 +559,13 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
          }
          env->regs[r1 + 1] = rc;
          break;

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 571

Quoted 10 lines
target/s390x/diag.c +7 -0
+    case DIAG_320_SUBC_STORE_VC:
+        rc = handle_diag320_store_vc(cpu, addr, r1, ra, qcs);
+        if (rc == -1) {
+            return;
+        }
+        env->regs[r1 + 1] = rc;
+        break;
      default:
          env->regs[r1 + 1] = DIAG_320_RC_NOT_SUPPORTED;
          break;

Regards,
Jared Rossi

#37 lore raw

PATCH v5 10/29 s390x/diag: Introduce DIAG 508 for secure IPL operations

In reply to Zhuoying Cai

From: Collin Walling <[email protected]>

In order to support secure IPL (aka secure boot) for the s390-ccw BIOS, a new s390 DIAGNOSE instruction is introduced to leverage QEMU for handling operations such as signature verification and certificate retrieval.

Currently, only subcode 0 is supported with this patch, which is used to query a bitmap of which subcodes are supported.

---
 docs/specs/s390x-secure-ipl.rst | 18 ++++++++++++++++++
 include/hw/s390x/ipl/diag508.h  | 15 +++++++++++++++
 target/s390x/diag.c             | 27 +++++++++++++++++++++++++++
 target/s390x/kvm/kvm.c          | 14 ++++++++++++++
 target/s390x/s390x-internal.h   |  2 ++
 target/s390x/tcg/misc_helper.c  |  7 +++++++
 6 files changed, 83 insertions(+)
 create mode 100644 include/hw/s390x/ipl/diag508.h
docs/specs/s390x-secure-ipl.rst +18 -0
index 16868aa823..6b3249173f 100644
@@ -46,3 +46,21 @@ Subcode 2 - store verification certificates
     storage specified in the VCB input length field.
 
     VCE contains various information of a VC from the CS.
+
+
+Secure IPL Data Structures, Facilities, and Functions
+=====================================================
+
+DIAGNOSE function code 'X'508' - KVM IPL extensions
+---------------------------------------------------
+
+DIAGNOSE 'X'508' is reserved for KVM guest use in order to facilitate
+communication of additional IPL operations that cannot be handled by userspace,
+such as signature verification for secure IPL.
+
+If the function code specifies 0x508, KVM IPL extension functions are performed.
+These functions are meant to provide extended functionality for s390 guest boot
+that requires assistance from QEMU.
+
+Subcode 0 - query installed subcodes
+    Returns a 64-bit mask indicating which subcodes are supported.
include/hw/s390x/ipl/diag508.h new file +15 -0
new file mode 100644
index 0000000000..6281ad8299
@@ -0,0 +1,15 @@
+/*
+ * S/390 DIAGNOSE 508 definitions and structures
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Collin Walling <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef S390X_DIAG508_H
+#define S390X_DIAG508_H
+
+#define DIAG_508_SUBC_QUERY_SUBC    0x0000
+
+#endif
target/s390x/diag.c +27 -0
index 820f45a0bd..6519a3cedc 100644
@@ -20,6 +20,7 @@
 #include "hw/s390x/cert-store.h"
 #include "hw/s390x/ipl.h"
 #include "hw/s390x/ipl/diag320.h"
+#include "hw/s390x/ipl/diag508.h"
 #include "hw/s390x/s390-virtio-ccw.h"
 #include "system/kvm.h"
 #include "kvm/kvm_s390x.h"
@@ -571,3 +572,29 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
         break;
     }
 }
+
+void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
+{
+    uint64_t subcode = env->regs[r3];
+    int rc;
+
+    if (env->psw.mask & PSW_MASK_PSTATE) {
+        s390_program_interrupt(env, PGM_PRIVILEGED, ra);
+        return;
+    }
+
+    if ((subcode & ~0x0ffffULL) || (r1 & 1)) {
+        s390_program_interrupt(env, PGM_SPECIFICATION, ra);
+        return;
+    }
+
+    switch (subcode) {
+    case DIAG_508_SUBC_QUERY_SUBC:
+        rc = 0;
+        break;
+    default:
+        s390_program_interrupt(env, PGM_SPECIFICATION, ra);
+        return;
+    }
+    env->regs[r1 + 1] = rc;
+}
target/s390x/kvm/kvm.c +14 -0
index 5510fc2fc5..ae6cd3d506 100644
@@ -101,6 +101,7 @@
 #define DIAG_CERT_STORE                 0x320
 #define DIAG_KVM_HYPERCALL              0x500
 #define DIAG_KVM_BREAKPOINT             0x501
+#define DIAG_SECURE_IPL                 0x508
 
 #define ICPT_INSTRUCTION                0x04
 #define ICPT_PROGRAM                    0x08
@@ -1571,6 +1572,16 @@ static void kvm_handle_diag_320(S390CPU *cpu, struct kvm_run *run)
     handle_diag_320(&cpu->env, r1, r3, RA_IGNORED);
 }
 
+static void kvm_handle_diag_508(S390CPU *cpu, struct kvm_run *run)
+{
+    uint64_t r1, r3;
+
+    r1 = (run->s390_sieic.ipa & 0x00f0) >> 4;
+    r3 = run->s390_sieic.ipa & 0x000f;
+
+    handle_diag_508(&cpu->env, r1, r3, RA_IGNORED);
+}
+
 #define DIAG_KVM_CODE_MASK 0x000000000000ffff
 
 static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
@@ -1604,6 +1615,9 @@ static int handle_diag(S390CPU *cpu, struct kvm_run *run, uint32_t ipb)
     case DIAG_CERT_STORE:
         kvm_handle_diag_320(cpu, run);
         break;
+    case DIAG_SECURE_IPL:
+        kvm_handle_diag_508(cpu, run);
+        break;
     default:
         trace_kvm_insn_diag(func_code);
         kvm_s390_program_interrupt(cpu, PGM_SPECIFICATION);
target/s390x/s390x-internal.h +2 -0
index ecff2d07a1..7cca8a67de 100644
@@ -393,6 +393,8 @@ void handle_diag_308(CPUS390XState *env, uint64_t r1, uint64_t r3,
                      uintptr_t ra);
 void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3,
                      uintptr_t ra);
+void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3,
+                     uintptr_t ra);
 
 
 /* translate.c */
target/s390x/tcg/misc_helper.c +7 -0
index 412c34ed93..ddbf495118 100644
@@ -149,6 +149,13 @@ void HELPER(diag)(CPUS390XState *env, uint32_t r1, uint32_t r3, uint32_t num)
         bql_unlock();
         r = 0;
         break;
+    case 0x508:
+        /* secure ipl operations */
+        bql_lock();
+        handle_diag_508(env, r1, r3, GETPC());
+        bql_unlock();
+        r = 0;
+        break;
     default:
         r = -1;
         break;
Signature · 1 line
2.50.1
#38 lore raw

PATCH v5 11/29 crypto/x509-utils: Add helper functions for DIAG 508 subcode 1

In reply to Zhuoying Cai

Introduce helper functions to support signature verification required by DIAG 508 subcode 1:

qcrypto_pkcs7_convert_sig_pem() – converts a signature from DER to PEM format qcrypto_x509_verify_sig() – verifies the provided data against the given signature

These functions enable basic signature verification support.

---
 crypto/x509-utils.c         | 108 ++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h |  39 +++++++++++++
 2 files changed, 147 insertions(+)
crypto/x509-utils.c +108 -0
index 67b42aad1f..f582e2ee48 100644
@@ -16,6 +16,7 @@
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
 #include <gnutls/x509.h>
+#include <gnutls/pkcs7.h>
 
 static const int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALGO__MAX] = {
     [QCRYPTO_HASH_ALGO_MD5] = GNUTLS_DIG_MD5,
@@ -275,6 +276,96 @@ cleanup:
     return ret;
 }
 
+int qcrypto_pkcs7_convert_sig_pem(uint8_t *sig, size_t sig_size,
+                                  uint8_t **result, size_t *resultlen,
+                                  Error **errp)
+{
+    int ret = -1;
+    int rc;
+    gnutls_pkcs7_t signature;
+    gnutls_datum_t sig_datum_der = {.data = sig, .size = sig_size};
+    gnutls_datum_t sig_datum_pem = { 0, };
+
+    rc = gnutls_pkcs7_init(&signature);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initalize pkcs7 data: %s", gnutls_strerror(rc));
+        return ret;
+     }
+
+    rc = gnutls_pkcs7_import(signature, &sig_datum_der, GNUTLS_X509_FMT_DER);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import signature: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_pkcs7_export2(signature, GNUTLS_X509_FMT_PEM, &sig_datum_pem);
+    if (rc != 0) {
+        error_setg(errp, "Failed to convert signature to PEM format: %s",
+                   gnutls_strerror(rc));
+        gnutls_free(sig_datum_pem.data);
+        goto cleanup;
+    }
+
+    *result = g_steal_pointer(&sig_datum_pem.data);
+    *resultlen = sig_datum_pem.size;
+
+    ret = 0;
+
+cleanup:
+    gnutls_pkcs7_deinit(signature);
+    return ret;
+}
+
+int qcrypto_x509_verify_sig(uint8_t *cert, size_t cert_size,
+                            uint8_t *comp, size_t comp_size,
+                            uint8_t *sig, size_t sig_size, Error **errp)
+{
+    int rc;
+    int ret = -1;
+    gnutls_x509_crt_t crt = NULL;
+    gnutls_pkcs7_t signature = NULL;
+    gnutls_datum_t cert_datum = {.data = cert, .size = cert_size};
+    gnutls_datum_t data_datum = {.data = comp, .size = comp_size};
+    gnutls_datum_t sig_datum = {.data = sig, .size = sig_size};
+
+    rc = gnutls_x509_crt_init(&crt);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initialize certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_x509_crt_import(crt, &cert_datum, GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import certificate: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_pkcs7_init(&signature);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initalize pkcs7 data: %s", gnutls_strerror(rc));
+        goto cleanup;
+     }
+
+    rc = gnutls_pkcs7_import(signature, &sig_datum , GNUTLS_X509_FMT_PEM);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import signature: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    rc = gnutls_pkcs7_verify_direct(signature, crt, 0, &data_datum, 0);
+    if (rc != 0) {
+        error_setg(errp, "Failed to verify signature: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }
+
+    ret = 0;
+
+cleanup:
+    gnutls_x509_crt_deinit(crt);
+    gnutls_pkcs7_deinit(signature);
+    return ret;
+}
+
 #else /* ! CONFIG_GNUTLS */
 
 int qcrypto_get_x509_cert_fingerprint(uint8_t *cert, size_t size,
@@ -318,4 +409,21 @@ int qcrypto_x509_get_cert_key_id(uint8_t *cert, size_t size,
     return -1;
 }
 
+int qcrypto_pkcs7_convert_sig_pem(uint8_t *sig, size_t sig_size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp)
+{
+    error_setg(errp, "GNUTLS is required to export pkcs7 signature");
+    return -1;
+}
+
+int qcrypto_x509_verify_sig(uint8_t *cert, size_t cert_size,
+                            uint8_t *comp, size_t comp_size,
+                            uint8_t *sig, size_t sig_size, Error **errp)
+{
+    error_setg(errp, "GNUTLS is required for signature-verification support");
+    return -1;
+}
+
 #endif /* ! CONFIG_GNUTLS */
include/crypto/x509-utils.h +39 -0
index f169df81cb..c4073fd265 100644
@@ -97,4 +97,43 @@ int qcrypto_x509_get_cert_key_id(uint8_t *cert, size_t size,
                                  size_t *resultlen,
                                  Error **errp);
 
+/**
+ * qcrypto_pkcs7_convert_sig_pem
+ * @sig: pointer to the PKCS#7 signature in DER format
+ * @sig_size: size of the signature
+ * @result: output location for the allocated buffer for the signature in PEM format
+            (the function allocates memory which must be freed by the caller)
+ * @resultlen: pointer to the size of the buffer
+               (will be updated with the actual size of the PEM-encoded signature)
+ * @errp: error pointer
+ *
+ * Convert given PKCS#7 @sig from DER to PEM format.
+ *
+ * Returns: 0 if PEM-encoded signature was successfully stored in @result,
+ *         -1 on error.
+ */
+int qcrypto_pkcs7_convert_sig_pem(uint8_t *sig, size_t sig_size,
+                                  uint8_t **result,
+                                  size_t *resultlen,
+                                  Error **errp);
+
+/**
+ * qcrypto_x509_verify_sig
+ * @cert: pointer to the raw certificate data
+ * @cert_size: size of the certificate
+ * @comp: pointer to the component to be verified
+ * @comp_size: size of the component
+ * @sig: pointer to the signature
+ * @sig_size: size of the signature
+ * @errp: error pointer
+ *
+ * Verify the provided @comp against the @sig and @cert.
+ *
+ * Returns: 0 on success,
+ *         -1 on error.
+ */
+int qcrypto_x509_verify_sig(uint8_t *cert, size_t cert_size,
+                            uint8_t *comp, size_t comp_size,
+                            uint8_t *sig, size_t sig_size, Error **errp);
+
 #endif
Signature · 1 line
2.50.1
#39 lore raw

Re: [PATCH v5 11/29] crypto/x509-utils: Add helper functions for DIAG 508 subcode 1

Quoted 51 lines · Zhuoying Cai

Introduce helper functions to support signature verification required by DIAG 508 subcode 1:

qcrypto_pkcs7_convert_sig_pem() – converts a signature from DER to PEM format qcrypto_x509_verify_sig() – verifies the provided data against the given signature

These functions enable basic signature verification support.

---
 crypto/x509-utils.c         | 108 ++++++++++++++++++++++++++++++++++++
 include/crypto/x509-utils.h |  39 +++++++++++++
 2 files changed, 147 insertions(+)
crypto/x509-utils.c +22 -0
index 67b42aad1f..f582e2ee48 100644
@@ -16,6 +16,7 @@
 #include <gnutls/gnutls.h>
 #include <gnutls/crypto.h>
 #include <gnutls/x509.h>
+#include <gnutls/pkcs7.h>
 
 static const int qcrypto_to_gnutls_hash_alg_map[QCRYPTO_HASH_ALGO__MAX] = {
     [QCRYPTO_HASH_ALGO_MD5] = GNUTLS_DIG_MD5,
@@ -275,6 +276,96 @@ cleanup:
     return ret;
 }
 
+int qcrypto_pkcs7_convert_sig_pem(uint8_t *sig, size_t sig_size,
+                                  uint8_t **result, size_t *resultlen,
+                                  Error **errp)
+{
+    int ret = -1;
+    int rc;
+    gnutls_pkcs7_t signature;
+    gnutls_datum_t sig_datum_der = {.data = sig, .size = sig_size};
+    gnutls_datum_t sig_datum_pem = { 0, };
+
+    rc = gnutls_pkcs7_init(&signature);
+    if (rc < 0) {
+        error_setg(errp, "Failed to initalize pkcs7 data: %s", gnutls_strerror(rc));
+        return ret;
+     }
+
+    rc = gnutls_pkcs7_import(signature, &sig_datum_der, GNUTLS_X509_FMT_DER);
+    if (rc != 0) {
+        error_setg(errp, "Failed to import signature: %s", gnutls_strerror(rc));
+        goto cleanup;
+    }

crypto/x509-utils.c cleanup: · line 309

Quoted 10 lines
crypto/x509-utils.c +10 -0
+
+    rc = gnutls_pkcs7_export2(signature, GNUTLS_X509_FMT_PEM, &sig_datum_pem);
+    if (rc != 0) {
+        error_setg(errp, "Failed to convert signature to PEM format: %s",
+                   gnutls_strerror(rc));
+        gnutls_free(sig_datum_pem.data);
+        goto cleanup;
+    }
+
+    *result = g_steal_pointer(&sig_datum_pem.data);

I just realized we should actually allocate a buffer with g_new and copy over from sig_datum_pem, because we can't safely assume that gnutls buffers can be freed with the system free(), only gnutls_free()

crypto/x509-utils.c cleanup: · line 317

Quoted 8 lines
crypto/x509-utils.c +8 -0
+    *resultlen = sig_datum_pem.size;
+
+    ret = 0;
+
+cleanup:
+    gnutls_pkcs7_deinit(signature);
+    return ret;
+}

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

PATCH v5 12/29 s390x/diag: Implement DIAG 508 subcode 1 for signature verification

In reply to Zhuoying Cai

From: Collin Walling <[email protected]>

DIAG 508 subcode 1 performs signature-verification on signed components. A signed component may be a Linux kernel image, or any other signed binary. **Verification of initrd is not supported.**

The instruction call expects two item-pairs: an address of a device component, an address of the analogous signature file (in PKCS#7 DER format), and their respective lengths. All of this data should be encapsulated within a Diag508SignatureVerificationBlock, with the CertificateStoreInfo fields ignored. The DIAG handler will read from the provided addresses to retrieve the necessary data, parse the signature file, then perform the signature-verification. Because there is no way to correlate a specific certificate to a component, each certificate in the store is tried until either verification succeeds, or all certs have been exhausted.

The subcode value is denoted by setting the second-to-left-most bit of a 2-byte field.

A return code of 1 indicates success, and the index and length of the corresponding certificate will be set in the CertificateStoreInfo portion of the SigVerifBlock. The following values indicate failure:

	0x0102: certificate not available
	0x0202: component data is invalid
	0x0302: signature is not in PKCS#7 format
	0x0402: signature-verification failed
---
 docs/specs/s390x-secure-ipl.rst |   5 ++
 include/hw/s390x/ipl/diag508.h  |  23 +++++++
 target/s390x/diag.c             | 112 +++++++++++++++++++++++++++++++-
 3 files changed, 139 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +5 -0
index 6b3249173f..385f8d85a8 100644
@@ -64,3 +64,8 @@ that requires assistance from QEMU.
 
 Subcode 0 - query installed subcodes
     Returns a 64-bit mask indicating which subcodes are supported.
+
+Subcode 1 - perform signature verification
+    Perform signature-verification on a signed component, using certificates
+    from the certificate store and leveraging qcrypto libraries to perform
+    this operation.
include/hw/s390x/ipl/diag508.h +23 -0
index 6281ad8299..c99c6705c0 100644
@@ -11,5 +11,28 @@
 #define S390X_DIAG508_H
 
 #define DIAG_508_SUBC_QUERY_SUBC    0x0000
+#define DIAG_508_SUBC_SIG_VERIF     0x8000
+
+#define DIAG_508_RC_OK              0x0001
+#define DIAG_508_RC_NO_CERTS        0x0102
+#define DIAG_508_RC_INVAL_COMP_DATA 0x0202
+#define DIAG_508_RC_INVAL_PKCS7_SIG 0x0302
+#define DIAG_508_RC_FAIL_VERIF      0x0402
+
+struct Diag508CertificateStoreInfo {
+    uint8_t  idx;
+    uint8_t  reserved[7];
+    uint64_t len;
+};
+typedef struct Diag508CertificateStoreInfo Diag508CertificateStoreInfo;
+
+struct Diag508SignatureVerificationBlock {
+    Diag508CertificateStoreInfo csi;
+    uint64_t comp_len;
+    uint64_t comp_addr;
+    uint64_t sig_len;
+    uint64_t sig_addr;
+};
+typedef struct Diag508SignatureVerificationBlock Diag508SignatureVerificationBlock;
 
 #endif
target/s390x/diag.c +111 -1

127 lines not on this page · raw message

Signature · 1 line
2.50.1
#41 lore raw

Re: [PATCH v5 12/29] s390x/diag: Implement DIAG 508 subcode 1 for signature verification

Quoted 71 lines · Zhuoying Cai

From: Collin Walling <[email protected]>

DIAG 508 subcode 1 performs signature-verification on signed components. A signed component may be a Linux kernel image, or any other signed binary. **Verification of initrd is not supported.**

The instruction call expects two item-pairs: an address of a device component, an address of the analogous signature file (in PKCS#7 DER format), and their respective lengths. All of this data should be encapsulated within a Diag508SignatureVerificationBlock, with the CertificateStoreInfo fields ignored. The DIAG handler will read from the provided addresses to retrieve the necessary data, parse the signature file, then perform the signature-verification. Because there is no way to correlate a specific certificate to a component, each certificate in the store is tried until either verification succeeds, or all certs have been exhausted.

The subcode value is denoted by setting the second-to-left-most bit of a 2-byte field.

A return code of 1 indicates success, and the index and length of the corresponding certificate will be set in the CertificateStoreInfo portion of the SigVerifBlock. The following values indicate failure:

	0x0102: certificate not available
	0x0202: component data is invalid
	0x0302: signature is not in PKCS#7 format
	0x0402: signature-verification failed
---
  docs/specs/s390x-secure-ipl.rst |   5 ++
  include/hw/s390x/ipl/diag508.h  |  23 +++++++
  target/s390x/diag.c             | 112 +++++++++++++++++++++++++++++++-
  3 files changed, 139 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +5 -0
index 6b3249173f..385f8d85a8 100644
@@ -64,3 +64,8 @@ that requires assistance from QEMU.
 
  Subcode 0 - query installed subcodes
      Returns a 64-bit mask indicating which subcodes are supported.
+
+Subcode 1 - perform signature verification
+    Perform signature-verification on a signed component, using certificates
+    from the certificate store and leveraging qcrypto libraries to perform
+    this operation.
include/hw/s390x/ipl/diag508.h +13 -0
index 6281ad8299..c99c6705c0 100644
@@ -11,5 +11,28 @@
  #define S390X_DIAG508_H
 
  #define DIAG_508_SUBC_QUERY_SUBC    0x0000
+#define DIAG_508_SUBC_SIG_VERIF     0x8000
+
+#define DIAG_508_RC_OK              0x0001
+#define DIAG_508_RC_NO_CERTS        0x0102
+#define DIAG_508_RC_INVAL_COMP_DATA 0x0202
+#define DIAG_508_RC_INVAL_PKCS7_SIG 0x0302
+#define DIAG_508_RC_FAIL_VERIF      0x0402
+
+struct Diag508CertificateStoreInfo {
+    uint8_t  idx;
+    uint8_t  reserved[7];
+    uint64_t len;
+};

include/hw/s390x/ipl/diag508.h line 36

Quoted 10 lines
include/hw/s390x/ipl/diag508.h +10 -0
+typedef struct Diag508CertificateStoreInfo Diag508CertificateStoreInfo;
+
+struct Diag508SignatureVerificationBlock {
+    Diag508CertificateStoreInfo csi;
+    uint64_t comp_len;
+    uint64_t comp_addr;
+    uint64_t sig_len;
+    uint64_t sig_addr;
+};
+typedef struct Diag508SignatureVerificationBlock Diag508SignatureVerificationBlock;

Maybe shorten the above structs to just Diag508CSI and Diag508SVB or similar?

Quoted 125 lines
include/hw/s390x/ipl/diag508.h +0 -0
  #endif
target/s390x/diag.c +104 -1
index 6519a3cedc..2fe25a2c66 100644
@@ -573,9 +573,107 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
      }
  }
 
+static int diag_508_verify_sig(uint8_t *cert, size_t cert_size,
+                              uint8_t *comp, size_t comp_size,
+                              uint8_t *sig, size_t sig_size)
+{
+    g_autofree uint8_t *sig_pem = NULL;
+    size_t sig_size_pem;
+    int rc;
+
+    /*
+     * PKCS#7 signature with DER format
+     * Convert to PEM format for signature verification
+     */
+    rc = qcrypto_pkcs7_convert_sig_pem(sig, sig_size, &sig_pem, &sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    /*
+     * Ignore errors from signature format convertion and verification,
+     * because currently in the certificate lookup process.
+     *
+     * Any error is treated as a verification failure,
+     * and the final result (verified or not) will be reported later.
+     */
+    rc = qcrypto_x509_verify_sig(cert, cert_size,
+                                 comp, comp_size,
+                                 sig_pem, sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+static int handle_diag508_sig_verif(uint64_t addr, size_t csi_size, size_t svb_size,
+                                    S390IPLCertificateStore *qcs)
+{
+    int rc;
+    int verified;
+    uint64_t comp_len, comp_addr;
+    uint64_t sig_len, sig_addr;
+    g_autofree uint8_t *svb_comp = NULL;
+    g_autofree uint8_t *svb_sig = NULL;
+    g_autofree Diag508SignatureVerificationBlock *svb = NULL;
+
+    if (!qcs || !qcs->count) {
+        return DIAG_508_RC_NO_CERTS;
+    }
+
+    svb = g_new0(Diag508SignatureVerificationBlock, 1);
+    cpu_physical_memory_read(addr, svb, svb_size);
+
+    comp_len = be64_to_cpu(svb->comp_len);
+    comp_addr = be64_to_cpu(svb->comp_addr);
+    sig_len = be64_to_cpu(svb->sig_len);
+    sig_addr = be64_to_cpu(svb->sig_addr);
+
+    if (!comp_len || !comp_addr) {
+        return DIAG_508_RC_INVAL_COMP_DATA;
+    }
+
+    if (!sig_len || !sig_addr) {
+        return DIAG_508_RC_INVAL_PKCS7_SIG;
+    }
+
+    svb_comp = g_malloc0(comp_len);
+    cpu_physical_memory_read(comp_addr, svb_comp, comp_len);
+
+    svb_sig = g_malloc0(sig_len);
+    cpu_physical_memory_read(sig_addr, svb_sig, sig_len);
+
+    rc = DIAG_508_RC_FAIL_VERIF;
+    /*
+     * It is uncertain which certificate contains
+     * the analogous key to verify the signed data
+     */
+    for (int i = 0; i < qcs->count; i++) {
+        verified = diag_508_verify_sig(qcs->certs[i].raw,
+                                       qcs->certs[i].size,
+                                       svb_comp, comp_len,
+                                       svb_sig, sig_len);
+        if (verified == 0) {
+            svb->csi.idx = i;
+            svb->csi.len = cpu_to_be64(qcs->certs[i].der_size);
+            cpu_physical_memory_write(addr, &svb->csi, be32_to_cpu(csi_size));
+            rc = DIAG_508_RC_OK;
+            break;
+       }
+    }
+
+    return rc;
+}
+
+QEMU_BUILD_BUG_MSG(sizeof(Diag508SignatureVerificationBlock) != 48,
+                   "size of Diag508SignatureVerificationBlock is wrong");
+
  void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
+    uint64_t addr = env->regs[r1];
      int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
@@ -590,7 +688,19 @@ void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
      switch (subcode) {
      case DIAG_508_SUBC_QUERY_SUBC:
-        rc = 0;
+        rc = DIAG_508_SUBC_SIG_VERIF;
+        break;
+    case DIAG_508_SUBC_SIG_VERIF:
+        size_t csi_size = sizeof(Diag508CertificateStoreInfo);
+        size_t svb_size = sizeof(Diag508SignatureVerificationBlock);
+

target/s390x/diag.c void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 706

Quoted 10 lines
target/s390x/diag.c +7 -0
+        if (!diag_parm_addr_valid(addr, svb_size, false) ||
+            !diag_parm_addr_valid(addr, csi_size, true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        rc = handle_diag508_sig_verif(addr, csi_size, svb_size, qcs);
          break;
      default:
          s390_program_interrupt(env, PGM_SPECIFICATION, ra);

Regards,
Jared Rossi

#42 lore raw

Re: [PATCH v5 12/29] s390x/diag: Implement DIAG 508 subcode 1 for signature verification

Quoted 77 lines · Jared Rossi
Quoted 75 lines · Zhuoying Cai

From: Collin Walling <[email protected]>

DIAG 508 subcode 1 performs signature-verification on signed components. A signed component may be a Linux kernel image, or any other signed binary. **Verification of initrd is not supported.**

The instruction call expects two item-pairs: an address of a device component, an address of the analogous signature file (in PKCS#7 DER format), and their respective lengths. All of this data should be encapsulated within a Diag508SignatureVerificationBlock, with the CertificateStoreInfo fields ignored. The DIAG handler will read from the provided addresses to retrieve the necessary data, parse the signature file, then perform the signature-verification. Because there is no way to correlate a specific certificate to a component, each certificate in the store is tried until either verification succeeds, or all certs have been exhausted.

The subcode value is denoted by setting the second-to-left-most bit of a 2-byte field.

A return code of 1 indicates success, and the index and length of the corresponding certificate will be set in the CertificateStoreInfo portion of the SigVerifBlock. The following values indicate failure:

	0x0102: certificate not available
	0x0202: component data is invalid
	0x0302: signature is not in PKCS#7 format
	0x0402: signature-verification failed
---
  docs/specs/s390x-secure-ipl.rst |   5 ++
  include/hw/s390x/ipl/diag508.h  |  23 +++++++
  target/s390x/diag.c             | 112 +++++++++++++++++++++++++++++++-
  3 files changed, 139 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +5 -0
index 6b3249173f..385f8d85a8 100644
@@ -64,3 +64,8 @@ that requires assistance from QEMU.
 
  Subcode 0 - query installed subcodes
      Returns a 64-bit mask indicating which subcodes are supported.
+
+Subcode 1 - perform signature verification
+    Perform signature-verification on a signed component, using certificates
+    from the certificate store and leveraging qcrypto libraries to perform
+    this operation.
include/hw/s390x/ipl/diag508.h +17 -0
index 6281ad8299..c99c6705c0 100644
@@ -11,5 +11,28 @@
  #define S390X_DIAG508_H
 
  #define DIAG_508_SUBC_QUERY_SUBC    0x0000
+#define DIAG_508_SUBC_SIG_VERIF     0x8000
+
+#define DIAG_508_RC_OK              0x0001
+#define DIAG_508_RC_NO_CERTS        0x0102
+#define DIAG_508_RC_INVAL_COMP_DATA 0x0202
+#define DIAG_508_RC_INVAL_PKCS7_SIG 0x0302
+#define DIAG_508_RC_FAIL_VERIF      0x0402
+
+struct Diag508CertificateStoreInfo {
+    uint8_t  idx;
+    uint8_t  reserved[7];
+    uint64_t len;
+};
+typedef struct Diag508CertificateStoreInfo Diag508CertificateStoreInfo;
+
+struct Diag508SignatureVerificationBlock {
+    Diag508CertificateStoreInfo csi;
Quoted 9 lines

include/hw/s390x/ipl/diag508.h line 36

Quoted 6 lines
include/hw/s390x/ipl/diag508.h +6 -0
+    uint64_t comp_len;
+    uint64_t comp_addr;
+    uint64_t sig_len;
+    uint64_t sig_addr;
+};
+typedef struct Diag508SignatureVerificationBlock Diag508SignatureVerificationBlock;

Maybe shorten the above structs to just Diag508CSI and Diag508SVB or similar?

On another note, I played around with updating the 508 code to make the structures similar to what we'd see in the PoPs (also made other changes based on feedback I left to Joy on other patches). I came up with this design:

struct Diag508SigVerifBlock {
    uint32_t length;
    uint8_t reserved0[3];
    uint8_t version;
    uint32_t reserved[2];
    uint8_t cert_store_index;
    uint8_t reserved1[7];
    uint64_t cert_len;
    uint64_t comp_len;
    uint64_t comp_addr;
    uint64_t sig_len;
    uint64_t sig_addr;
};

typedef struct Diag508SigVerifBlock Diag508SigVerifBlock;

This condenses the two structures while also making it 64 bytes.

Do you think this is a good idea?

Quoted 137 lines
Quoted 125 lines
include/hw/s390x/ipl/diag508.h +0 -0
  #endif
target/s390x/diag.c +104 -1
index 6519a3cedc..2fe25a2c66 100644
@@ -573,9 +573,107 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
      }
  }
 
+static int diag_508_verify_sig(uint8_t *cert, size_t cert_size,
+                              uint8_t *comp, size_t comp_size,
+                              uint8_t *sig, size_t sig_size)
+{
+    g_autofree uint8_t *sig_pem = NULL;
+    size_t sig_size_pem;
+    int rc;
+
+    /*
+     * PKCS#7 signature with DER format
+     * Convert to PEM format for signature verification
+     */
+    rc = qcrypto_pkcs7_convert_sig_pem(sig, sig_size, &sig_pem, &sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    /*
+     * Ignore errors from signature format convertion and verification,
+     * because currently in the certificate lookup process.
+     *
+     * Any error is treated as a verification failure,
+     * and the final result (verified or not) will be reported later.
+     */
+    rc = qcrypto_x509_verify_sig(cert, cert_size,
+                                 comp, comp_size,
+                                 sig_pem, sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+static int handle_diag508_sig_verif(uint64_t addr, size_t csi_size, size_t svb_size,
+                                    S390IPLCertificateStore *qcs)
+{
+    int rc;
+    int verified;
+    uint64_t comp_len, comp_addr;
+    uint64_t sig_len, sig_addr;
+    g_autofree uint8_t *svb_comp = NULL;
+    g_autofree uint8_t *svb_sig = NULL;
+    g_autofree Diag508SignatureVerificationBlock *svb = NULL;
+
+    if (!qcs || !qcs->count) {
+        return DIAG_508_RC_NO_CERTS;
+    }
+
+    svb = g_new0(Diag508SignatureVerificationBlock, 1);
+    cpu_physical_memory_read(addr, svb, svb_size);
+
+    comp_len = be64_to_cpu(svb->comp_len);
+    comp_addr = be64_to_cpu(svb->comp_addr);
+    sig_len = be64_to_cpu(svb->sig_len);
+    sig_addr = be64_to_cpu(svb->sig_addr);
+
+    if (!comp_len || !comp_addr) {
+        return DIAG_508_RC_INVAL_COMP_DATA;
+    }
+
+    if (!sig_len || !sig_addr) {
+        return DIAG_508_RC_INVAL_PKCS7_SIG;
+    }
+
+    svb_comp = g_malloc0(comp_len);
+    cpu_physical_memory_read(comp_addr, svb_comp, comp_len);
+
+    svb_sig = g_malloc0(sig_len);
+    cpu_physical_memory_read(sig_addr, svb_sig, sig_len);
+
+    rc = DIAG_508_RC_FAIL_VERIF;
+    /*
+     * It is uncertain which certificate contains
+     * the analogous key to verify the signed data
+     */
+    for (int i = 0; i < qcs->count; i++) {
+        verified = diag_508_verify_sig(qcs->certs[i].raw,
+                                       qcs->certs[i].size,
+                                       svb_comp, comp_len,
+                                       svb_sig, sig_len);
+        if (verified == 0) {
+            svb->csi.idx = i;
+            svb->csi.len = cpu_to_be64(qcs->certs[i].der_size);
+            cpu_physical_memory_write(addr, &svb->csi, be32_to_cpu(csi_size));
+            rc = DIAG_508_RC_OK;
+            break;
+       }
+    }
+
+    return rc;
+}
+
+QEMU_BUILD_BUG_MSG(sizeof(Diag508SignatureVerificationBlock) != 48,
+                   "size of Diag508SignatureVerificationBlock is wrong");
+
  void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
+    uint64_t addr = env->regs[r1];
      int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
@@ -590,7 +688,19 @@ void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
      switch (subcode) {
      case DIAG_508_SUBC_QUERY_SUBC:
-        rc = 0;
+        rc = DIAG_508_SUBC_SIG_VERIF;
+        break;
+    case DIAG_508_SUBC_SIG_VERIF:
+        size_t csi_size = sizeof(Diag508CertificateStoreInfo);
+        size_t svb_size = sizeof(Diag508SignatureVerificationBlock);
+

target/s390x/diag.c void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 706

Quoted 10 lines
target/s390x/diag.c +7 -0
+        if (!diag_parm_addr_valid(addr, svb_size, false) ||
+            !diag_parm_addr_valid(addr, csi_size, true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        rc = handle_diag508_sig_verif(addr, csi_size, svb_size, qcs);
          break;
      default:
          s390_program_interrupt(env, PGM_SPECIFICATION, ra);

Regards,
Jared Rossi

Signature · 2 lines
Regards,
  Collin
#43 lore raw

Re: [PATCH v5 12/29] s390x/diag: Implement DIAG 508 subcode 1 for signature verification

In reply to Zhuoying Cai
Quoted 105 lines · Zhuoying Cai

From: Collin Walling <[email protected]>

DIAG 508 subcode 1 performs signature-verification on signed components. A signed component may be a Linux kernel image, or any other signed binary. **Verification of initrd is not supported.**

The instruction call expects two item-pairs: an address of a device component, an address of the analogous signature file (in PKCS#7 DER format), and their respective lengths. All of this data should be encapsulated within a Diag508SignatureVerificationBlock, with the CertificateStoreInfo fields ignored. The DIAG handler will read from the provided addresses to retrieve the necessary data, parse the signature file, then perform the signature-verification. Because there is no way to correlate a specific certificate to a component, each certificate in the store is tried until either verification succeeds, or all certs have been exhausted.

The subcode value is denoted by setting the second-to-left-most bit of a 2-byte field.

A return code of 1 indicates success, and the index and length of the corresponding certificate will be set in the CertificateStoreInfo portion of the SigVerifBlock. The following values indicate failure:

	0x0102: certificate not available
	0x0202: component data is invalid
	0x0302: signature is not in PKCS#7 format
	0x0402: signature-verification failed
---
  docs/specs/s390x-secure-ipl.rst |   5 ++
  include/hw/s390x/ipl/diag508.h  |  23 +++++++
  target/s390x/diag.c             | 112 +++++++++++++++++++++++++++++++-
  3 files changed, 139 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +5 -0
index 6b3249173f..385f8d85a8 100644
@@ -64,3 +64,8 @@ that requires assistance from QEMU.
 
  Subcode 0 - query installed subcodes
      Returns a 64-bit mask indicating which subcodes are supported.
+
+Subcode 1 - perform signature verification
+    Perform signature-verification on a signed component, using certificates
+    from the certificate store and leveraging qcrypto libraries to perform
+    this operation.
include/hw/s390x/ipl/diag508.h +23 -0
index 6281ad8299..c99c6705c0 100644
@@ -11,5 +11,28 @@
  #define S390X_DIAG508_H
 
  #define DIAG_508_SUBC_QUERY_SUBC    0x0000
+#define DIAG_508_SUBC_SIG_VERIF     0x8000
+
+#define DIAG_508_RC_OK              0x0001
+#define DIAG_508_RC_NO_CERTS        0x0102
+#define DIAG_508_RC_INVAL_COMP_DATA 0x0202
+#define DIAG_508_RC_INVAL_PKCS7_SIG 0x0302
+#define DIAG_508_RC_FAIL_VERIF      0x0402
+
+struct Diag508CertificateStoreInfo {
+    uint8_t  idx;
+    uint8_t  reserved[7];
+    uint64_t len;
+};
+typedef struct Diag508CertificateStoreInfo Diag508CertificateStoreInfo;
+
+struct Diag508SignatureVerificationBlock {
+    Diag508CertificateStoreInfo csi;
+    uint64_t comp_len;
+    uint64_t comp_addr;
+    uint64_t sig_len;
+    uint64_t sig_addr;
+};
+typedef struct Diag508SignatureVerificationBlock Diag508SignatureVerificationBlock;
 
  #endif
target/s390x/diag.c +14 -0
index 6519a3cedc..2fe25a2c66 100644
@@ -573,9 +573,107 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
      }
  }
 
+static int diag_508_verify_sig(uint8_t *cert, size_t cert_size,
+                              uint8_t *comp, size_t comp_size,
+                              uint8_t *sig, size_t sig_size)
+{
+    g_autofree uint8_t *sig_pem = NULL;
+    size_t sig_size_pem;
+    int rc;
+
+    /*
+     * PKCS#7 signature with DER format
+     * Convert to PEM format for signature verification
+     */
+    rc = qcrypto_pkcs7_convert_sig_pem(sig, sig_size, &sig_pem, &sig_size_pem, NULL);
+    if (rc < 0) {

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 599

Quoted 10 lines
target/s390x/diag.c +10 -0
+        return -1;
+    }
+
+    /*
+     * Ignore errors from signature format convertion and verification,
+     * because currently in the certificate lookup process.
+     *
+     * Any error is treated as a verification failure,
+     * and the final result (verified or not) will be reported later.
+     */

The comment here seems misleading as we are checking the return code from qcrypto_x509_verify_sig and not ignoring the error here. Is it meant for the handle_diag508_sig_verif function where we are looping through the certs?

Thanks Farhan

Quoted 101 lines
target/s390x/diag.c +87 -1
+    rc = qcrypto_x509_verify_sig(cert, cert_size,
+                                 comp, comp_size,
+                                 sig_pem, sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+static int handle_diag508_sig_verif(uint64_t addr, size_t csi_size, size_t svb_size,
+                                    S390IPLCertificateStore *qcs)
+{
+    int rc;
+    int verified;
+    uint64_t comp_len, comp_addr;
+    uint64_t sig_len, sig_addr;
+    g_autofree uint8_t *svb_comp = NULL;
+    g_autofree uint8_t *svb_sig = NULL;
+    g_autofree Diag508SignatureVerificationBlock *svb = NULL;
+
+    if (!qcs || !qcs->count) {
+        return DIAG_508_RC_NO_CERTS;
+    }
+
+    svb = g_new0(Diag508SignatureVerificationBlock, 1);
+    cpu_physical_memory_read(addr, svb, svb_size);
+
+    comp_len = be64_to_cpu(svb->comp_len);
+    comp_addr = be64_to_cpu(svb->comp_addr);
+    sig_len = be64_to_cpu(svb->sig_len);
+    sig_addr = be64_to_cpu(svb->sig_addr);
+
+    if (!comp_len || !comp_addr) {
+        return DIAG_508_RC_INVAL_COMP_DATA;
+    }
+
+    if (!sig_len || !sig_addr) {
+        return DIAG_508_RC_INVAL_PKCS7_SIG;
+    }
+
+    svb_comp = g_malloc0(comp_len);
+    cpu_physical_memory_read(comp_addr, svb_comp, comp_len);
+
+    svb_sig = g_malloc0(sig_len);
+    cpu_physical_memory_read(sig_addr, svb_sig, sig_len);
+
+    rc = DIAG_508_RC_FAIL_VERIF;
+    /*
+     * It is uncertain which certificate contains
+     * the analogous key to verify the signed data
+     */
+    for (int i = 0; i < qcs->count; i++) {
+        verified = diag_508_verify_sig(qcs->certs[i].raw,
+                                       qcs->certs[i].size,
+                                       svb_comp, comp_len,
+                                       svb_sig, sig_len);
+        if (verified == 0) {
+            svb->csi.idx = i;
+            svb->csi.len = cpu_to_be64(qcs->certs[i].der_size);
+            cpu_physical_memory_write(addr, &svb->csi, be32_to_cpu(csi_size));
+            rc = DIAG_508_RC_OK;
+            break;
+       }
+    }
+
+    return rc;
+}
+
+QEMU_BUILD_BUG_MSG(sizeof(Diag508SignatureVerificationBlock) != 48,
+                   "size of Diag508SignatureVerificationBlock is wrong");
+
  void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
+    uint64_t addr = env->regs[r1];
      int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
@@ -590,7 +688,19 @@ void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
      switch (subcode) {
      case DIAG_508_SUBC_QUERY_SUBC:
-        rc = 0;
+        rc = DIAG_508_SUBC_SIG_VERIF;
+        break;
+    case DIAG_508_SUBC_SIG_VERIF:
+        size_t csi_size = sizeof(Diag508CertificateStoreInfo);
+        size_t svb_size = sizeof(Diag508SignatureVerificationBlock);
+
+        if (!diag_parm_addr_valid(addr, svb_size, false) ||
+            !diag_parm_addr_valid(addr, csi_size, true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        rc = handle_diag508_sig_verif(addr, csi_size, svb_size, qcs);
          break;
      default:
          s390_program_interrupt(env, PGM_SPECIFICATION, ra);
#44 lore raw

Re: [PATCH v5 12/29] s390x/diag: Implement DIAG 508 subcode 1 for signature verification

Quoted 123 lines · Farhan Ali
Quoted 105 lines · Zhuoying Cai

From: Collin Walling <[email protected]>

DIAG 508 subcode 1 performs signature-verification on signed components. A signed component may be a Linux kernel image, or any other signed binary. **Verification of initrd is not supported.**

The instruction call expects two item-pairs: an address of a device component, an address of the analogous signature file (in PKCS#7 DER format), and their respective lengths. All of this data should be encapsulated within a Diag508SignatureVerificationBlock, with the CertificateStoreInfo fields ignored. The DIAG handler will read from the provided addresses to retrieve the necessary data, parse the signature file, then perform the signature-verification. Because there is no way to correlate a specific certificate to a component, each certificate in the store is tried until either verification succeeds, or all certs have been exhausted.

The subcode value is denoted by setting the second-to-left-most bit of a 2-byte field.

A return code of 1 indicates success, and the index and length of the corresponding certificate will be set in the CertificateStoreInfo portion of the SigVerifBlock. The following values indicate failure:

	0x0102: certificate not available
	0x0202: component data is invalid
	0x0302: signature is not in PKCS#7 format
	0x0402: signature-verification failed
---
  docs/specs/s390x-secure-ipl.rst |   5 ++
  include/hw/s390x/ipl/diag508.h  |  23 +++++++
  target/s390x/diag.c             | 112 +++++++++++++++++++++++++++++++-
  3 files changed, 139 insertions(+), 1 deletion(-)
docs/specs/s390x-secure-ipl.rst +5 -0
index 6b3249173f..385f8d85a8 100644
@@ -64,3 +64,8 @@ that requires assistance from QEMU.
 
  Subcode 0 - query installed subcodes
      Returns a 64-bit mask indicating which subcodes are supported.
+
+Subcode 1 - perform signature verification
+    Perform signature-verification on a signed component, using certificates
+    from the certificate store and leveraging qcrypto libraries to perform
+    this operation.
include/hw/s390x/ipl/diag508.h +23 -0
index 6281ad8299..c99c6705c0 100644
@@ -11,5 +11,28 @@
  #define S390X_DIAG508_H
 
  #define DIAG_508_SUBC_QUERY_SUBC    0x0000
+#define DIAG_508_SUBC_SIG_VERIF     0x8000
+
+#define DIAG_508_RC_OK              0x0001
+#define DIAG_508_RC_NO_CERTS        0x0102
+#define DIAG_508_RC_INVAL_COMP_DATA 0x0202
+#define DIAG_508_RC_INVAL_PKCS7_SIG 0x0302
+#define DIAG_508_RC_FAIL_VERIF      0x0402
+
+struct Diag508CertificateStoreInfo {
+    uint8_t  idx;
+    uint8_t  reserved[7];
+    uint64_t len;
+};
+typedef struct Diag508CertificateStoreInfo Diag508CertificateStoreInfo;
+
+struct Diag508SignatureVerificationBlock {
+    Diag508CertificateStoreInfo csi;
+    uint64_t comp_len;
+    uint64_t comp_addr;
+    uint64_t sig_len;
+    uint64_t sig_addr;
+};
+typedef struct Diag508SignatureVerificationBlock Diag508SignatureVerificationBlock;
 
  #endif
target/s390x/diag.c +14 -0
index 6519a3cedc..2fe25a2c66 100644
@@ -573,9 +573,107 @@ void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
      }
  }
 
+static int diag_508_verify_sig(uint8_t *cert, size_t cert_size,
+                              uint8_t *comp, size_t comp_size,
+                              uint8_t *sig, size_t sig_size)
+{
+    g_autofree uint8_t *sig_pem = NULL;
+    size_t sig_size_pem;
+    int rc;
+
+    /*
+     * PKCS#7 signature with DER format
+     * Convert to PEM format for signature verification
+     */
+    rc = qcrypto_pkcs7_convert_sig_pem(sig, sig_size, &sig_pem, &sig_size_pem, NULL);
+    if (rc < 0) {

target/s390x/diag.c void handle_diag_320(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra) · line 599

Quoted 10 lines
target/s390x/diag.c +10 -0
+        return -1;
+    }
+
+    /*
+     * Ignore errors from signature format convertion and verification,
+     * because currently in the certificate lookup process.
+     *
+     * Any error is treated as a verification failure,
+     * and the final result (verified or not) will be reported later.
+     */

The comment here seems misleading as we are checking the return code from qcrypto_x509_verify_sig and not ignoring the error here. Is it meant for the handle_diag508_sig_verif function where we are looping through the certs?

Quoted 2 lines

Thanks Farhan

Thank you for pointing it out. This comment is meant for when iterating over the certificates in handle_diag508_sig_verif(). I'll move it in the next version.

Quoted 101 lines
Quoted 101 lines
target/s390x/diag.c +87 -1
+    rc = qcrypto_x509_verify_sig(cert, cert_size,
+                                 comp, comp_size,
+                                 sig_pem, sig_size_pem, NULL);
+    if (rc < 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+static int handle_diag508_sig_verif(uint64_t addr, size_t csi_size, size_t svb_size,
+                                    S390IPLCertificateStore *qcs)
+{
+    int rc;
+    int verified;
+    uint64_t comp_len, comp_addr;
+    uint64_t sig_len, sig_addr;
+    g_autofree uint8_t *svb_comp = NULL;
+    g_autofree uint8_t *svb_sig = NULL;
+    g_autofree Diag508SignatureVerificationBlock *svb = NULL;
+
+    if (!qcs || !qcs->count) {
+        return DIAG_508_RC_NO_CERTS;
+    }
+
+    svb = g_new0(Diag508SignatureVerificationBlock, 1);
+    cpu_physical_memory_read(addr, svb, svb_size);
+
+    comp_len = be64_to_cpu(svb->comp_len);
+    comp_addr = be64_to_cpu(svb->comp_addr);
+    sig_len = be64_to_cpu(svb->sig_len);
+    sig_addr = be64_to_cpu(svb->sig_addr);
+
+    if (!comp_len || !comp_addr) {
+        return DIAG_508_RC_INVAL_COMP_DATA;
+    }
+
+    if (!sig_len || !sig_addr) {
+        return DIAG_508_RC_INVAL_PKCS7_SIG;
+    }
+
+    svb_comp = g_malloc0(comp_len);
+    cpu_physical_memory_read(comp_addr, svb_comp, comp_len);
+
+    svb_sig = g_malloc0(sig_len);
+    cpu_physical_memory_read(sig_addr, svb_sig, sig_len);
+
+    rc = DIAG_508_RC_FAIL_VERIF;
+    /*
+     * It is uncertain which certificate contains
+     * the analogous key to verify the signed data
+     */
+    for (int i = 0; i < qcs->count; i++) {
+        verified = diag_508_verify_sig(qcs->certs[i].raw,
+                                       qcs->certs[i].size,
+                                       svb_comp, comp_len,
+                                       svb_sig, sig_len);
+        if (verified == 0) {
+            svb->csi.idx = i;
+            svb->csi.len = cpu_to_be64(qcs->certs[i].der_size);
+            cpu_physical_memory_write(addr, &svb->csi, be32_to_cpu(csi_size));
+            rc = DIAG_508_RC_OK;
+            break;
+       }
+    }
+
+    return rc;
+}
+
+QEMU_BUILD_BUG_MSG(sizeof(Diag508SignatureVerificationBlock) != 48,
+                   "size of Diag508SignatureVerificationBlock is wrong");
+
  void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
  {
+    S390IPLCertificateStore *qcs = s390_ipl_get_certificate_store();
      uint64_t subcode = env->regs[r3];
+    uint64_t addr = env->regs[r1];
      int rc;
 
      if (env->psw.mask & PSW_MASK_PSTATE) {
@@ -590,7 +688,19 @@ void handle_diag_508(CPUS390XState *env, uint64_t r1, uint64_t r3, uintptr_t ra)
 
      switch (subcode) {
      case DIAG_508_SUBC_QUERY_SUBC:
-        rc = 0;
+        rc = DIAG_508_SUBC_SIG_VERIF;
+        break;
+    case DIAG_508_SUBC_SIG_VERIF:
+        size_t csi_size = sizeof(Diag508CertificateStoreInfo);
+        size_t svb_size = sizeof(Diag508SignatureVerificationBlock);
+
+        if (!diag_parm_addr_valid(addr, svb_size, false) ||
+            !diag_parm_addr_valid(addr, csi_size, true)) {
+            s390_program_interrupt(env, PGM_ADDRESSING, ra);
+            return;
+        }
+
+        rc = handle_diag508_sig_verif(addr, csi_size, svb_size, qcs);
          break;
      default:
          s390_program_interrupt(env, PGM_SPECIFICATION, ra);
#45 lore raw

PATCH v5 13/29 pc-bios/s390-ccw: Introduce IPL Information Report Block (IIRB)

In reply to Zhuoying Cai

The IPL information report block (IIRB) contains information used to locate IPL records and to report the results of signature verification of one or more secure components of the load device.

IIRB is stored immediately following the IPL Parameter Block. Results on component verification in any case (failure or success) are stored.

---
 docs/specs/s390x-secure-ipl.rst | 14 ++++++++
 pc-bios/s390-ccw/iplb.h         | 62 +++++++++++++++++++++++++++++++++
 2 files changed, 76 insertions(+)
docs/specs/s390x-secure-ipl.rst +14 -0
index 385f8d85a8..4bc330c399 100644
@@ -69,3 +69,17 @@ Subcode 1 - perform signature verification
     Perform signature-verification on a signed component, using certificates
     from the certificate store and leveraging qcrypto libraries to perform
     this operation.
+
+
+IPL Information Report Block
+----------------------------
+
+The IPL Parameter Block (IPLPB), utilized for IPL operation, is extended with an
+IPL Information Report Block (IIRB), which contains the results from secure IPL
+operations such as:
+
+* component data
+* verification results
+* certificate data
+
+The guest kernel will inspect the IIRB and build the keyring.
pc-bios/s390-ccw/iplb.h +62 -0

68 lines not on this page · raw message

Signature · 1 line
2.50.1
#46 lore raw

PATCH v5 14/29 pc-bios/s390-ccw: Define memory for IPLB and convert IPLB to pointers

In reply to Zhuoying Cai

Define a memory space for both IPL Parameter Block (IPLB) and IPL Information Report Block (IIRB) since IIRB is stored immediately following IPLB.

Convert IPLB to pointer and it points to the start of the defined memory space. IIRB points to the end of IPLB.

---
 pc-bios/s390-ccw/iplb.h     | 12 ++++++++++--
 pc-bios/s390-ccw/jump2ipl.c |  6 +++---
 pc-bios/s390-ccw/main.c     | 34 +++++++++++++++++++---------------
 pc-bios/s390-ccw/netmain.c  |  8 ++++----
 4 files changed, 36 insertions(+), 24 deletions(-)
pc-bios/s390-ccw/iplb.h +10 -2
index bdbc733e16..11302e004d 100644
@@ -20,7 +20,7 @@
 #include <string.h>
 
 extern QemuIplParameters qipl;
-extern IplParameterBlock iplb __attribute__((__aligned__(PAGE_SIZE)));
+extern IplParameterBlock *iplb;
 extern bool have_iplb;
 
 struct IplInfoReportBlockHeader {
@@ -85,6 +85,14 @@ struct IplInfoReportBlock {
 } __attribute__ ((packed));
 typedef struct IplInfoReportBlock IplInfoReportBlock;
 
+struct IplBlocks {
+    IplParameterBlock   iplb;
+    IplInfoReportBlock  iirb;
+} __attribute__ ((packed));
+typedef struct IplBlocks IplBlocks;
+
+extern IplBlocks ipl_data __attribute__((__aligned__(PAGE_SIZE)));
+
 #define S390_IPL_TYPE_FCP 0x00
 #define S390_IPL_TYPE_CCW 0x02
 #define S390_IPL_TYPE_QEMU_SCSI 0xff
@@ -127,7 +135,7 @@ static inline bool load_next_iplb(void)
 
     qipl.index++;
     next_iplb = (IplParameterBlock *) qipl.next_iplb;
-    memcpy(&iplb, next_iplb, sizeof(IplParameterBlock));
+    memcpy(iplb, next_iplb, sizeof(IplParameterBlock));
 
     qipl.chain_len--;
     qipl.next_iplb = qipl.next_iplb + sizeof(IplParameterBlock);
pc-bios/s390-ccw/jump2ipl.c +3 -3
index 86321d0f46..fa2ca5cbe1 100644
@@ -43,11 +43,11 @@ int jump_to_IPL_code(uint64_t address)
      * The IPLB for QEMU SCSI type devices must be rebuilt during re-ipl. The
      * iplb.devno is set to the boot position of the target SCSI device.
      */
-    if (iplb.pbt == S390_IPL_TYPE_QEMU_SCSI) {
-        iplb.devno = qipl.index;
+    if (iplb->pbt == S390_IPL_TYPE_QEMU_SCSI) {
+        iplb->devno = qipl.index;
     }
 
-    if (have_iplb && !set_iplb(&iplb)) {
+    if (have_iplb && !set_iplb(iplb)) {
         panic("Failed to set IPLB");
     }
 
pc-bios/s390-ccw/main.c +19 -15
index 76bf743900..c9328f1c51 100644
@@ -22,7 +22,9 @@
 static SubChannelId blk_schid = { .one = 1 };
 static char loadparm_str[LOADPARM_LEN + 1];
 QemuIplParameters qipl;
-IplParameterBlock iplb __attribute__((__aligned__(PAGE_SIZE)));
+/* Ensure that IPLB and IIRB are page aligned and sequential in memory */
+IplBlocks ipl_data;
+IplParameterBlock *iplb;
 bool have_iplb;
 static uint16_t cutype;
 LowCore *lowcore; /* Yes, this *is* a pointer to address 0 */
@@ -51,7 +53,7 @@ void write_subsystem_identification(void)
 void write_iplb_location(void)
 {
     if (cutype == CU_TYPE_VIRTIO && virtio_get_device_type() != VIRTIO_ID_NET) {
-        lowcore->ptr_iplb = ptr2u32(&iplb);
+        lowcore->ptr_iplb = ptr2u32(iplb);
     }
 }
 
@@ -162,7 +164,7 @@ static void menu_setup(void)
         return;
     }
 
-    switch (iplb.pbt) {
+    switch (iplb->pbt) {
     case S390_IPL_TYPE_CCW:
     case S390_IPL_TYPE_QEMU_SCSI:
         menu_set_parms(qipl.qipl_flags & BOOT_MENU_FLAG_MASK,
@@ -191,8 +193,8 @@ static void boot_setup(void)
 {
     char lpmsg[] = "LOADPARM=[________]\n";
 
-    if (have_iplb && memcmp(iplb.loadparm, NO_LOADPARM, LOADPARM_LEN) != 0) {
-        ebcdic_to_ascii((char *) iplb.loadparm, loadparm_str, LOADPARM_LEN);
+    if (have_iplb && memcmp(iplb->loadparm, NO_LOADPARM, LOADPARM_LEN) != 0) {
+        ebcdic_to_ascii((char *) iplb->loadparm, loadparm_str, LOADPARM_LEN);
     } else {
         sclp_get_loadparm_ascii(loadparm_str);
     }
@@ -216,21 +218,21 @@ static bool find_boot_device(void)
     VDev *vdev = virtio_get_device();
     bool found = false;
 
-    switch (iplb.pbt) {
+    switch (iplb->pbt) {
     case S390_IPL_TYPE_CCW:
         vdev->scsi_device_selected = false;
-        debug_print_int("device no. ", iplb.ccw.devno);
-        blk_schid.ssid = iplb.ccw.ssid & 0x3;
+        debug_print_int("device no. ", iplb->ccw.devno);
+        blk_schid.ssid = iplb->ccw.ssid & 0x3;
         debug_print_int("ssid ", blk_schid.ssid);
-        found = find_subch(iplb.ccw.devno);
+        found = find_subch(iplb->ccw.devno);
         break;
     case S390_IPL_TYPE_QEMU_SCSI:
         vdev->scsi_device_selected = true;
-        vdev->selected_scsi_device.channel = iplb.scsi.channel;
-        vdev->selected_scsi_device.target = iplb.scsi.target;
-        vdev->selected_scsi_device.lun = iplb.scsi.lun;
-        blk_schid.ssid = iplb.scsi.ssid & 0x3;
-        found = find_subch(iplb.scsi.devno);
+        vdev->selected_scsi_device.channel = iplb->scsi.channel;
+        vdev->selected_scsi_device.target = iplb->scsi.target;
+        vdev->selected_scsi_device.lun = iplb->scsi.lun;
+        blk_schid.ssid = iplb->scsi.ssid & 0x3;
+        found = find_subch(iplb->scsi.devno);
         break;
     default:
         puts("Unsupported IPLB");
@@ -311,10 +313,12 @@ static void probe_boot_device(void)
 
 void main(void)
 {
+    iplb = &ipl_data.iplb;
+
     copy_qipl();
     sclp_setup();
     css_setup();
-    have_iplb = store_iplb(&iplb);
+    have_iplb = store_iplb(iplb);
     if (!have_iplb) {
         boot_setup();
         probe_boot_device();
pc-bios/s390-ccw/netmain.c +4 -4
index a9521dff41..457fbc3095 100644
@@ -528,11 +528,11 @@ static bool virtio_setup(void)
      */
     enable_mss_facility();
 
-    if (have_iplb || store_iplb(&iplb)) {
-        IPL_assert(iplb.pbt == S390_IPL_TYPE_CCW, "IPL_TYPE_CCW expected");
-        dev_no = iplb.ccw.devno;
+    if (have_iplb || store_iplb(iplb)) {
+        IPL_assert(iplb->pbt == S390_IPL_TYPE_CCW, "IPL_TYPE_CCW expected");
+        dev_no = iplb->ccw.devno;
         debug_print_int("device no. ", dev_no);
-        net_schid.ssid = iplb.ccw.ssid & 0x3;
+        net_schid.ssid = iplb->ccw.ssid & 0x3;
         debug_print_int("ssid ", net_schid.ssid);
         found = find_net_dev(&schib, dev_no);
     } else {
Signature · 1 line
2.50.1
#47 lore raw

PATCH v5 15/29 hw/s390x/ipl: Add IPIB flags to IPL Parameter Block

In reply to Zhuoying Cai

Add IPIB flags to IPL Parameter Block to determine if IPL needs to perform securely and if IPL Information Report Block (IIRB) exists.

Move DIAG308 flags to a separated header file and add flags for secure IPL.

Secure boot in audit mode will perform if certificate(s) exist in the key store. IIRB will exist and results of verification will be stored in IIRB.

---
 hw/s390x/ipl.c                 | 20 ++++++++++++++++++++
 hw/s390x/ipl.h                 | 17 -----------------
 include/hw/s390x/ipl/diag308.h | 34 ++++++++++++++++++++++++++++++++++
 include/hw/s390x/ipl/qipl.h    |  5 ++++-
 4 files changed, 58 insertions(+), 18 deletions(-)
 create mode 100644 include/hw/s390x/ipl/diag308.h
hw/s390x/ipl.c +20 -0
index 186be923d7..8ac0cee73d 100644
@@ -430,6 +430,13 @@ S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
     return &ipl->cert_store;
 }
 
+static bool s390_has_certificate(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return ipl->cert_store.count > 0;
+}
+
 static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
 {
     CcwDevice *ccw_dev = NULL;
@@ -487,6 +494,19 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
         s390_ipl_convert_loadparm((char *)lp, iplb->loadparm);
         iplb->flags |= DIAG308_FLAGS_LP_VALID;
 
+        /*
+         * Secure boot in audit mode will perform
+         * if certificate(s) exist in the key store.
+         *
+         * IPL Information Report Block (IIRB) will exist
+         * for secure boot in audit mode.
+         *
+         * Results of secure boot will be stored in IIRB.
+         */
+        if (s390_has_certificate()) {
+            iplb->hdr_flags |= DIAG308_IPIB_FLAGS_IPLIR;
+        }
+
         return true;
     }
 
hw/s390x/ipl.h +0 -17
index e26fc1cd6a..3b8cc5474e 100644
@@ -23,7 +23,6 @@
 #include "qom/object.h"
 #include "target/s390x/kvm/pv.h"
 
-#define DIAG308_FLAGS_LP_VALID 0x80
 #define MAX_BOOT_DEVS 8 /* Max number of devices that may have a bootindex */
 
 void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp);
@@ -91,22 +90,6 @@ struct S390IPLState {
 };
 QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong");
 
-#define DIAG_308_RC_OK              0x0001
-#define DIAG_308_RC_NO_CONF         0x0102
-#define DIAG_308_RC_INVALID         0x0402
-#define DIAG_308_RC_NO_PV_CONF      0x0902
-#define DIAG_308_RC_INVAL_FOR_PV    0x0a02
-
-#define DIAG308_RESET_MOD_CLR       0
-#define DIAG308_RESET_LOAD_NORM     1
-#define DIAG308_LOAD_CLEAR          3
-#define DIAG308_LOAD_NORMAL_DUMP    4
-#define DIAG308_SET                 5
-#define DIAG308_STORE               6
-#define DIAG308_PV_SET              8
-#define DIAG308_PV_STORE            9
-#define DIAG308_PV_START            10
-
 #define S390_IPL_TYPE_FCP 0x00
 #define S390_IPL_TYPE_CCW 0x02
 #define S390_IPL_TYPE_PV 0x05
include/hw/s390x/ipl/diag308.h new file +34 -0
new file mode 100644
index 0000000000..6e62f29215
@@ -0,0 +1,34 @@
+/*
+ * S/390 DIAGNOSE 308 definitions and structures
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef S390X_DIAG308_H
+#define S390X_DIAG308_H
+
+#define DIAG_308_RC_OK              0x0001
+#define DIAG_308_RC_NO_CONF         0x0102
+#define DIAG_308_RC_INVALID         0x0402
+#define DIAG_308_RC_NO_PV_CONF      0x0902
+#define DIAG_308_RC_INVAL_FOR_PV    0x0a02
+
+#define DIAG308_RESET_MOD_CLR       0
+#define DIAG308_RESET_LOAD_NORM     1
+#define DIAG308_LOAD_CLEAR          3
+#define DIAG308_LOAD_NORMAL_DUMP    4
+#define DIAG308_SET                 5
+#define DIAG308_STORE               6
+#define DIAG308_PV_SET              8
+#define DIAG308_PV_STORE            9
+#define DIAG308_PV_START            10
+
+#define DIAG308_FLAGS_LP_VALID 0x80
+
+#define DIAG308_IPIB_FLAGS_SIPL 0x40
+#define DIAG308_IPIB_FLAGS_IPLIR 0x20
+
+#endif
include/hw/s390x/ipl/qipl.h +4 -1
index e505f44020..5c2bf3051c 100644
@@ -12,6 +12,8 @@
 #ifndef S390X_QIPL_H
 #define S390X_QIPL_H
 
+#include "diag308.h"
+
 /* Boot Menu flags */
 #define QIPL_FLAG_BM_OPTS_CMD   0x80
 #define QIPL_FLAG_BM_OPTS_ZIPL  0x40
@@ -103,7 +105,8 @@ typedef struct IplBlockQemuScsi IplBlockQemuScsi;
 union IplParameterBlock {
     struct {
         uint32_t len;
-        uint8_t  reserved0[3];
+        uint8_t  hdr_flags;
+        uint8_t  reserved0[2];
         uint8_t  version;
         uint32_t blk0_len;
         uint8_t  pbt;
Signature · 1 line
2.50.1
#48 lore raw

Re: [PATCH v5 15/29] hw/s390x/ipl: Add IPIB flags to IPL Parameter Block

Quoted 43 lines · Zhuoying Cai

Add IPIB flags to IPL Parameter Block to determine if IPL needs to perform securely and if IPL Information Report Block (IIRB) exists.

Move DIAG308 flags to a separated header file and add flags for secure IPL.

Secure boot in audit mode will perform if certificate(s) exist in the key store. IIRB will exist and results of verification will be stored in IIRB.

---
  hw/s390x/ipl.c                 | 20 ++++++++++++++++++++
  hw/s390x/ipl.h                 | 17 -----------------
  include/hw/s390x/ipl/diag308.h | 34 ++++++++++++++++++++++++++++++++++
  include/hw/s390x/ipl/qipl.h    |  5 ++++-
  4 files changed, 58 insertions(+), 18 deletions(-)

create mode 100644 include/hw/s390x/ipl/diag308.h

hw/s390x/ipl.c +10 -0
index 186be923d7..8ac0cee73d 100644
@@ -430,6 +430,13 @@ S390IPLCertificateStore *s390_ipl_get_certificate_store(void)
      return &ipl->cert_store;
  }
 
+static bool s390_has_certificate(void)
+{
+    S390IPLState *ipl = get_ipl_device();
+
+    return ipl->cert_store.count > 0;
+}
+
  static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
  {
      CcwDevice *ccw_dev = NULL;
@@ -487,6 +494,19 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
          s390_ipl_convert_loadparm((char *)lp, iplb->loadparm);
          iplb->flags |= DIAG308_FLAGS_LP_VALID;
 
+        /*
+         * Secure boot in audit mode will perform
+         * if certificate(s) exist in the key store.

hw/s390x/ipl.c static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb) · line 509

Quoted 10 lines
hw/s390x/ipl.c +10 -0
+         *
+         * IPL Information Report Block (IIRB) will exist
+         * for secure boot in audit mode.
+         *
+         * Results of secure boot will be stored in IIRB.
+         */
+        if (s390_has_certificate()) {
+            iplb->hdr_flags |= DIAG308_IPIB_FLAGS_IPLIR;
+        }
+

We could also override the previously assigned minimum IPLB length here if the flag is set.

That would avoid always using the max length and then patch 16 could be dropped too.

Quoted 92 lines
hw/s390x/ipl.c +0 -0
          return true;
      }
 
hw/s390x/ipl.h +0 -17
index e26fc1cd6a..3b8cc5474e 100644
@@ -23,7 +23,6 @@
  #include "qom/object.h"
  #include "target/s390x/kvm/pv.h"
 
-#define DIAG308_FLAGS_LP_VALID 0x80
  #define MAX_BOOT_DEVS 8 /* Max number of devices that may have a bootindex */
 
  void s390_ipl_convert_loadparm(char *ascii_lp, uint8_t *ebcdic_lp);
@@ -91,22 +90,6 @@ struct S390IPLState {
  };
  QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong");
 
-#define DIAG_308_RC_OK              0x0001
-#define DIAG_308_RC_NO_CONF         0x0102
-#define DIAG_308_RC_INVALID         0x0402
-#define DIAG_308_RC_NO_PV_CONF      0x0902
-#define DIAG_308_RC_INVAL_FOR_PV    0x0a02
-
-#define DIAG308_RESET_MOD_CLR       0
-#define DIAG308_RESET_LOAD_NORM     1
-#define DIAG308_LOAD_CLEAR          3
-#define DIAG308_LOAD_NORMAL_DUMP    4
-#define DIAG308_SET                 5
-#define DIAG308_STORE               6
-#define DIAG308_PV_SET              8
-#define DIAG308_PV_STORE            9
-#define DIAG308_PV_START            10
-
  #define S390_IPL_TYPE_FCP 0x00
  #define S390_IPL_TYPE_CCW 0x02
  #define S390_IPL_TYPE_PV 0x05
include/hw/s390x/ipl/diag308.h new file +34 -0
new file mode 100644
index 0000000000..6e62f29215
@@ -0,0 +1,34 @@
+/*
+ * S/390 DIAGNOSE 308 definitions and structures
+ *
+ * Copyright 2025 IBM Corp.
+ * Author(s): Zhuoying Cai <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef S390X_DIAG308_H
+#define S390X_DIAG308_H
+
+#define DIAG_308_RC_OK              0x0001
+#define DIAG_308_RC_NO_CONF         0x0102
+#define DIAG_308_RC_INVALID         0x0402
+#define DIAG_308_RC_NO_PV_CONF      0x0902
+#define DIAG_308_RC_INVAL_FOR_PV    0x0a02
+
+#define DIAG308_RESET_MOD_CLR       0
+#define DIAG308_RESET_LOAD_NORM     1
+#define DIAG308_LOAD_CLEAR          3
+#define DIAG308_LOAD_NORMAL_DUMP    4
+#define DIAG308_SET                 5
+#define DIAG308_STORE               6
+#define DIAG308_PV_SET              8
+#define DIAG308_PV_STORE            9
+#define DIAG308_PV_START            10
+
+#define DIAG308_FLAGS_LP_VALID 0x80
+
+#define DIAG308_IPIB_FLAGS_SIPL 0x40
+#define DIAG308_IPIB_FLAGS_IPLIR 0x20
+
+#endif
include/hw/s390x/ipl/qipl.h +2 -0
index e505f44020..5c2bf3051c 100644
@@ -12,6 +12,8 @@
  #ifndef S390X_QIPL_H
  #define S390X_QIPL_H
 
+#include "diag308.h"
+
  /* Boot Menu flags */
  #define QIPL_FLAG_BM_OPTS_CMD   0x80
  #define QIPL_FLAG_BM_OPTS_ZIPL  0x40

include/hw/s390x/ipl/qipl.h typedef struct IplBlockQemuScsi IplBlockQemuScsi; · line 112

Quoted 9 lines
include/hw/s390x/ipl/qipl.h +2 -1
@@ -103,7 +105,8 @@ typedef struct IplBlockQemuScsi IplBlockQemuScsi;
  union IplParameterBlock {
      struct {
          uint32_t len;
-        uint8_t  reserved0[3];
+        uint8_t  hdr_flags;
+        uint8_t  reserved0[2];
          uint8_t  version;
          uint32_t blk0_len;
          uint8_t  pbt;

Regards,
Jared Rossi

#49 lore raw

PATCH v5 16/29 hw/s390x/ipl: Set iplb->len to maximum length of IPL Parameter Block

In reply to Zhuoying Cai

The IPL Information Report Block (IIRB) immediately follows the IPL Parameter Block (IPLB).

The IPLB struct is allocated 4KB in memory, and iplb->len indicates the amount of memory currently used by the IPLB.

To ensure proper alignment of the IIRB and prevent overlap, set iplb->len to the maximum length of the IPLB, allowing alignment constraints to be determined based on its size.

---
 hw/s390x/ipl.c | 6 +++---
 hw/s390x/ipl.h | 1 +
 2 files changed, 4 insertions(+), 3 deletions(-)
hw/s390x/ipl.c +3 -3
index 8ac0cee73d..d1a972ac8d 100644
@@ -459,7 +459,7 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
             if (scsi_lp && strlen(scsi_lp) > 0) {
                 lp = scsi_lp;
             }
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
             iplb->blk0_len =
                 cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN - S390_IPLB_HEADER_LEN);
             iplb->pbt = S390_IPL_TYPE_QEMU_SCSI;
@@ -470,14 +470,14 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
             iplb->scsi.ssid = ccw_dev->sch->ssid & 3;
             break;
         case CCW_DEVTYPE_VFIO:
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
             iplb->pbt = S390_IPL_TYPE_CCW;
             iplb->ccw.devno = cpu_to_be16(ccw_dev->sch->devno);
             iplb->ccw.ssid = ccw_dev->sch->ssid & 3;
             break;
         case CCW_DEVTYPE_VIRTIO_NET:
         case CCW_DEVTYPE_VIRTIO:
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
             iplb->blk0_len =
                 cpu_to_be32(S390_IPLB_MIN_CCW_LEN - S390_IPLB_HEADER_LEN);
             iplb->pbt = S390_IPL_TYPE_CCW;
hw/s390x/ipl.h +1 -0
index 3b8cc5474e..01922d80c4 100644
@@ -100,6 +100,7 @@ QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong");
 #define S390_IPLB_MIN_CCW_LEN 200
 #define S390_IPLB_MIN_FCP_LEN 384
 #define S390_IPLB_MIN_QEMU_SCSI_LEN 200
+#define S390_IPLB_MAX_LEN 4096
 
 static inline bool diag_parm_addr_valid(uint64_t addr, size_t size, bool write)
 {
Signature · 1 line
2.50.1
#50 lore raw

Re: [PATCH v5 16/29] hw/s390x/ipl: Set iplb->len to maximum length of IPL Parameter Block

Quoted 51 lines · Zhuoying Cai

The IPL Information Report Block (IIRB) immediately follows the IPL Parameter Block (IPLB).

The IPLB struct is allocated 4KB in memory, and iplb->len indicates the amount of memory currently used by the IPLB.

To ensure proper alignment of the IIRB and prevent overlap, set iplb->len to the maximum length of the IPLB, allowing alignment constraints to be determined based on its size.

---
  hw/s390x/ipl.c | 6 +++---
  hw/s390x/ipl.h | 1 +
  2 files changed, 4 insertions(+), 3 deletions(-)
hw/s390x/ipl.c +3 -3
index 8ac0cee73d..d1a972ac8d 100644
@@ -459,7 +459,7 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
              if (scsi_lp && strlen(scsi_lp) > 0) {
                  lp = scsi_lp;
              }
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
              iplb->blk0_len =
                  cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN - S390_IPLB_HEADER_LEN);
              iplb->pbt = S390_IPL_TYPE_QEMU_SCSI;
@@ -470,14 +470,14 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
              iplb->scsi.ssid = ccw_dev->sch->ssid & 3;
              break;
          case CCW_DEVTYPE_VFIO:
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
              iplb->pbt = S390_IPL_TYPE_CCW;
              iplb->ccw.devno = cpu_to_be16(ccw_dev->sch->devno);
              iplb->ccw.ssid = ccw_dev->sch->ssid & 3;
              break;
          case CCW_DEVTYPE_VIRTIO_NET:
          case CCW_DEVTYPE_VIRTIO:
-            iplb->len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
+            iplb->len = cpu_to_be32(S390_IPLB_MAX_LEN);
              iplb->blk0_len =
                  cpu_to_be32(S390_IPLB_MIN_CCW_LEN - S390_IPLB_HEADER_LEN);
              iplb->pbt = S390_IPL_TYPE_CCW;
hw/s390x/ipl.h +0 -0
index 3b8cc5474e..01922d80c4 100644

hw/s390x/ipl.h QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong"); · line 106

Quoted 7 lines
hw/s390x/ipl.h +1 -0
@@ -100,6 +100,7 @@ QEMU_BUILD_BUG_MSG(offsetof(S390IPLState, iplb) & 3, "alignment of iplb wrong");
  #define S390_IPLB_MIN_CCW_LEN 200
  #define S390_IPLB_MIN_FCP_LEN 384
  #define S390_IPLB_MIN_QEMU_SCSI_LEN 200
+#define S390_IPLB_MAX_LEN 4096
 
  static inline bool diag_parm_addr_valid(uint64_t addr, size_t size, bool write)
  {

This only needs to be done if the IIRB exists.  See comments on patch 15.

Regards,
Jared Rossi

#51 lore raw

PATCH v5 17/29 s390x: Guest support for Secure-IPL Facility

In reply to Zhuoying Cai

Introduce Secure-IPL (SIPL) facility.

Use fac_ipl to represent bytes 136 and 137 for IPL device facilities of the SCLP Read Info block.

Availability of SIPL facility is determined by byte 136 bit 1 of the SCLP Read Info block. Byte 136's facilities cannot be represented without the availability of the extended-length-SCCB, so add it as a check for consistency.

Secure IPL is not available for guests under protected virtualization.

---
 hw/s390x/sclp.c                     | 2 ++
 include/hw/s390x/sclp.h             | 4 +++-
 target/s390x/cpu_features.c         | 4 ++++
 target/s390x/cpu_features.h         | 1 +
 target/s390x/cpu_features_def.h.inc | 3 +++
 target/s390x/cpu_models.c           | 2 ++
 target/s390x/gen-features.c         | 2 ++
 target/s390x/kvm/kvm.c              | 3 +++
 8 files changed, 20 insertions(+), 1 deletion(-)
hw/s390x/sclp.c +2 -0
index 9718564fa4..69d3328a3d 100644
@@ -145,6 +145,8 @@ static void read_SCP_info(SCLPDevice *sclp, SCCB *sccb)
     if (s390_has_feat(S390_FEAT_EXTENDED_LENGTH_SCCB)) {
         s390_get_feat_block(S390_FEAT_TYPE_SCLP_FAC134,
                             &read_info->fac134);
+        s390_get_feat_block(S390_FEAT_TYPE_SCLP_FAC_IPL,
+                            read_info->fac_ipl);
     }
 
     read_info->facilities = cpu_to_be64(SCLP_HAS_CPU_INFO |
include/hw/s390x/sclp.h +3 -1
index d32f6180e0..bfd330c340 100644
@@ -136,7 +136,9 @@ typedef struct ReadInfo {
     uint32_t hmfai;
     uint8_t  _reserved7[134 - 128];     /* 128-133 */
     uint8_t  fac134;
-    uint8_t  _reserved8[144 - 135];     /* 135-143 */
+    uint8_t  _reserved8;
+    uint8_t  fac_ipl[2];                /* 136-137 */
+    uint8_t  _reserved9[144 - 137];     /* 138-143 */
     struct CPUEntry entries[];
     /*
      * When the Extended-Length SCCB (ELS) feature is enabled the
target/s390x/cpu_features.c +4 -0
index 436471f4b4..200bd8c15b 100644
@@ -119,6 +119,7 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
      * Some facilities are not available for CPUs in protected mode:
      * - All SIE facilities because SIE is not available
      * - DIAG318
+     * - Secure IPL Facility
      *
      * As VMs can move in and out of protected mode the CPU model
      * doesn't protect us from that problem because it is only
@@ -149,6 +150,9 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
         clear_be_bit(s390_feat_def(S390_FEAT_DIAG_318)->bit, data);
         clear_be_bit(s390_feat_def(S390_FEAT_CERT_STORE)->bit, data);
         break;
+    case S390_FEAT_TYPE_SCLP_FAC_IPL:
+        clear_be_bit(s390_feat_def(S390_FEAT_SIPL)->bit, data);
+        break;
     default:
         return;
     }
target/s390x/cpu_features.h +1 -0
index 5635839d03..b038198555 100644
@@ -24,6 +24,7 @@ typedef enum {
     S390_FEAT_TYPE_SCLP_CONF_CHAR,
     S390_FEAT_TYPE_SCLP_CONF_CHAR_EXT,
     S390_FEAT_TYPE_SCLP_FAC134,
+    S390_FEAT_TYPE_SCLP_FAC_IPL,
     S390_FEAT_TYPE_SCLP_CPU,
     S390_FEAT_TYPE_MISC,
     S390_FEAT_TYPE_PLO,
target/s390x/cpu_features_def.h.inc +3 -0
index 941a69e013..55eef618b8 100644
@@ -140,6 +140,9 @@ DEF_FEAT(SIE_IBS, "ibs", SCLP_CONF_CHAR_EXT, 10, "SIE: Interlock-and-broadcast-s
 DEF_FEAT(DIAG_318, "diag318", SCLP_FAC134, 0, "Control program name and version codes")
 DEF_FEAT(CERT_STORE, "cstore", SCLP_FAC134, 5, "Provide Certificate Store functions")
 
+/* Features exposed via SCLP SCCB Facilities byte 136 - 137 (bit numbers relative to byte-136) */
+DEF_FEAT(SIPL, "sipl", SCLP_FAC_IPL, 1, "Secure-IPL facility")
+
 /* Features exposed via SCLP CPU info. */
 DEF_FEAT(SIE_F2, "sief2", SCLP_CPU, 4, "SIE: interception format 2 (Virtual SIE)")
 DEF_FEAT(SIE_SKEY, "skey", SCLP_CPU, 5, "SIE: Storage-key facility")
target/s390x/cpu_models.c +2 -0
index 6b8471700e..f99536ef9a 100644
@@ -263,6 +263,7 @@ bool s390_has_feat(S390Feat feat)
         case S390_FEAT_SIE_CMMA:
         case S390_FEAT_SIE_PFMFI:
         case S390_FEAT_SIE_IBS:
+        case S390_FEAT_SIPL:
         case S390_FEAT_CONFIGURATION_TOPOLOGY:
             return false;
             break;
@@ -507,6 +508,7 @@ static void check_consistency(const S390CPUModel *model)
         { S390_FEAT_AP_QUEUE_INTERRUPT_CONTROL, S390_FEAT_AP },
         { S390_FEAT_DIAG_318, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_CERT_STORE, S390_FEAT_EXTENDED_LENGTH_SCCB },
+        { S390_FEAT_SIPL, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_NNPA, S390_FEAT_VECTOR },
         { S390_FEAT_RDP, S390_FEAT_LOCAL_TLB_CLEARING },
         { S390_FEAT_UV_FEAT_AP, S390_FEAT_AP },
target/s390x/gen-features.c +2 -0
index 6c20c3a862..bd2060ab93 100644
@@ -721,6 +721,7 @@ static uint16_t full_GEN16_GA1[] = {
     S390_FEAT_UV_FEAT_AP,
     S390_FEAT_UV_FEAT_AP_INTR,
     S390_FEAT_CERT_STORE,
+    S390_FEAT_SIPL,
 };
 
 static uint16_t full_GEN17_GA1[] = {
@@ -922,6 +923,7 @@ static uint16_t qemu_MAX[] = {
     S390_FEAT_PRNO_TRNG,
     S390_FEAT_EXTENDED_LENGTH_SCCB,
     S390_FEAT_CERT_STORE,
+    S390_FEAT_SIPL,
 };
 
 /****** END FEATURE DEFS ******/
target/s390x/kvm/kvm.c +3 -0
index ae6cd3d506..31bd574dec 100644
@@ -2520,6 +2520,9 @@ bool kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
 
     set_bit(S390_FEAT_CERT_STORE, model->features);
 
+    /* Some Secure IPL facilities are emulated by QEMU */
+    set_bit(S390_FEAT_SIPL, model->features);
+
     /* Test for Ultravisor features that influence secure guest behavior */
     query_uv_feat_guest(model->features);
 
Signature · 1 line
2.50.1
#52 lore raw

PATCH v5 18/29 pc-bios/s390-ccw: Refactor zipl_run()

In reply to Zhuoying Cai

Refactor to enhance readability before enabling secure IPL in later patches.

---
 pc-bios/s390-ccw/bootmap.c | 49 ++++++++++++++++++++++++--------------
 1 file changed, 31 insertions(+), 18 deletions(-)
pc-bios/s390-ccw/bootmap.c +31 -18
index 0f8baa0198..ff0fa78cf0 100644
@@ -674,6 +674,35 @@ static int zipl_load_segment(ComponentEntry *entry)
     return 0;
 }
 
+static int zipl_run_normal(ComponentEntry **entry_ptr, uint8_t *tmp_sec)
+{
+    ComponentEntry *entry = *entry_ptr;
+
+    while (entry->component_type == ZIPL_COMP_ENTRY_LOAD ||
+           entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
+
+        /* Secure boot is off, so we skip signature entries */
+        if (entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
+            entry++;
+            continue;
+        }
+
+        if (zipl_load_segment(entry)) {
+            return -1;
+        }
+
+        entry++;
+
+        if ((uint8_t *)&entry[1] > tmp_sec + MAX_SECTOR_SIZE) {
+            puts("Wrong entry value");
+            return -EINVAL;
+        }
+    }
+
+    *entry_ptr = entry;
+    return 0;
+}
+
 /* Run a zipl program */
 static int zipl_run(ScsiBlockPtr *pte)
 {
@@ -700,25 +729,9 @@ static int zipl_run(ScsiBlockPtr *pte)
 
     /* Load image(s) into RAM */
     entry = (ComponentEntry *)(&header[1]);
-    while (entry->component_type == ZIPL_COMP_ENTRY_LOAD ||
-           entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
-
-        /* We don't support secure boot yet, so we skip signature entries */
-        if (entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
-            entry++;
-            continue;
-        }
 
-        if (zipl_load_segment(entry)) {
-            return -1;
-        }
-
-        entry++;
-
-        if ((uint8_t *)(&entry[1]) > (tmp_sec + MAX_SECTOR_SIZE)) {
-            puts("Wrong entry value");
-            return -EINVAL;
-        }
+    if (zipl_run_normal(&entry, tmp_sec)) {
+        return -1;
     }
 
     if (entry->component_type != ZIPL_COMP_ENTRY_EXEC) {
Signature · 1 line
2.50.1
#53 lore raw

PATCH v5 19/29 pc-bios/s390-ccw: Rework zipl_load_segment function

In reply to Zhuoying Cai

Make the address variable a parameter of zipl_load_segment and return segment length.

Modify this function to allow the caller to specify a memory address where segment data should be loaded into.

seg_len variable is necessary to store the calculated segment length and is used during signature verification. Return the length on success, or a negative return code on failure.

---
 pc-bios/s390-ccw/bootmap.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
pc-bios/s390-ccw/bootmap.c +10 -5
index ff0fa78cf0..4f54c643ff 100644
@@ -613,19 +613,22 @@ static int ipl_eckd(void)
  * IPL a SCSI disk
  */
 
-static int zipl_load_segment(ComponentEntry *entry)
+/*
+ * Returns: length of the segment on sucess,
+ *          negative value on error.
+ */
+static int zipl_load_segment(ComponentEntry *entry, uint64_t address)
 {
     const int max_entries = (MAX_SECTOR_SIZE / sizeof(ScsiBlockPtr));
     ScsiBlockPtr *bprs = (void *)sec;
     const int bprs_size = sizeof(sec);
     block_number_t blockno;
-    uint64_t address;
     int i;
     char err_msg[] = "zIPL failed to read BPRS at 0xZZZZZZZZZZZZZZZZ";
     char *blk_no = &err_msg[30]; /* where to print blockno in (those ZZs) */
+    int seg_len = 0;
 
     blockno = entry->data.blockno;
-    address = entry->compdat.load_addr;
 
     debug_print_int("loading segment at block", blockno);
     debug_print_int("addr", address);
@@ -668,10 +671,12 @@ static int zipl_load_segment(ComponentEntry *entry)
                 puts("zIPL load segment failed");
                 return -EIO;
             }
+
+            seg_len += bprs->size * (bprs[i].blockct + 1);
         }
     } while (blockno);
 
-    return 0;
+    return seg_len;
 }
 
 static int zipl_run_normal(ComponentEntry **entry_ptr, uint8_t *tmp_sec)
@@ -687,7 +692,7 @@ static int zipl_run_normal(ComponentEntry **entry_ptr, uint8_t *tmp_sec)
             continue;
         }
 
-        if (zipl_load_segment(entry)) {
+        if (zipl_load_segment(entry, entry->compdat.load_addr) < 0) {
             return -1;
         }
 
Signature · 1 line
2.50.1
#54 lore raw

PATCH v5 20/29 pc-bios/s390-ccw: Add signature verification for secure IPL in audit mode

In reply to Zhuoying Cai

Enable secure IPL in audit mode, which performs signature verification, but any error does not terminate the boot process. Only warnings will be logged to the console instead.

Add a comp_len variable to store the length of a segment in zipl_load_segment. comp_len variable is necessary to store the calculated segment length and is used during signature verification. Return the length on success, or a negative return code on failure.

Secure IPL in audit mode requires at least one certificate provided in the key store along with necessary facilities (Secure IPL Facility, Certificate Store Facility and secure IPL extension support).

Note: Secure IPL in audit mode is implemented for the SCSI scheme of virtio-blk/virtio-scsi devices.

---
 docs/system/s390x/secure-ipl.rst |  36 ++++
 pc-bios/s390-ccw/Makefile        |   3 +-
 pc-bios/s390-ccw/bootmap.c       |  39 +++-
 pc-bios/s390-ccw/bootmap.h       |  11 +
 pc-bios/s390-ccw/main.c          |   9 +
 pc-bios/s390-ccw/s390-ccw.h      |  15 ++
 pc-bios/s390-ccw/sclp.c          |  44 ++++
 pc-bios/s390-ccw/sclp.h          |   6 +
 pc-bios/s390-ccw/secure-ipl.c    | 357 +++++++++++++++++++++++++++++++
 pc-bios/s390-ccw/secure-ipl.h    |  93 ++++++++
 10 files changed, 610 insertions(+), 3 deletions(-)
 create mode 100644 pc-bios/s390-ccw/secure-ipl.c
 create mode 100644 pc-bios/s390-ccw/secure-ipl.h
docs/system/s390x/secure-ipl.rst +36 -0
index 9b3fd25cc4..40a5781c7d 100644
@@ -18,3 +18,39 @@ paths or directories on the command-line:
     qemu-system-s390x -machine s390-ccw-virtio, \
                                boot-certs.0.path=/.../qemu/certs, \
                                boot-certs.1.path=/another/path/cert.pem ...
+
+
+IPL Modes
+=========
+
+The concept of IPL Modes are introduced to differentiate between the IPL configurations.
+These modes are mutually exclusive and enabled based on the ``boot-certs`` option on the
+QEMU command line.
+
+Normal Mode
+-----------
+
+The absence of certificates will attempt to IPL a guest without secure IPL operations.
+No checks are performed, and no warnings/errors are reported. This is the default mode.
+
+Configuration:
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio ...
+
+Audit Mode
+----------
+
+With *only* the presence of certificates in the store, it is assumed that secure
+boot operations should be performed with errors reported as warnings. As such,
+the secure IPL operations will be performed, and any errors that stem from these
+operations will report a warning via the SCLP console.
+
+Configuration:
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
pc-bios/s390-ccw/Makefile +2 -1
index a0f24c94a8..603761a857 100644
@@ -34,7 +34,8 @@ QEMU_DGFLAGS = -MMD -MP -MT $@ -MF $(@D)/$(*F).d
 .PHONY : all clean build-all distclean
 
 OBJECTS = start.o main.o bootmap.o jump2ipl.o sclp.o menu.o netmain.o \
-	  virtio.o virtio-net.o virtio-scsi.o virtio-blkdev.o cio.o dasd-ipl.o
+	  virtio.o virtio-net.o virtio-scsi.o virtio-blkdev.o cio.o dasd-ipl.o \
+	  secure-ipl.o
 
 SLOF_DIR := $(SRC_PATH)/../../roms/SLOF
 
pc-bios/s390-ccw/bootmap.c +37 -2
index 4f54c643ff..3922e7cdde 100644
@@ -15,6 +15,7 @@
 #include "bootmap.h"
 #include "virtio.h"
 #include "bswap.h"
+#include "secure-ipl.h"
 
 #ifdef DEBUG
 /* #define DEBUG_FALLBACK */
@@ -617,7 +618,7 @@ static int ipl_eckd(void)
  * Returns: length of the segment on sucess,
  *          negative value on error.
  */
-static int zipl_load_segment(ComponentEntry *entry, uint64_t address)
+int zipl_load_segment(ComponentEntry *entry, uint64_t address)
 {
     const int max_entries = (MAX_SECTOR_SIZE / sizeof(ScsiBlockPtr));
     ScsiBlockPtr *bprs = (void *)sec;
@@ -735,7 +736,19 @@ static int zipl_run(ScsiBlockPtr *pte)
     /* Load image(s) into RAM */
     entry = (ComponentEntry *)(&header[1]);
 
-    if (zipl_run_normal(&entry, tmp_sec)) {
+    switch (boot_mode) {
+    case ZIPL_BOOT_MODE_SECURE_AUDIT:
+        if (zipl_run_secure(&entry, tmp_sec)) {
+            return -1;
+        }
+        break;
+    case ZIPL_BOOT_MODE_NORMAL:
+        if (zipl_run_normal(&entry, tmp_sec)) {
+            return -1;
+        }
+        break;
+    default:
+        puts("Unknown boot mode");
         return -1;
     }
 
@@ -1101,17 +1114,35 @@ static int zipl_load_vscsi(void)
  * IPL starts here
  */
 
+ZiplBootMode zipl_mode(uint8_t hdr_flags)
+{
+    bool sipl_set = hdr_flags & DIAG308_IPIB_FLAGS_SIPL;
+    bool iplir_set = hdr_flags & DIAG308_IPIB_FLAGS_IPLIR;
+
+    if (!sipl_set && iplir_set) {
+        return ZIPL_BOOT_MODE_SECURE_AUDIT;
+    }
+
+    return ZIPL_BOOT_MODE_NORMAL;
+}
+
 void zipl_load(void)
 {
     VDev *vdev = virtio_get_device();
 
     if (vdev->is_cdrom) {
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+            panic("Secure boot from ISO image is not supported!");
+        }
         ipl_iso_el_torito();
         puts("Failed to IPL this ISO image!");
         return;
     }
 
     if (virtio_get_device_type() == VIRTIO_ID_NET) {
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+            panic("Virtio net boot device does not support secure boot!");
+        }
         netmain();
         puts("Failed to IPL from this network!");
         return;
@@ -1122,6 +1153,10 @@ void zipl_load(void)
         return;
     }
 
+    if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+        panic("ECKD boot device does not support secure boot!");
+    }
+
     switch (virtio_get_device_type()) {
     case VIRTIO_ID_BLOCK:
         zipl_load_vblk();
pc-bios/s390-ccw/bootmap.h +11 -0
index 95943441d3..90fd530256 100644
@@ -88,9 +88,18 @@ typedef struct BootMapTable {
     BootMapPointer entry[];
 } __attribute__ ((packed)) BootMapTable;
 
+#define DER_SIGNATURE_FORMAT 1
+
+typedef struct SignatureInformation {
+    uint8_t format;
+    uint8_t reserved[3];
+    uint32_t sig_len;
+} __attribute__((packed)) SignatureInformation;
+
 typedef union ComponentEntryData {
     uint64_t load_psw;
     uint64_t load_addr;
+    SignatureInformation sig_info;
 } ComponentEntryData;
 
 typedef struct ComponentEntry {
@@ -113,6 +122,8 @@ typedef struct ScsiMbr {
     ScsiBlockPtr pt;   /* block pointer to program table */
 } __attribute__ ((packed)) ScsiMbr;
 
+int zipl_load_segment(ComponentEntry *entry, uint64_t address);
+
 #define ZIPL_MAGIC              "zIPL"
 #define ZIPL_MAGIC_EBCDIC       "\xa9\xc9\xd7\xd3"
 #define IPL1_MAGIC "\xc9\xd7\xd3\xf1" /* == "IPL1" in EBCDIC */
pc-bios/s390-ccw/main.c +9 -0
index c9328f1c51..668660e64d 100644
@@ -28,6 +28,7 @@ IplParameterBlock *iplb;
 bool have_iplb;
 static uint16_t cutype;
 LowCore *lowcore; /* Yes, this *is* a pointer to address 0 */
+ZiplBootMode boot_mode;
 
 #define LOADPARM_PROMPT "PROMPT  "
 #define LOADPARM_EMPTY  "        "
@@ -272,9 +273,17 @@ static int virtio_setup(void)
 
 static void ipl_boot_device(void)
 {
+    if (boot_mode == ZIPL_BOOT_MODE_UNSPECIFIED) {
+        boot_mode = zipl_mode(iplb->hdr_flags);
+    }
+
     switch (cutype) {
     case CU_TYPE_DASD_3990:
     case CU_TYPE_DASD_2107:
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+            panic("Passthrough (vfio) device does not support secure boot!");
+        }
+
         dasd_ipl(blk_schid, cutype);
         break;
     case CU_TYPE_VIRTIO:
pc-bios/s390-ccw/s390-ccw.h +15 -0
index b1dc35cded..c2ba40d067 100644
@@ -39,6 +39,9 @@ typedef unsigned long long u64;
 #define MIN_NON_ZERO(a, b) ((a) == 0 ? (b) : \
                             ((b) == 0 ? (a) : (MIN(a, b))))
 #endif
+#ifndef ROUND_UP
+#define ROUND_UP(n, d) (((n) + (d) - 1) & -(0 ? (n) : (d)))
+#endif
 
 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
 
@@ -64,6 +67,8 @@ void sclp_print(const char *string);
 void sclp_set_write_mask(uint32_t receive_mask, uint32_t send_mask);
 void sclp_setup(void);
 void sclp_get_loadparm_ascii(char *loadparm);
+bool sclp_is_diag320_on(void);
+bool sclp_is_sipl_on(void);
 int sclp_read(char *str, size_t count);
 
 /* virtio.c */
@@ -76,6 +81,16 @@ int virtio_read(unsigned long sector, void *load_addr);
 /* bootmap.c */
 void zipl_load(void);
 
+typedef enum ZiplBootMode {
+    ZIPL_BOOT_MODE_UNSPECIFIED = 0,
+    ZIPL_BOOT_MODE_NORMAL = 1,
+    ZIPL_BOOT_MODE_SECURE_AUDIT = 2,
+} ZiplBootMode;
+
+extern ZiplBootMode boot_mode;
+
+ZiplBootMode zipl_mode(uint8_t hdr_flags);
+
 /* jump2ipl.c */
 void write_reset_psw(uint64_t psw);
 int jump_to_IPL_code(uint64_t address);
pc-bios/s390-ccw/sclp.c +44 -0

50 lines not on this page · raw message

pc-bios/s390-ccw/sclp.h +6 -0
index 64b53cad29..cf147f4634 100644
@@ -50,6 +50,8 @@ typedef struct SCCBHeader {
 } __attribute__((packed)) SCCBHeader;
 
 #define SCCB_DATA_LEN (SCCB_SIZE - sizeof(SCCBHeader))
+#define SCCB_FAC134_DIAG320_BIT 0x4
+#define SCCB_FAC_IPL_SIPL_BIT 0x4000
 
 typedef struct ReadInfo {
     SCCBHeader h;
@@ -57,6 +59,10 @@ typedef struct ReadInfo {
     uint8_t rnsize;
     uint8_t reserved[13];
     uint8_t loadparm[LOADPARM_LEN];
+    uint8_t reserved1[102];
+    uint8_t fac134;
+    uint8_t reserved2;
+    uint16_t fac_ipl;
 } __attribute__((packed)) ReadInfo;
 
 typedef struct SCCB {
pc-bios/s390-ccw/secure-ipl.c new file +357 -0

357 lines not on this page · raw message

pc-bios/s390-ccw/secure-ipl.h new file +93 -0

93 lines not on this page · raw message

Signature · 1 line
2.50.1
#55 lore raw

PATCH v5 21/29 s390x: Guest support for Secure-IPL Code Loading Attributes Facility (SCLAF)

In reply to Zhuoying Cai

The secure-IPL-code-loading-attributes facility (SCLAF) provides additional security during IPL.

Availability of SCLAF is determined by byte 136 bit 3 of the SCLP Read Info block.

---
 docs/specs/s390x-secure-ipl.rst     | 25 +++++++++++++++++++++++++
 target/s390x/cpu_features.c         |  2 ++
 target/s390x/cpu_features_def.h.inc |  1 +
 target/s390x/cpu_models.c           |  3 +++
 target/s390x/gen-features.c         |  2 ++
 target/s390x/kvm/kvm.c              |  1 +
 6 files changed, 34 insertions(+)
docs/specs/s390x-secure-ipl.rst +25 -0
index 4bc330c399..72ab901014 100644
@@ -83,3 +83,28 @@ operations such as:
 * certificate data
 
 The guest kernel will inspect the IIRB and build the keyring.
+
+
+Secure Code Loading Attributes Facility
+---------------------------------
+
+The Secure Code Loading Attributes Facility (SCLAF) enhances system security during the
+IPL by enforcing additional verification rules.
+
+When SCLAF is available, its behavior depends on the IPL mode. It introduces verification
+of both signed and unsigned components to help ensure that only authorized code is loaded
+during the IPL process. Any errors detected by SCLAF are reported in the IIRB.
+
+Unsigned components are restricted to load addresses at or above absolute storage address
+``0x2000``.
+
+Signed components must include a Secure Code Loading Attribute Block (SCLAB), which is
+appended at the very end of the component. The SCLAB defines security attributes for
+handling the signed code. Specifically, it may:
+
+* Provide direction on how to process the rest of the component.
+
+* Provide further validation of information on where to load the signed binary code
+  from the load device.
+
+* Specify where to start the execution of the loaded OS code.
target/s390x/cpu_features.c +2 -0
index 200bd8c15b..29ea3bfec2 100644
@@ -120,6 +120,7 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
      * - All SIE facilities because SIE is not available
      * - DIAG318
      * - Secure IPL Facility
+     * - Secure IPL Code Loading Attributes Facility
      *
      * As VMs can move in and out of protected mode the CPU model
      * doesn't protect us from that problem because it is only
@@ -152,6 +153,7 @@ void s390_fill_feat_block(const S390FeatBitmap features, S390FeatType type,
         break;
     case S390_FEAT_TYPE_SCLP_FAC_IPL:
         clear_be_bit(s390_feat_def(S390_FEAT_SIPL)->bit, data);
+        clear_be_bit(s390_feat_def(S390_FEAT_SCLAF)->bit, data);
         break;
     default:
         return;
target/s390x/cpu_features_def.h.inc +1 -0
index 55eef618b8..ecfca0faef 100644
@@ -142,6 +142,7 @@ DEF_FEAT(CERT_STORE, "cstore", SCLP_FAC134, 5, "Provide Certificate Store functi
 
 /* Features exposed via SCLP SCCB Facilities byte 136 - 137 (bit numbers relative to byte-136) */
 DEF_FEAT(SIPL, "sipl", SCLP_FAC_IPL, 1, "Secure-IPL facility")
+DEF_FEAT(SCLAF, "sclaf", SCLP_FAC_IPL, 3, "Secure-IPL-code-loading-attributes facility")
 
 /* Features exposed via SCLP CPU info. */
 DEF_FEAT(SIE_F2, "sief2", SCLP_CPU, 4, "SIE: interception format 2 (Virtual SIE)")
target/s390x/cpu_models.c +3 -0
index f99536ef9a..7d214b5f72 100644
@@ -264,6 +264,7 @@ bool s390_has_feat(S390Feat feat)
         case S390_FEAT_SIE_PFMFI:
         case S390_FEAT_SIE_IBS:
         case S390_FEAT_SIPL:
+        case S390_FEAT_SCLAF:
         case S390_FEAT_CONFIGURATION_TOPOLOGY:
             return false;
             break;
@@ -509,6 +510,8 @@ static void check_consistency(const S390CPUModel *model)
         { S390_FEAT_DIAG_318, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_CERT_STORE, S390_FEAT_EXTENDED_LENGTH_SCCB },
         { S390_FEAT_SIPL, S390_FEAT_EXTENDED_LENGTH_SCCB },
+        { S390_FEAT_SCLAF, S390_FEAT_EXTENDED_LENGTH_SCCB },
+        { S390_FEAT_SCLAF, S390_FEAT_SIPL },
         { S390_FEAT_NNPA, S390_FEAT_VECTOR },
         { S390_FEAT_RDP, S390_FEAT_LOCAL_TLB_CLEARING },
         { S390_FEAT_UV_FEAT_AP, S390_FEAT_AP },
target/s390x/gen-features.c +2 -0
index bd2060ab93..c3e0c6ceff 100644
@@ -722,6 +722,7 @@ static uint16_t full_GEN16_GA1[] = {
     S390_FEAT_UV_FEAT_AP_INTR,
     S390_FEAT_CERT_STORE,
     S390_FEAT_SIPL,
+    S390_FEAT_SCLAF,
 };
 
 static uint16_t full_GEN17_GA1[] = {
@@ -924,6 +925,7 @@ static uint16_t qemu_MAX[] = {
     S390_FEAT_EXTENDED_LENGTH_SCCB,
     S390_FEAT_CERT_STORE,
     S390_FEAT_SIPL,
+    S390_FEAT_SCLAF,
 };
 
 /****** END FEATURE DEFS ******/
target/s390x/kvm/kvm.c +1 -0
index 31bd574dec..2ed11fab52 100644
@@ -2522,6 +2522,7 @@ bool kvm_s390_get_host_cpu_model(S390CPUModel *model, Error **errp)
 
     /* Some Secure IPL facilities are emulated by QEMU */
     set_bit(S390_FEAT_SIPL, model->features);
+    set_bit(S390_FEAT_SCLAF, model->features);
 
     /* Test for Ultravisor features that influence secure guest behavior */
     query_uv_feat_guest(model->features);
Signature · 1 line
2.50.1
#56 lore raw

PATCH v5 22/29 pc-bios/s390-ccw: Add additional security checks for secure boot

In reply to Zhuoying Cai

Add additional checks to ensure that components do not overlap with signed components when loaded into memory.

Add additional checks to ensure the load addresses of unsigned components are greater than or equal to 0x2000.

When the secure IPL code loading attributes facility (SCLAF) is installed, all signed components must contain a secure code loading attributes block (SCLAB).

The SCLAB provides further validation of information on where to load the signed binary code from the load device, and where to start the execution of the loaded OS code.

When SCLAF is installed, its content must be evaluated during secure IPL. However, a missing SCLAB will not be reported in audit mode. The SCALB checking will be skipped in this case.

Add IPL Information Error Indicators (IIEI) and Component Error Indicators (CEI) for IPL Information Report Block (IIRB).

When SCLAF is installed, additional secure boot checks are performed during zipl and store results of verification into IIRB.

---
 pc-bios/s390-ccw/iplb.h       |  26 ++-
 pc-bios/s390-ccw/s390-ccw.h   |   1 +
 pc-bios/s390-ccw/sclp.c       |   8 +
 pc-bios/s390-ccw/sclp.h       |   1 +
 pc-bios/s390-ccw/secure-ipl.c | 412 +++++++++++++++++++++++++++++++++-
 pc-bios/s390-ccw/secure-ipl.h | 110 +++++++++
 6 files changed, 553 insertions(+), 5 deletions(-)
pc-bios/s390-ccw/iplb.h +24 -2
index 11302e004d..41cec91a68 100644
@@ -32,11 +32,19 @@ struct IplInfoReportBlockHeader {
 } __attribute__ ((packed));
 typedef struct IplInfoReportBlockHeader IplInfoReportBlockHeader;
 
+#define S390_IPL_INFO_IIEI_NO_SIGNED_COMP      0x8000 /* bit 0 */
+#define S390_IPL_INFO_IIEI_NO_SCLAB            0x4000 /* bit 1 */
+#define S390_IPL_INFO_IIEI_NO_GLOBAL_SCLAB     0x2000 /* bit 2 */
+#define S390_IPL_INFO_IIEI_MORE_GLOBAL_SCLAB   0x1000 /* bit 3 */
+#define S390_IPL_INFO_IIEI_FOUND_UNSIGNED_COMP 0x800 /* bit 4 */
+#define S390_IPL_INFO_IIEI_MORE_SIGNED_COMP    0x400 /* bit 5 */
+
 struct IplInfoBlockHeader {
     uint32_t len;
     uint8_t  ibt;
     uint8_t  reserved1[3];
-    uint8_t  reserved2[8];
+    uint16_t iiei;
+    uint8_t  reserved2[6];
 } __attribute__ ((packed));
 typedef struct IplInfoBlockHeader IplInfoBlockHeader;
 
@@ -60,13 +68,27 @@ typedef struct IplSignatureCertificateList IplSignatureCertificateList;
 #define S390_IPL_COMPONENT_FLAG_SC  0x80
 #define S390_IPL_COMPONENT_FLAG_CSV 0x40
 
+#define S390_IPL_COMPONENT_CEI_INVALID_SCLAB             0x80000000 /* bit 0 */
+#define S390_IPL_COMPONENT_CEI_INVALID_SCLAB_LEN         0x40000000 /* bit 1 */
+#define S390_IPL_COMPONENT_CEI_INVALID_SCLAB_FORMAT      0x20000000 /* bit 2 */
+#define S390_IPL_COMPONENT_CEI_UNMATCHED_SCLAB_LOAD_ADDR 0x10000000 /* bit 3 */
+#define S390_IPL_COMPONENT_CEI_UNMATCHED_SCLAB_LOAD_PSW  0x8000000  /* bit 4 */
+#define S390_IPL_COMPONENT_CEI_INVALID_LOAD_PSW          0x4000000  /* bit 5 */
+#define S390_IPL_COMPONENT_CEI_NUC_NOT_IN_GLOBAL_SCLA    0x2000000  /* bit 6 */
+#define S390_IPL_COMPONENT_CEI_SCLAB_OLA_NOT_ONE         0x1000000  /* bit 7 */
+#define S390_IPL_COMPONENT_CEI_SC_NOT_IN_GLOBAL_SCLAB    0x800000   /* bit 8 */
+#define S390_IPL_COMPONENT_CEI_SCLAB_LOAD_ADDR_NOT_ZERO  0x400000   /* bit 9 */
+#define S390_IPL_COMPONENT_CEI_SCLAB_LOAD_PSW_NOT_ZERO   0x200000   /* bit 10 */
+#define S390_IPL_COMPONENT_CEI_INVALID_UNSIGNED_ADDR     0x100000   /* bit 11 */
+
 struct IplDeviceComponentEntry {
     uint64_t addr;
     uint64_t len;
     uint8_t  flags;
     uint8_t  reserved1[5];
     uint16_t cert_index;
-    uint8_t  reserved2[8];
+    uint32_t cei;
+    uint8_t  reserved2[4];
 } __attribute__ ((packed));
 typedef struct IplDeviceComponentEntry IplDeviceComponentEntry;
 
pc-bios/s390-ccw/s390-ccw.h +1 -0
index c2ba40d067..6d51d07c90 100644
@@ -69,6 +69,7 @@ void sclp_setup(void);
 void sclp_get_loadparm_ascii(char *loadparm);
 bool sclp_is_diag320_on(void);
 bool sclp_is_sipl_on(void);
+bool sclp_is_sclaf_on(void);
 int sclp_read(char *str, size_t count);
 
 /* virtio.c */
pc-bios/s390-ccw/sclp.c +8 -0
index 0b03c3164f..16f973dde8 100644
@@ -157,6 +157,14 @@ bool sclp_is_sipl_on(void)
     return fac_ipl & SCCB_FAC_IPL_SIPL_BIT;
 }
 
+bool sclp_is_sclaf_on(void)
+{
+    uint16_t fac_ipl = 0;
+
+    sclp_get_fac_ipl(&fac_ipl);
+    return fac_ipl & SCCB_FAC_IPL_SCLAF_BIT;
+}
+
 int sclp_read(char *str, size_t count)
 {
     ReadEventData *sccb = (void *)_sccb;
pc-bios/s390-ccw/sclp.h +1 -0
index cf147f4634..3441020d6b 100644
@@ -52,6 +52,7 @@ typedef struct SCCBHeader {
 #define SCCB_DATA_LEN (SCCB_SIZE - sizeof(SCCBHeader))
 #define SCCB_FAC134_DIAG320_BIT 0x4
 #define SCCB_FAC_IPL_SIPL_BIT 0x4000
+#define SCCB_FAC_IPL_SCLAF_BIT 0x1000
 
 typedef struct ReadInfo {
     SCCBHeader h;
pc-bios/s390-ccw/secure-ipl.c +409 -3

447 lines not on this page · raw message

pc-bios/s390-ccw/secure-ipl.h +110 -0

122 lines not on this page · raw message

Signature · 1 line
2.50.1
#57 lore raw

PATCH v5 23/29 Add secure-boot to s390-ccw-virtio machine type option

In reply to Zhuoying Cai

Add secure-boot as a parameter of s390-ccw-virtio machine type option.

The secure-boot=on|off parameter is implemented to enable secure IPL.

By default, secure-boot is set to false if not specified in the command line.

---
 docs/system/s390x/secure-ipl.rst   | 20 ++++++++++++++++----
 hw/s390x/s390-virtio-ccw.c         | 22 ++++++++++++++++++++++
 include/hw/s390x/s390-virtio-ccw.h |  1 +
 qemu-options.hx                    |  6 +++++-
 4 files changed, 44 insertions(+), 5 deletions(-)
docs/system/s390x/secure-ipl.rst +16 -4
index 40a5781c7d..0d14d0d62d 100644
@@ -19,19 +19,31 @@ paths or directories on the command-line:
                                boot-certs.0.path=/.../qemu/certs, \
                                boot-certs.1.path=/another/path/cert.pem ...
 
+Enabling Secure IPL
+-------------------
+
+Secure IPL is enabled by explicitly setting ``secure-boot=on``; if not specified,
+secure boot is considered off.
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio,secure-boot=on|off
+
 
 IPL Modes
 =========
 
 The concept of IPL Modes are introduced to differentiate between the IPL configurations.
-These modes are mutually exclusive and enabled based on the ``boot-certs`` option on the
-QEMU command line.
+These modes are mutually exclusive and enabled based on specific combinations of
+the ``secure-boot`` and ``boot-certs`` options on the QEMU command line.
 
 Normal Mode
 -----------
 
-The absence of certificates will attempt to IPL a guest without secure IPL operations.
-No checks are performed, and no warnings/errors are reported. This is the default mode.
+The absence of both certificates and the ``secure-boot`` option will attempt to
+IPL a guest without secure IPL operations. No checks are performed, and no
+warnings/errors are reported.  This is the default mode, and can be explicitly
+enabled with ``secure-boot=off``.
 
 Configuration:
 
hw/s390x/s390-virtio-ccw.c +22 -0
index 9ac425c695..1a1c905c7b 100644
@@ -823,6 +823,21 @@ static void machine_set_boot_certs(Object *obj, Visitor *v, const char *name,
     ms->boot_certs = cert_list;
 }
 
+static inline bool machine_get_secure_boot(Object *obj, Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+
+    return ms->secure_boot;
+}
+
+static inline void machine_set_secure_boot(Object *obj, bool value,
+                                            Error **errp)
+{
+    S390CcwMachineState *ms = S390_CCW_MACHINE(obj);
+
+    ms->secure_boot = value;
+}
+
 static void ccw_machine_class_init(ObjectClass *oc, const void *data)
 {
     MachineClass *mc = MACHINE_CLASS(oc);
@@ -881,6 +896,13 @@ static void ccw_machine_class_init(ObjectClass *oc, const void *data)
                               machine_get_boot_certs, machine_set_boot_certs, NULL, NULL);
     object_class_property_set_description(oc, "boot-certs",
             "provide paths to a directory and/or a certificate file for secure boot");
+
+    object_class_property_add_bool(oc, "secure-boot",
+                                   machine_get_secure_boot,
+                                   machine_set_secure_boot);
+    object_class_property_set_description(oc, "secure-boot",
+            "enable/disable secure boot");
+
 }
 
 static inline void s390_machine_initfn(Object *obj)
include/hw/s390x/s390-virtio-ccw.h +1 -0
index b90949355c..552c936da0 100644
@@ -33,6 +33,7 @@ struct S390CcwMachineState {
     uint64_t memory_limit;
     uint64_t max_pagesize;
     BootCertPathList *boot_certs;
+    bool secure_boot;
 
     SCLPDevice *sclp;
 };
qemu-options.hx +5 -1
index ac497eb3a0..5d9cd0d0f1 100644
@@ -45,7 +45,8 @@ DEF("machine", HAS_ARG, QEMU_OPTION_machine, \
     "                memory-backend='backend-id' specifies explicitly provided backend for main RAM (default=none)\n"
     "                cxl-fmw.0.targets.0=firsttarget,cxl-fmw.0.targets.1=secondtarget,cxl-fmw.0.size=size[,cxl-fmw.0.interleave-granularity=granularity]\n"
     "                smp-cache.0.cache=cachename,smp-cache.0.topology=topologylevel\n"
-    "                boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file provides paths to a directory and/or a certificate file\n",
+    "                boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file provides paths to a directory and/or a certificate file\n"
+    "                secure-boot=on|off enable/disable secure boot (default=off) \n",
     QEMU_ARCH_ALL)
 SRST
 ``-machine [type=]name[,prop=value[,...]]``
@@ -209,6 +210,9 @@ SRST
 
     ``boot-certs.0.path=/path/directory,boot-certs.1.path=/path/file``
         Provide paths to a directory and/or a certificate file on the host [s390x only].
+
+    ``secure-boot=on|off``
+        Enables or disables secure boot on s390-ccw guest. The default is off.
 ERST
 
 DEF("M", HAS_ARG, QEMU_OPTION_M,
Signature · 1 line
2.50.1
#58 lore raw

PATCH v5 24/29 hw/s390x/ipl: Set IPIB flags for secure IPL

In reply to Zhuoying Cai

If -secure-boot on is specified on the command line option, indicating true secure IPL enabled, set Secure-IPL bit and IPL-Information-Report bit on in IPIB Flags field, and trigger true secure IPL in the S390 BIOS.

Any error that occurs during true secure IPL will cause the IPL to terminate.

---
 hw/s390x/ipl.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
hw/s390x/ipl.c +17 -1
index d1a972ac8d..a196e1d648 100644
@@ -437,6 +437,11 @@ static bool s390_has_certificate(void)
     return ipl->cert_store.count > 0;
 }
 
+static bool s390_secure_boot_enabled(void)
+{
+    return S390_CCW_MACHINE(qdev_get_machine())->secure_boot;
+}
+
 static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
 {
     CcwDevice *ccw_dev = NULL;
@@ -494,6 +499,17 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
         s390_ipl_convert_loadparm((char *)lp, iplb->loadparm);
         iplb->flags |= DIAG308_FLAGS_LP_VALID;
 
+        /*
+         * If secure-boot is enabled, then toggle the secure IPL flags to trigger
+         * secure boot in the s390 BIOS.
+         *
+         * Boot process will terminate if any error occurs during secure boot.
+         *
+         * If SIPL is on, IPLIR must also be on.
+         */
+        if (s390_secure_boot_enabled()) {
+            iplb->hdr_flags |= (DIAG308_IPIB_FLAGS_SIPL | DIAG308_IPIB_FLAGS_IPLIR);
+        }
         /*
          * Secure boot in audit mode will perform
          * if certificate(s) exist in the key store.
@@ -503,7 +519,7 @@ static bool s390_build_iplb(DeviceState *dev_st, IplParameterBlock *iplb)
          *
          * Results of secure boot will be stored in IIRB.
          */
-        if (s390_has_certificate()) {
+        else if (s390_has_certificate()) {
             iplb->hdr_flags |= DIAG308_IPIB_FLAGS_IPLIR;
         }
 
Signature · 1 line
2.50.1
#59 lore raw

PATCH v5 25/29 pc-bios/s390-ccw: Handle true secure IPL mode

In reply to Zhuoying Cai

When secure boot is enabled (-secure-boot on) and certificate(s) are provided, the boot operates in True Secure IPL mode.

Any verification error during True Secure IPL mode will cause the entire boot process to terminate.

Secure IPL in audit mode requires at least one certificate provided in the key store along with necessary facilities. If secure boot is enabled but no certificate is provided, the boot process will also terminate, as this is not a valid secure boot configuration.

Note: True Secure IPL mode is implemented for the SCSI scheme of virtio-blk/virtio-scsi devices.

---
 docs/system/s390x/secure-ipl.rst | 16 ++++++++++++++++
 pc-bios/s390-ccw/bootmap.c       | 19 ++++++++++++++++---
 pc-bios/s390-ccw/main.c          |  7 ++++++-
 pc-bios/s390-ccw/s390-ccw.h      |  2 ++
 pc-bios/s390-ccw/secure-ipl.c    |  4 ++++
 pc-bios/s390-ccw/secure-ipl.h    |  3 +++
 6 files changed, 47 insertions(+), 4 deletions(-)
docs/system/s390x/secure-ipl.rst +16 -0
index 0d14d0d62d..8ab457f1e1 100644
@@ -66,3 +66,19 @@ Configuration:
     qemu-system-s390x -machine s390-ccw-virtio, \
                                boot-certs.0.path=/.../qemu/certs, \
                                boot-certs.1.path=/another/path/cert.pem ...
+
+Secure Mode
+-----------
+
+With *both* the presence of certificates in the store and the ``secure-boot=on``
+option, it is understood that secure boot should be performed with errors
+reported and boot will abort.
+
+Configuration:
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio, \
+                               secure-boot=on, \
+                               boot-certs.0.path=/.../qemu/certs, \
+                               boot-certs.1.path=/another/path/cert.pem ...
pc-bios/s390-ccw/bootmap.c +16 -3
index 3922e7cdde..3ab89b91fb 100644
@@ -737,6 +737,9 @@ static int zipl_run(ScsiBlockPtr *pte)
     entry = (ComponentEntry *)(&header[1]);
 
     switch (boot_mode) {
+    case ZIPL_BOOT_MODE_INVALID:
+        return -1;
+    case ZIPL_BOOT_MODE_SECURE:
     case ZIPL_BOOT_MODE_SECURE_AUDIT:
         if (zipl_run_secure(&entry, tmp_sec)) {
             return -1;
@@ -1118,9 +1121,16 @@ ZiplBootMode zipl_mode(uint8_t hdr_flags)
 {
     bool sipl_set = hdr_flags & DIAG308_IPIB_FLAGS_SIPL;
     bool iplir_set = hdr_flags & DIAG308_IPIB_FLAGS_IPLIR;
+    VCStorageSizeBlock *vcssb;
 
     if (!sipl_set && iplir_set) {
         return ZIPL_BOOT_MODE_SECURE_AUDIT;
+    } else if (sipl_set && iplir_set) {
+        vcssb = zipl_secure_get_vcssb();
+        if (vcssb == NULL || vcssb->length == VCSSB_NO_VC) {
+            return ZIPL_BOOT_MODE_INVALID;
+        }
+        return ZIPL_BOOT_MODE_SECURE;
     }
 
     return ZIPL_BOOT_MODE_NORMAL;
@@ -1131,7 +1141,8 @@ void zipl_load(void)
     VDev *vdev = virtio_get_device();
 
     if (vdev->is_cdrom) {
-        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
+            boot_mode == ZIPL_BOOT_MODE_SECURE) {
             panic("Secure boot from ISO image is not supported!");
         }
         ipl_iso_el_torito();
@@ -1140,7 +1151,8 @@ void zipl_load(void)
     }
 
     if (virtio_get_device_type() == VIRTIO_ID_NET) {
-        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
+            boot_mode == ZIPL_BOOT_MODE_SECURE) {
             panic("Virtio net boot device does not support secure boot!");
         }
         netmain();
@@ -1153,7 +1165,8 @@ void zipl_load(void)
         return;
     }
 
-    if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+    if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
+        boot_mode == ZIPL_BOOT_MODE_SECURE) {
         panic("ECKD boot device does not support secure boot!");
     }
 
pc-bios/s390-ccw/main.c +6 -1
index 668660e64d..c5b425209a 100644
@@ -277,10 +277,15 @@ static void ipl_boot_device(void)
         boot_mode = zipl_mode(iplb->hdr_flags);
     }
 
+    if (boot_mode == ZIPL_BOOT_MODE_INVALID) {
+        panic("Need at least one certificate for secure boot!");
+    }
+
     switch (cutype) {
     case CU_TYPE_DASD_3990:
     case CU_TYPE_DASD_2107:
-        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT) {
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
+            boot_mode == ZIPL_BOOT_MODE_SECURE) {
             panic("Passthrough (vfio) device does not support secure boot!");
         }
 
pc-bios/s390-ccw/s390-ccw.h +2 -0
index 6d51d07c90..389cc8ea7c 100644
@@ -83,9 +83,11 @@ int virtio_read(unsigned long sector, void *load_addr);
 void zipl_load(void);
 
 typedef enum ZiplBootMode {
+    ZIPL_BOOT_MODE_INVALID = -1,
     ZIPL_BOOT_MODE_UNSPECIFIED = 0,
     ZIPL_BOOT_MODE_NORMAL = 1,
     ZIPL_BOOT_MODE_SECURE_AUDIT = 2,
+    ZIPL_BOOT_MODE_SECURE = 3,
 } ZiplBootMode;
 
 extern ZiplBootMode boot_mode;
pc-bios/s390-ccw/secure-ipl.c +4 -0
index 8c696828cd..09554a55ae 100644
@@ -273,6 +273,10 @@ static bool check_sclab_presence(uint8_t *sclab_magic,
         comps->device_entries[comp_index].cei |= S390_IPL_COMPONENT_CEI_INVALID_SCLAB;
 
         /* a missing SCLAB will not be reported in audit mode */
+        if (boot_mode == ZIPL_BOOT_MODE_SECURE) {
+            zipl_secure_handle("Magic is not matched. SCLAB does not exist");
+         }
+
         return false;
     }
 
pc-bios/s390-ccw/secure-ipl.h +3 -0
index d60201bf45..9ddb5b79b7 100644
@@ -58,6 +58,9 @@ static inline void zipl_secure_handle(const char *message)
     case ZIPL_BOOT_MODE_SECURE_AUDIT:
         IPL_check(false, message);
         break;
+    case ZIPL_BOOT_MODE_SECURE:
+        IPL_assert(false, message);
+        break;
     default:
         break;
     }
Signature · 1 line
2.50.1
#60 lore raw

PATCH v5 26/29 pc-bios/s390-ccw: Handle secure boot with multiple boot devices

In reply to Zhuoying Cai

The current approach to enable secure boot relies on providing secure-boot and boot-certs parameters of s390-ccw-virtio machine type option, which apply to all boot devices.

With the possibility of multiple boot devices, secure boot expects all provided devices to be supported and eligible (e.g., virtio-blk/virtio-scsi using the SCSI scheme).

If multiple boot devices are provided and include an unsupported (e.g., ECKD, VFIO) or a non-eligible (e.g., Net) device, the boot process will terminate with an error logged to the console.

---
 pc-bios/s390-ccw/bootmap.c  | 31 ++++++++-------
 pc-bios/s390-ccw/main.c     | 75 ++++++++++++++++++++++++++++++++++---
 pc-bios/s390-ccw/s390-ccw.h |  1 +
 3 files changed, 88 insertions(+), 19 deletions(-)
pc-bios/s390-ccw/bootmap.c +18 -13
index 3ab89b91fb..8297f22c3c 100644
@@ -1136,25 +1136,35 @@ ZiplBootMode zipl_mode(uint8_t hdr_flags)
     return ZIPL_BOOT_MODE_NORMAL;
 }
 
+int zipl_check_scsi_mbr_magic(void)
+{
+    ScsiMbr *mbr = (void *)sec;
+
+    /* Grab the MBR */
+    memset(sec, FREE_SPACE_FILLER, sizeof(sec));
+    if (virtio_read(0, mbr)) {
+        puts("Cannot read block 0");
+        return -EIO;
+    }
+
+    if (!magic_match(mbr->magic, ZIPL_MAGIC)) {
+        return -1;
+    }
+
+    return 0;
+}
+
 void zipl_load(void)
 {
     VDev *vdev = virtio_get_device();
 
     if (vdev->is_cdrom) {
-        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
-            boot_mode == ZIPL_BOOT_MODE_SECURE) {
-            panic("Secure boot from ISO image is not supported!");
-        }
         ipl_iso_el_torito();
         puts("Failed to IPL this ISO image!");
         return;
     }
 
     if (virtio_get_device_type() == VIRTIO_ID_NET) {
-        if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
-            boot_mode == ZIPL_BOOT_MODE_SECURE) {
-            panic("Virtio net boot device does not support secure boot!");
-        }
         netmain();
         puts("Failed to IPL from this network!");
         return;
@@ -1165,11 +1175,6 @@ void zipl_load(void)
         return;
     }
 
-    if (boot_mode == ZIPL_BOOT_MODE_SECURE_AUDIT ||
-        boot_mode == ZIPL_BOOT_MODE_SECURE) {
-        panic("ECKD boot device does not support secure boot!");
-    }
-
     switch (virtio_get_device_type()) {
     case VIRTIO_ID_BLOCK:
         zipl_load_vblk();
pc-bios/s390-ccw/main.c +69 -6

97 lines not on this page · raw message

pc-bios/s390-ccw/s390-ccw.h +1 -0
index 389cc8ea7c..3009104686 100644
@@ -93,6 +93,7 @@ typedef enum ZiplBootMode {
 extern ZiplBootMode boot_mode;
 
 ZiplBootMode zipl_mode(uint8_t hdr_flags);
+int zipl_check_scsi_mbr_magic(void);
 
 /* jump2ipl.c */
 void write_reset_psw(uint64_t psw);
Signature · 1 line
2.50.1
#61 lore raw

PATCH v5 27/29 hw/s390x/ipl: Handle secure boot without specifying a boot device

In reply to Zhuoying Cai

If secure boot in audit mode or True Secure IPL mode is enabled without specifying a boot device, the boot process will terminate with an error.

---
 hw/s390x/ipl.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
hw/s390x/ipl.c +10 -0
index a196e1d648..da50b52c75 100644
@@ -764,6 +764,16 @@ void s390_ipl_prepare_cpu(S390CPU *cpu)
         s390_ipl_create_cert_store(&ipl->cert_store);
         if (!ipl->iplb_valid) {
             ipl->iplb_valid = s390_init_all_iplbs(ipl);
+
+            /*
+             * Secure IPL without specifying a boot device.
+             * IPLB is not generated if no boot device is defined.
+             */
+            if ((s390_has_certificate() || s390_secure_boot_enabled()) &&
+                !ipl->iplb_valid) {
+                error_report("No boot device defined for Secure IPL");
+                exit(1);
+            }
         } else {
             ipl->qipl.chain_len = 0;
         }
Signature · 1 line
2.50.1
#62 lore raw

PATCH v5 28/29 docs/specs: Add secure IPL documentation

In reply to Zhuoying Cai

Add documentation for secure IPL

---
 docs/specs/s390x-secure-ipl.rst | 53 +++++++++++++++++++++++++++++++++
 1 file changed, 53 insertions(+)
docs/specs/s390x-secure-ipl.rst +53 -0
index 72ab901014..dab25cb8c1 100644
@@ -1,5 +1,58 @@
 .. SPDX-License-Identifier: GPL-2.0-or-later
 
+s390 Secure IPL
+===============
+
+Secure IPL (a.k.a. secure boot) enables s390-ccw virtual machines to
+leverage qcrypto libraries and z/Architecture emulations to verify the
+integrity of signed kernels. The qcrypto libraries are used to perform
+certificate validation and signature-verification, whereas the
+z/Architecture emulations are used to ensure secure IPL data has not
+been tampered with, convey data between QEMU and userspace, and set up
+the relevant secure IPL data structures with verification results.
+
+To find out more about using this feature, see ``docs/system/s390x/secure-ipl.rst``.
+
+Note that "userspace" will refer to the s390-ccw BIOS unless stated
+otherwise.
+
+Both QEMU and userspace work in tandem to perform secure IPL. The Secure
+Loading Attributes Facility (SCLAF) is used to check the Secure Code
+Loading Attribute Block (SCLAB) and ensure that secure IPL data has not
+been tampered with. DIAGNOSE 'X'320' is invoked by userspace to query
+the certificate store info and retrieve specific certificates from QEMU.
+DIAGNOSE 'X'508' is used by userspace to leverage qcrypto libraries to
+perform signature-verification in QEMU. Lastly, userspace generates and
+appends an IPL Information Report Block (IIRB) at the end of the IPL
+Parameter Block, which is used by the kernel to store signed and
+verified entries.
+
+The logical steps are as follows:
+
+- Userspace reads data payload from disk (e.g. stage3 boot loader, kernel)
+- Userspace checks the validity of the SCLAB
+- Userspace invokes DIAG 508 subcode 1 and provides it the payload
+- QEMU handles DIAG 508 request by reading the payload and retrieving the
+  certificate store
+- QEMU DIAG 508 utilizes qcrypto libraries to perform signature-verification on
+  the payload, attempting with each cert in the store (until success or exhausted)
+- QEMU DIAG 508 returns:
+
+  - success: index of cert used to verify payload
+  - failure: error code
+
+- Userspace responds to this operation:
+
+  - success: retrieves cert from store via DIAG 320 using returned index
+  - failure: reports with warning (audit mode), aborts with error (secure mode)
+
+- Userspace appends IIRB at the end of the IPLB
+- Userspace kicks off IPL
+
+More information regarding the respective DIAGNOSE commands and IPL data
+structures are outlined within this document.
+
+
 s390 Certificate Store and Functions
 ====================================
 
Signature · 1 line
2.50.1
#63 lore raw

PATCH v5 29/29 docs/system/s390x: Add secure IPL documentation

In reply to Zhuoying Cai

Add documentation for secure IPL

---
 docs/system/s390x/secure-ipl.rst | 96 ++++++++++++++++++++++++++++++++
 1 file changed, 96 insertions(+)
docs/system/s390x/secure-ipl.rst +96 -0
index 8ab457f1e1..5842ed83d0 100644
@@ -1,5 +1,21 @@
 .. SPDX-License-Identifier: GPL-2.0-or-later
 
+s390 Secure IPL
+===============
+
+Secure IPL, also known as secure boot, enables s390-ccw virtual machines to
+verify the integrity of guest kernels.
+
+For technical details of this feature, see ``docs/specs/s390x-secure-ipl.rst``.
+
+This document explains how to use secure IPL with s390x in QEMU. It covers
+new command line options for providing certificates and enabling secure IPL,
+the different IPL modes (Normal, Audit, and Secure), and system requirements.
+
+A quickstart guide is provided to demonstrate how to generate certificates,
+sign images, and start a guest in Secure Mode.
+
+
 Secure IPL Command Line Options
 ===============================
 
@@ -82,3 +98,83 @@ Configuration:
                                secure-boot=on, \
                                boot-certs.0.path=/.../qemu/certs, \
                                boot-certs.1.path=/another/path/cert.pem ...
+
+
+Constraints
+===========
+
+The following constraints apply when attempting to secure IPL an s390 guest:
+
+- z16 CPU model
+- certificates must be in X.509 PEM format
+- only support for SCSI scheme of virtio-blk/virtio-scsi devices
+- a boot device must be specified
+- any unsupported devices (e.g., ECKD and VFIO) or non-eligible devices (e.g.,
+  Net) will cause the entire boot process terminating early with an error
+  logged to the console.
+
+
+Secure IPL Quickstart
+=====================
+
+Build QEMU with gnutls enabled
+-------------------------------
+
+.. code-block:: shell
+
+    ./configure … --enable-gnutls
+
+Generate certificate (e.g. via certtool)
+----------------------------------------
+
+A private key is required before generating a certificate. This key must be kept secure
+and confidential.
+
+Use an RSA private key for signing.
+
+.. code-block:: shell
+
+    certtool --generate-privkey > key.pem
+
+A self-signed certificate requires the organization name. Use the ``cert.info`` template
+to pre-fill values and avoid interactive prompts from certtool.
+
+.. code-block:: shell
+
+    cat > cert.info <<EOF
+    cn = "My Name"
+    expiration_days = 36500
+    cert_signing_key
+    EOF
+
+    certtool --generate-self-signed \
+             --load-privkey key.pem \
+             --template cert.info \
+             --hash=SHA256 \
+             --outfile cert.pem
+
+Sign Images (e.g. via sign-file)
+--------------------------------
+
+- signing must be performed on a KVM guest filesystem
+- sign-file script used in the example below is located within the kernel source
+  repo
+
+.. code-block:: shell
+
+    ./sign-file sha256 key.pem cert.pem /boot/vmlinuz-…
+    ./sign-file sha256 key.pem cert.pem /usr/lib/s390-tools/stage3.bin
+
+Run zipl with secure boot enabled
+---------------------------------
+
+.. code-block:: shell
+
+    zipl --secure 1 -V
+
+Start Guest with Cmd Options
+----------------------------
+
+.. code-block:: shell
+
+    qemu-system-s390x -machine s390-ccw-virtio,secure-boot=on,boot-certs.0.path=cert.pem ...
Signature · 1 line
2.50.1