From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832104; cv=none; d=zohomail.com; s=zohoarc; b=TQ+7OI/wNfVxMbO76wWyzOfJGBtqHtI+yEBQYBLqbo4L/7/jpK624pyk6L8BOfOqnukJOPFhnYeKpjA5oDKrNONyjLFEPt0MTq6EJKkths/dWGwgFXxts/L5vbwcLv38SqFzVBZrqhNP255S0eMTCoLGZ32Sk3IcsMvuIsQePTc= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832104; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=eqxhYyeojQe2Ib53kjbVyPX79LdO/gqtoV91n+Zc3z4=; b=Tl6k8dMxhaR+FhZzT7fKGWt8XUY6DCjWmPnCdbJZh1ArSQuTr061k5sS0c+zLFFeJXVptnB5G9eqkzkYKQ2edCzwkYRGVu8Tn3GRM4R3WyrTP3pYvF1SHsNNi5J12l74678lzg5Rb7PbbmB1qHD/fUq3jx6AmoBuwE2nM1Y3i7o= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832104828577.1888891662483; Mon, 7 Nov 2022 06:41:44 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-496-3CkUfKx4MACZFVdflX3i5g-1; Mon, 07 Nov 2022 09:41:39 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.rdu2.redhat.com [10.11.54.7]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id BEB39101A54E; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id AAE44140EBF5; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 3F508194658F; Mon, 7 Nov 2022 14:41:31 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 39EAF1946587 for ; Mon, 7 Nov 2022 14:41:30 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 2F8EA40C2143; Mon, 7 Nov 2022 14:41:30 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 8266340C2064; Mon, 7 Nov 2022 14:41:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832103; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=eqxhYyeojQe2Ib53kjbVyPX79LdO/gqtoV91n+Zc3z4=; b=hOuTF01GeAAFdUsbkzC9KZnjFy//eZgEvCL8hu2aSHPbS08/vlhV8d4y8lbpLptDIZDsZG +XE0lia6MMYWk/KR52Hy/k733cM5w7zY8H0VLPBD7wUwUTfbgv1J7rBFlpUCQ7qs/xqMUu cSRGvS9rVR4v5Vwd+HOseVvvXfzaTZo= X-MC-Unique: 3CkUfKx4MACZFVdflX3i5g-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 01/12] build-aux: only forbid gethostname in C files Date: Mon, 7 Nov 2022 14:41:16 +0000 Message-Id: <20221107144127.973324-2-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.7 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832106416100001 This function is fine to use in other languages Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- build-aux/syntax-check.mk | 1 + 1 file changed, 1 insertion(+) diff --git a/build-aux/syntax-check.mk b/build-aux/syntax-check.mk index 68cd9dff5f..e1d80bd536 100644 --- a/build-aux/syntax-check.mk +++ b/build-aux/syntax-check.mk @@ -203,6 +203,7 @@ sc_prohibit_readlink: =20 sc_prohibit_gethostname: @prohibit=3D'gethostname *\(' \ + in_vc_files=3D'\.[ch]$$' \ halt=3D'use virGetHostname, not gethostname' \ $(_sc_search_regexp) =20 --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832099; cv=none; d=zohomail.com; s=zohoarc; b=dTyabk1NUtW0jdcYCng63oJ11A08XlznxWV5F5u2iWkZMqkNop3JrWBzjWf5+Wx2DBkGkm7SgOWzif0uAnQDStkvM19t3koZPc9Z1cLkDR58x6NJ+5OB8yhvlP7zGPmOEC3f7J65inaPHJi9FV4l7owHm6AXxiIvPflMhJ88q24= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832099; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=tSl0Qo43H320Kc2stgLLsKwjEyUKHgW0OhdTfS3RJ1k=; b=IT2a6JJsNpE8jLM0iEblYsYUo0OWlBPiMS149Za48/Oiem6PVnrd4wcF8rPv4m1O3tHUnYNedSkSLptIBdGiIIiyQYhW2hiY4JIPWGYO/KCqoy5Db7ha9BLt9Y441lgFWKnyZDigebK1892p9CCF+PvEgQqmHEIQv+9e35DoBDU= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832099586736.9829532034366; Mon, 7 Nov 2022 06:41:39 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-548-LVCbk-tqOJibUfyROx97bQ-1; Mon, 07 Nov 2022 09:41:36 -0500 Received: from smtp.corp.redhat.com (int-mx06.intmail.prod.int.rdu2.redhat.com [10.11.54.6]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id C33BB185A7AF; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id AE3FD2166B29; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id A12051946588; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 54B0519465B6 for ; Mon, 7 Nov 2022 14:41:31 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 39E7340C2143; Mon, 7 Nov 2022 14:41:31 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 6D22F40C2064; Mon, 7 Nov 2022 14:41:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832098; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=tSl0Qo43H320Kc2stgLLsKwjEyUKHgW0OhdTfS3RJ1k=; b=WGLUrajg+iFSaHxm/Az+IBp+/XGogxtqr/fGTjVLhZXDt2LGJ9snB0dFdWjCdAq9FUIxzF 4g+J9kT015ukpslAT0uqbJdxHkHg30My+pwLTEqd6kpPb8YMzjNIm0DkVOS+C124he0+L4 2CJoRBUFfANoKnHD4VWu7WJ0KjQPDx4= X-MC-Unique: LVCbk-tqOJibUfyROx97bQ-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 02/12] tools: support validating SEV firmware boot measurements Date: Mon, 7 Nov 2022 14:41:17 +0000 Message-Id: <20221107144127.973324-3-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.6 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832100414100002 The virt-qemu-sev-validate program will compare a reported SEV/SEV-ES domain launch measurement, to a computed launch measurement. This determines whether the domain has been tampered with during launch. This initial implementation requires all inputs to be provided explicitly, and as such can run completely offline, without any connection to libvirt. The tool is placed in the libvirt-client-qemu sub-RPM since it is specific to the QEMU driver. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/meson.build | 1 + docs/manpages/virt-qemu-sev-validate.rst | 207 ++++++++++++++++++ libvirt.spec.in | 2 + tools/meson.build | 5 + tools/virt-qemu-sev-validate | 263 +++++++++++++++++++++++ 5 files changed, 478 insertions(+) create mode 100644 docs/manpages/virt-qemu-sev-validate.rst create mode 100755 tools/virt-qemu-sev-validate diff --git a/docs/manpages/meson.build b/docs/manpages/meson.build index b5556996a4..84b2e247e9 100644 --- a/docs/manpages/meson.build +++ b/docs/manpages/meson.build @@ -20,6 +20,7 @@ docs_man_files =3D [ { 'name': 'virt-qemu-run', 'section': '1', 'install': conf.has('WITH_QEM= U') }, { 'name': 'virt-qemu-qmp-proxy', 'section': '1', 'install': conf.has('WI= TH_QEMU') }, { 'name': 'virt-xml-validate', 'section': '1', 'install': true }, + { 'name': 'virt-qemu-sev-validate', 'section': '1', 'install': conf.has(= 'WITH_QEMU') }, =20 { 'name': 'libvirt-guests', 'section': '8', 'install': conf.has('WITH_LI= BVIRTD') }, { 'name': 'libvirtd', 'section': '8', 'install': conf.has('WITH_LIBVIRTD= ') }, diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst new file mode 100644 index 0000000000..0f6c64ba90 --- /dev/null +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -0,0 +1,207 @@ +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D +virt-qemu-sev-validate +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +-------------------------------------------- +validate a domain AMD SEV launch measurement +-------------------------------------------- + +:Manual section: 1 +:Manual group: Virtualization Support + +.. contents:: + +SYNOPSIS +=3D=3D=3D=3D=3D=3D=3D=3D + + +``virt-qemu-sev-validate`` [*OPTIONS*] + + +DESCRIPTION +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +This program validates the reported measurement for a domain launched with= AMD +SEV. If the program exits with a status of zero, the guest owner can be +confident that their guest OS is running under the protection offered by t= he +SEV / SEV-ES platform. + +Note that the level of protection varies depending on the AMD SEV platform +generation and describing the differences is outside the scope of this +document. + +For the results of this program to be considered trustworthy, it is requir= ed to +be run on a machine that is already trusted by the guest owner. This could= be a +machine that the guest owner has direct physical control over, or it could= be +another virtual machine protected by AMD SEV that has already had its laun= ch +measurement validated. Running this program on the virtualization host wil= l not +produce an answer that can be trusted. + +OPTIONS +=3D=3D=3D=3D=3D=3D=3D + +Common options +-------------- + +``-h``, ``--help`` + +Display command line help usage then exit. + +``-d``, ``--debug`` + +Show debug information while running + +``-q``, ``--quiet`` + +Don't print information about the attestation result. + +Guest state options +------------------- + +These options provide information about the state of the guest that needs = its +boot attested. + +``--measurement BASE64-STRING`` + +The launch measurement reported by the hypervisor of the domain to be vali= dated. +The measurement must be 48 bytes of binary data encoded as a base64 string. + +``--api-major VERSION`` + +The SEV API major version of the hypervisor the domain is running on. + +``--api-minor VERSION`` + +The SEV API major version of the hypervisor the domain is running on. + +``--build-id ID`` + +The SEV build ID of the hypervisor the domain is running on. + +``--policy POLiCY`` + +The policy bitmask associated with the session launch data of the domain t= o be +validated. + +Guest config options +-------------------- + +These options provide items needed to calculate the expected domain launch +measurement. This will then be compared to the reported launch measurement. + +``-f PATH``, ``--firmware=3DPATH`` + +Path to the firmware loader binary. This is the EDK2 build that knows how = to +initialize AMD SEV. For the validation to be trustworthy it important that= the +firmware build used has no support for loading non-volatile variables from +NVRAM, even if NVRAM is expose to the guest. + +``--tik PATH`` + +TIK file for domain. This file must be exactly 16 bytes in size and contai= ns the +unique transport integrity key associated with the domain session launch d= ata. +This is mutually exclusive with the ``--tk`` argument. + +``--tek PATH`` + +TEK file for domain. This file must be exactly 16 bytes in size and contai= ns the +unique transport encryption key associated with the domain session launch = data. +This is mutually exclusive with the ``--tk`` argument. + +``--tk PATH`` + +TEK/TIK combined file for the domain. This file must be exactly 32 bytes in +size, with the first 16 bytes containing the TEK and the last 16 bytes +containing the TIK. This is mutually exclusive with the ``--tik`` and ``-= -tek`` +arguments. + +EXAMPLES +=3D=3D=3D=3D=3D=3D=3D=3D + +Fully offline execution +----------------------- + +This scenario allows a measurement to be securely validated in a completely +offline state without any connection to the hypervisor host. All required +data items must be provided as command line parameters. This usage model is +considered secure, because all input data is provided by the user. + +Validate the measurement of a SEV guest booting from disk: + +:: + + # virt-qemu-sev-validate \ + --firmware OVMF.sev.fd \ + --tk this-guest-tk.bin \ + --measurement Zs2pf19ubFSafpZ2WKkwquXvACx9Wt/BV+eJwQ/taO8jhyIj/F8sw= FrybR1fZ2ID \ + --api-major 0 \ + --api-minor 24 \ + --build-id 13 \ + --policy 3 + +EXIT STATUS +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + +Upon successful attestation of the launch measurement, an exit status of 0= will +be set. + +Upon failure to attest the launch measurement one of the following codes w= ill +be set: + +* **1** - *Guest measurement did not validate* + + Assuming the inputs to this program are correct, the virtual machine lau= nch + has been compromised and it should not be trusted henceforth. + +* **2** - *Usage scenario cannot be supported* + + The way in which this program has been invoked prevent it from being abl= e to + validate the launch measurement. + +* **3** - *unexpected error occurred in the code* + + A logic flaw in this program means it is unable to complete the validati= on of + the measurement. This is a bug which should be reported to the maintaine= rs. + +AUTHOR +=3D=3D=3D=3D=3D=3D + +Daniel P. Berrang=C3=A9 + + +BUGS +=3D=3D=3D=3D + +Please report all bugs you discover. This should be done via either: + +#. the mailing list + + `https://libvirt.org/contact.html `_ + +#. the bug tracker + + `https://libvirt.org/bugs.html `_ + +Alternatively, you may report bugs to your software distributor / vendor. + + +COPYRIGHT +=3D=3D=3D=3D=3D=3D=3D=3D=3D + +Copyright (C) 2022 by Red Hat, Inc. + + +LICENSE +=3D=3D=3D=3D=3D=3D=3D + +``virt-qemu-sev-validate`` is distributed under the terms of the GNU LGPL = v2.1+. +This is free software; see the source for copying conditions. There +is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE + + +SEE ALSO +=3D=3D=3D=3D=3D=3D=3D=3D + +virsh(1), `SEV launch security usage `_, +`https://www.libvirt.org/ `_ diff --git a/libvirt.spec.in b/libvirt.spec.in index 5ea9ef2912..a24e4d1159 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -2179,7 +2179,9 @@ exit 0 %if %{with_qemu} %files client-qemu %{_mandir}/man1/virt-qemu-qmp-proxy.1* +%{_mandir}/man1/virt-qemu-sev-validate.1* %{_bindir}/virt-qemu-qmp-proxy +%{_bindir}/virt-qemu-sev-validate %endif =20 %files libs -f %{name}.lang diff --git a/tools/meson.build b/tools/meson.build index 20509906af..c41c619af4 100644 --- a/tools/meson.build +++ b/tools/meson.build @@ -299,6 +299,11 @@ if conf.has('WITH_SANLOCK') ) endif =20 +if conf.has('WITH_QEMU') + install_data('virt-qemu-sev-validate', + install_dir: bindir) +endif + if conf.has('WITH_LIBVIRTD') configure_file( input: 'libvirt-guests.sh.in', diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate new file mode 100755 index 0000000000..7ff54e7623 --- /dev/null +++ b/tools/virt-qemu-sev-validate @@ -0,0 +1,263 @@ +#!/usr/bin/python3 +# +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# Validates a guest AMD SEV launch measurement +# +# A general principle in writing this tool is that it must calculate the +# expected measurement based entirely on information it receives on the CLI +# from the guest owner. +# +# It cannot generally trust information obtained from the guest XML or fro= m the +# virtualization host OS. The main exceptions are: +# +# - The guest measurement +# +# This is a result of cryptographic operation using a shared secret kno= wn +# only to the guest owner and SEV platform, not the host OS. +# +# - The guest policy +# +# This is encoded in the launch session blob that is encrypted with a s= hared +# secret known only to the guest owner and SEV platform, not the host O= S. It +# is impossible for the host OS to maliciously launch a guest with diff= erent +# policy and the user provided launch session blob. +# +# CAVEAT: the user must ALWAYS create a launch blob with freshly genera= ted +# TIK/TEK for every new VM. Re-use of the same TIK/TEK for multiple VMs +# is insecure. +# +# - The SEV API version / build ID +# +# This does not have an impact on the security of the measurement, unle= ss +# the guest owner needs a guarantee that the host is not using specific +# firmware versions with known flaws. +# + +import argparse +from base64 import b64decode +from hashlib import sha256 +import hmac +import logging +import sys +import traceback + +log =3D logging.getLogger() + + +class AttestationFailedException(Exception): + pass + + +class UnsupportedUsageException(Exception): + pass + + +class ConfidentialVM(object): + + def __init__(self, + measurement=3DNone, + api_major=3DNone, + api_minor=3DNone, + build_id=3DNone, + policy=3DNone): + self.measurement =3D measurement + self.api_major =3D api_major + self.api_minor =3D api_minor + self.build_id =3D build_id + self.policy =3D policy + + self.firmware =3D None + self.tik =3D None + self.tek =3D None + + def load_tik_tek(self, tik_path, tek_path): + with open(tik_path, 'rb') as fh: + self.tik =3D fh.read() + log.debug("TIK(hex): %s", self.tik.hex()) + + if len(self.tik) !=3D 16: + raise UnsupportedUsageException( + "Expected 16 bytes in TIK file, but got %d" % len(self.tik= )) + + with open(tek_path, 'rb') as fh: + self.tek =3D fh.read() + log.debug("TEK(hex): %s", self.tek.hex()) + + if len(self.tek) !=3D 16: + raise UnsupportedUsageException( + "Expected 16 bytes in TEK file, but got %d" % len(self.tek= )) + + def load_tk(self, tk_path): + with open(tk_path, 'rb') as fh: + tk =3D fh.read() + + if len(tk) !=3D 32: + raise UnsupportedUsageException( + "Expected 32 bytes in TIK/TEK file, but got %d" % len(tk)) + + self.tek =3D tk[0:16] + self.tik =3D tk[16:32] + log.debug("TIK(hex): %s", self.tik.hex()) + log.debug("TEK(hex): %s", self.tek.hex()) + + def load_firmware(self, firmware_path): + with open(firmware_path, 'rb') as fh: + self.firmware =3D fh.read() + log.debug("Firmware(sha256): %s", sha256(self.firmware).hexdigest(= )) + + # Get the full set of measured launch data for the domain + # + # The measured data that the guest is initialized with is the concaten= ation + # of the following: + # + # - The firmware blob + def get_measured_data(self): + measured_data =3D self.firmware + log.debug("Measured-data(sha256): %s", + sha256(measured_data).hexdigest()) + return measured_data + + # Get the reported and computed launch measurements for the domain + # + # AMD Secure Encrypted Virtualization API , section 6.5: + # + # measurement =3D HMAC(0x04 || API_MAJOR || API_MINOR || BUILD || + # GCTX.POLICY || GCTX.LD || MNONCE; GCTX.TIK) + # + # Where GCTX.LD covers all the measured data the guest is initialized = with + # per get_measured_data(). + def get_measurements(self): + measurement =3D b64decode(self.measurement) + reported =3D measurement[0:32] + nonce =3D measurement[32:48] + + measured_data =3D self.get_measured_data() + msg =3D ( + bytes([0x4]) + + self.api_major.to_bytes(1, 'little') + + self.api_minor.to_bytes(1, 'little') + + self.build_id.to_bytes(1, 'little') + + self.policy.to_bytes(4, 'little') + + sha256(measured_data).digest() + + nonce + ) + log.debug("Measured-msg(hex): %s", msg.hex()) + + computed =3D hmac.new(self.tik, msg, 'sha256').digest() + + log.debug("Measurement reported(hex): %s", reported.hex()) + log.debug("Measurement computed(hex): %s", computed.hex()) + + return reported, computed + + def attest(self): + reported, computed =3D self.get_measurements() + + if reported !=3D computed: + raise AttestationFailedException( + "Measurement does not match, VM is not trustworthy") + + +def parse_command_line(): + parser =3D argparse.ArgumentParser( + description=3D'Validate guest AMD SEV launch measurement') + parser.add_argument('--debug', '-d', action=3D'store_true', + help=3D'Show debug information') + parser.add_argument('--quiet', '-q', action=3D'store_true', + help=3D'Do not display status') + + # Arguments related to the state of the launched guest + vmstate =3D parser.add_argument_group("Virtual machine launch state") + vmstate.add_argument('--measurement', '-m', required=3DTrue, + help=3D'Measurement for the running domain') + vmstate.add_argument('--api-major', type=3Dint, required=3DTrue, + help=3D'SEV API major version for the running dom= ain') + vmstate.add_argument('--api-minor', type=3Dint, required=3DTrue, + help=3D'SEV API minor version for the running dom= ain') + vmstate.add_argument('--build-id', type=3Dint, required=3DTrue, + help=3D'SEV build ID for the running domain') + vmstate.add_argument('--policy', type=3Dint, required=3DTrue, + help=3D'SEV policy for the running domain') + + # Arguments related to calculation of the expected launch measurement + vmconfig =3D parser.add_argument_group("Virtual machine config") + vmconfig.add_argument('--firmware', '-f', required=3DTrue, + help=3D'Path to the firmware binary') + vmconfig.add_argument('--tik', + help=3D'TIK file for domain') + vmconfig.add_argument('--tek', + help=3D'TEK file for domain') + vmconfig.add_argument('--tk', + help=3D'TEK/TIK combined file for domain') + + return parser.parse_args() + + +# Sanity check the set of CLI args specified provide enough info for us to= do +# the job +def check_usage(args): + if args.tk is not None: + if args.tik is not None or args.tek is not None: + raise UnsupportedUsageException( + "--tk is mutually exclusive with --tek/--tik") + else: + if args.tik is None or args.tek is None: + raise UnsupportedUsageException( + "Either --tk or both of --tek/--tik are required") + + +def attest(args): + cvm =3D ConfidentialVM(measurement=3Dargs.measurement, + api_major=3Dargs.api_major, + api_minor=3Dargs.api_minor, + build_id=3Dargs.build_id, + policy=3Dargs.policy) + + cvm.load_firmware(args.firmware) + + if args.tk is not None: + cvm.load_tk(args.tk) + else: + cvm.load_tik_tek(args.tik, args.tek) + + cvm.attest() + + if not args.quiet: + print("OK: Looks good to me") + +def main(): + args =3D parse_command_line() + if args.debug: + logging.basicConfig(level=3D"DEBUG") + formatter =3D logging.Formatter("[%(levelname)s]: %(message)s") + handler =3D log.handlers[0] + handler.setFormatter(formatter) + + try: + check_usage(args) + + attest(args) + + sys.exit(0) + except AttestationFailedException as e: + if args.debug: + traceback.print_tb(e.__traceback__) + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(1) + except UnsupportedUsageException as e: + if args.debug: + traceback.print_tb(e.__traceback__) + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(2) + except Exception as e: + if args.debug: + traceback.print_tb(e.__traceback__) + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(3) + +if __name__ =3D=3D "__main__": + main() --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832127; cv=none; d=zohomail.com; s=zohoarc; b=iKZxmHJgmd//+x88LuCq+sOeYPvi48lfIkoiiaQRX41Ek3xyJt3t9KZJpfxXO41iSBVagnHl09aFDGqe8kszrugCDf/3OoYw+JyCPdMhTxv8eaJcdF4Efaz+WiVG+LRFZy5Z/8amOgZ8e2i/eBStDsRKNdFoY722K3n4mCpjH+o= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832127; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=iOpvam1gmiwQXosm8ijvEp/lSmIuryTenZq0iHc//aQ=; b=DnPRv3KSTJK6e+gpQ5+sRUk+j7ssJgKf4f3JZTgev0ao8V4+XkO9+FuPoirDnJRALiaJCA1rV1zfoDSXlO8GJ/sk3CPUGdOzwYd/cBhHE4wlsaG0DRUkdy0rSVCfvLpqW0O5VTicti/4MDQ7fZ1M7+9PJ9vm47HdVhU3NFZ6fZA= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832127645866.0369205028488; Mon, 7 Nov 2022 06:42:07 -0800 (PST) Received: from mimecast-mx02.redhat.com (mx3-rdu2.redhat.com [66.187.233.73]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-452-A2qEnvcUNHCQ9yleywHw_g-1; Mon, 07 Nov 2022 09:41:49 -0500 Received: from smtp.corp.redhat.com (int-mx04.intmail.prod.int.rdu2.redhat.com [10.11.54.4]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 15D222932498; Mon, 7 Nov 2022 14:41:47 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id F2C062028CE4; Mon, 7 Nov 2022 14:41:46 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id DEEB91946A43; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 6439D1946587 for ; Mon, 7 Nov 2022 14:41:32 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 4942440C83EC; Mon, 7 Nov 2022 14:41:32 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 7AF7C40C2064; Mon, 7 Nov 2022 14:41:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832126; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=iOpvam1gmiwQXosm8ijvEp/lSmIuryTenZq0iHc//aQ=; b=gxPsqXxHY4rsuUKMARCj0u6Fpffa68XGm6lzZFT24zISj7Ja6ZB58AaENzZt5TkJGZbCQ+ dPvAKWWVS/FZmzu1YHtWYPWbEBCkDRlmn9Vc1Wekdcf5E4y1BqM+nPiOCBu3K2z/uMj8tg 1xTu8oiPOVQ4sPt8ezVwvDs/1Mws1qc= X-MC-Unique: A2qEnvcUNHCQ9yleywHw_g-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 03/12] tools: load guest config from libvirt Date: Mon, 7 Nov 2022 14:41:18 +0000 Message-Id: <20221107144127.973324-4-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.4 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832128686100001 Accept information about a connection to libvirt and a guest on the command line. Talk to libvirt to obtain the running guest state and automatically detect as much configuration as possible. It will refuse to use a libvirt connection that is thought to be local to the current machine, as running this tool on the hypervisor itself is not considered secure. This can be overridden using the --insecure flag. When querying the guest, it will also analyse the XML configuration in an attempt to detect any options that are liable to be mistakes. For example the NVRAM being measured should not have a persistent varstore. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 111 +++++++++++- tools/virt-qemu-sev-validate | 207 +++++++++++++++++++++-- 2 files changed, 304 insertions(+), 14 deletions(-) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index 0f6c64ba90..e2c4672a05 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -37,6 +37,12 @@ another virtual machine protected by AMD SEV that has al= ready had its launch measurement validated. Running this program on the virtualization host wil= l not produce an answer that can be trusted. =20 +If told to connect to libvirt, it will refuse to use a libvirt connection = that +is local to the machine, since that cannot be trusted. For the sake of tes= ting +or demonstration purposes, however, it can be forced to run in this scenar= io +using the ``--insecure`` flag. The result will, of course, still not be +trustworthy. + OPTIONS =3D=3D=3D=3D=3D=3D=3D =20 @@ -115,6 +121,43 @@ size, with the first 16 bytes containing the TEK and t= he last 16 bytes containing the TIK. This is mutually exclusive with the ``--tik`` and ``-= -tek`` arguments. =20 +Libvirt options +--------------- + +These options are used when connecting to libvirt to automatically obtain +state and configuration information about the domain to be attested. + +``-c``, ``--connect URI`` + +Libvirt connection URI. For the validation to be trustworthy this must be = a URI +resolving to a remote virtualization host. This requirement can be overrid= den +using the ``--insecure`` argument. + +``-o``, ``--domain ID|NAME|UUID`` + +Domain ID, or domain name or domain UUID. Used to identify which libvirt d= omain +is to have its launch measured. The domain must be running, and would usua= lly +have been started in a paused state, to allow validation to be performed b= efore +guest CPUs begin execution. + +``-i``, ``--insecure`` + +Proceed even if usage scenario is known to be insecure. This allows the pr= ogram +to connect to a local libvirt hypervisor and rely on file content from the +virtualization host. It also allows the validation to proceed even if the +virtual machine CPUs are not in the initial paused state. The result of the +validation must not be trusted. + +``-g``, ``--ignore-config`` + +Do not attempt to sanity check the domain config. The default behaviour is= to +print out errors if identifying configuration elements in the guest XML th= at +would invalidate the launch measurement. This can help the guest owner to +understand any configuration mistakes that have been made. If the +``--ignore-config`` argument is given, this sanity checking of configurati= on +will be skipped. The result is that the validation will likely be reported= as +failed. + EXAMPLES =3D=3D=3D=3D=3D=3D=3D=3D =20 @@ -139,6 +182,46 @@ Validate the measurement of a SEV guest booting from d= isk: --build-id 13 \ --policy 3 =20 +Fetch from remote libvirt +------------------------- + +This scenario allows fetching certain data from a remote hypervisor via a +connection to libvirt. It will aid in debugging by analysing the guest +configuration and reporting anything that could invalidate the measurement +of the guest. This usage model is considered secure, because the limited +information obtained from the untrusted hypervisor cannot be used to change +the result. + +Validate the measurement of a SEV guest booting from disk: + +:: + + # virt-qemu-sev-validate \ + --connect qemu+ssh://root@some.remote.host/system \ + --firmware OVMF.sev.fd \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + +Fetch from local libvirt +------------------------ + +This scenario allows fetching all data from the local hypervisor via a +connection to libvirt. It is only to be used for the purpose of testing, +debugging, or demonstrations, because running on the local hypervisor is n= ot +a secure scenario. To enable this usage, the ``--insecure`` flag must be +specified. Given a pointer to the libvirt guest to validate, all informati= on +needed to perform a validation, except the TIK/TEK pair can be acquired +automatically. + +Validate the measurement of a SEV guest booting from disk: + +:: + + # virt-qemu-sev-validate \ + --insecure \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 @@ -158,7 +241,33 @@ be set: The way in which this program has been invoked prevent it from being abl= e to validate the launch measurement. =20 -* **3** - *unexpected error occurred in the code* +* **3** - *Usage scenario is not secure* + + The way in which this program has been invoked means that the result of = any + launch measurement validation will not be secure. + + The program can be reinvoked with ``--insecure`` argument to force a + validation, however, the results of this should not be trusted. This sho= uld + only be used for testing, debugging or demonstration purposes, never in a + production deployment. + +* **4** - *Domain has incorrect configuration to be measured* + + The way in which the guest has been configured prevent this program from= being + able to validate the launch measurement. Note that in general the guest + configuration reported by the hypervisor is not trustworthy, so it is + possible this error could be a false positive designed to cause a denial= of + service. + + This program can be reinvoked with the ``--ignore-config`` argument to s= kip + the sanity checks on the domain XML. This will likely result in it faili= ng + with an exit code of **1** indicating the measurement is invalid + +* **5** - *Domain is in incorrect state to be measured* + + The domain has to be running in order to validate a launch measurement. + +* **6** - *unexpected error occurred in the code* =20 A logic flaw in this program means it is unable to complete the validati= on of the measurement. This is a bug which should be reported to the maintaine= rs. diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index 7ff54e7623..31c739c10f 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -39,9 +39,14 @@ from base64 import b64decode from hashlib import sha256 import hmac import logging +import re +import socket import sys import traceback =20 +from lxml import etree +import libvirt + log =3D logging.getLogger() =20 =20 @@ -53,6 +58,18 @@ class UnsupportedUsageException(Exception): pass =20 =20 +class InsecureUsageException(Exception): + pass + + +class IncorrectConfigException(Exception): + pass + + +class InvalidStateException(Exception): + pass + + class ConfidentialVM(object): =20 def __init__(self, @@ -159,6 +176,108 @@ class ConfidentialVM(object): "Measurement does not match, VM is not trustworthy") =20 =20 +class LibvirtConfidentialVM(ConfidentialVM): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.conn =3D None + self.dom =3D None + + def check_domain(self, doc, secure): + ls =3D doc.xpath("/domain/launchSecurity[@type=3D'sev']") + if len(ls) !=3D 1: + raise IncorrectConfigException( + "Domain is not configured with SEV launch security") + + dh =3D doc.xpath("/domain/launchSecurity[@type=3D'sev']/dhCert") + if len(dh) !=3D 1: + raise IncorrectConfigException( + "Domain must have SEV owner cert to validate measurement") + + session =3D doc.xpath("/domain/launchSecurity[@type=3D'sev']/sessi= on") + if len(session) !=3D 1: + raise IncorrectConfigException( + "Domain must have SEV session data to validate measurement= ") + + nvramnodes =3D doc.xpath("/domain/os/nvram") + if len(nvramnodes) !=3D 0 and secure: + raise InsecureUsageException( + "Domain firmware with NVRAM cannot be securely measured") + + loadernodes =3D doc.xpath("/domain/os/loader") + if len(loadernodes) !=3D 1: + raise IncorrectConfigException( + "Domain must have one firmware path") + + def load_domain(self, uri, id_name_uuid, secure, ignore_config): + self.conn =3D libvirt.open(uri) + + remote =3D socket.gethostname() !=3D self.conn.getHostname() + if not remote and secure: + raise InsecureUsageException( + "running locally on the hypervisor host is not secure") + + if re.match(r'^\d+$', id_name_uuid): + self.dom =3D self.conn.lookupByID(int(id_name_uuid)) + elif re.match(r'^[-a-f0-9]+$', id_name_uuid): + self.dom =3D self.conn.lookupByUUIDString(id_name_uuid) + else: + self.dom =3D self.conn.lookupByName(id_name_uuid) + + log.debug("VM: id=3D%d name=3D%s uuid=3D%s", + self.dom.ID(), self.dom.name(), self.dom.UUIDString()) + + if not self.dom.isActive(): + raise InvalidStateException( + "Domain must be running to validate measurement") + + state =3D self.dom.info()[0] + if state !=3D libvirt.VIR_DOMAIN_PAUSED and secure: + raise InvalidStateException( + "Domain must be paused to validate measurement") + + xml =3D self.dom.XMLDesc() + + doc =3D etree.fromstring(xml) + if not ignore_config: + self.check_domain(doc, secure) + + # See comments at top of file wrt why we are OK to trust the + # sev-api-major, sev-api-minor, sev-build-id and sev-policy data + # reported by the host + sevinfo =3D self.dom.launchSecurityInfo() + + if "sev-api-major" not in sevinfo: + raise UnsupportedUsageException( + "'api-major' not reported in domain launch security info") + + if self.measurement is None: + self.measurement =3D sevinfo["sev-measurement"] + if self.api_major is None: + self.api_major =3D sevinfo["sev-api-major"] + if self.api_minor is None: + self.api_minor =3D sevinfo["sev-api-minor"] + if self.build_id is None: + self.build_id =3D sevinfo["sev-build-id"] + if self.policy is None: + self.policy =3D sevinfo["sev-policy"] + + if self.firmware is None: + if remote: + raise UnsupportedUsageException( + "Cannot access firmware path remotely") + if secure: + raise InsecureUsageException( + "Using firmware path from XML is not secure") + + loadernodes =3D doc.xpath("/domain/os/loader") + if len(loadernodes) =3D=3D 0: + raise UnsupportedUsageException( + "--firmware not specified and no firmware path found") + + self.load_firmware(loadernodes[0].text) + + def parse_command_line(): parser =3D argparse.ArgumentParser( description=3D'Validate guest AMD SEV launch measurement') @@ -169,20 +288,20 @@ def parse_command_line(): =20 # Arguments related to the state of the launched guest vmstate =3D parser.add_argument_group("Virtual machine launch state") - vmstate.add_argument('--measurement', '-m', required=3DTrue, + vmstate.add_argument('--measurement', '-m', help=3D'Measurement for the running domain') - vmstate.add_argument('--api-major', type=3Dint, required=3DTrue, + vmstate.add_argument('--api-major', type=3Dint, help=3D'SEV API major version for the running dom= ain') - vmstate.add_argument('--api-minor', type=3Dint, required=3DTrue, + vmstate.add_argument('--api-minor', type=3Dint, help=3D'SEV API minor version for the running dom= ain') - vmstate.add_argument('--build-id', type=3Dint, required=3DTrue, + vmstate.add_argument('--build-id', type=3Dint, help=3D'SEV build ID for the running domain') - vmstate.add_argument('--policy', type=3Dint, required=3DTrue, + vmstate.add_argument('--policy', type=3Dint, help=3D'SEV policy for the running domain') =20 # Arguments related to calculation of the expected launch measurement vmconfig =3D parser.add_argument_group("Virtual machine config") - vmconfig.add_argument('--firmware', '-f', required=3DTrue, + vmconfig.add_argument('--firmware', '-f', help=3D'Path to the firmware binary') vmconfig.add_argument('--tik', help=3D'TIK file for domain') @@ -191,6 +310,17 @@ def parse_command_line(): vmconfig.add_argument('--tk', help=3D'TEK/TIK combined file for domain') =20 + # Arguments related to the connection to libvirt + vmconn =3D parser.add_argument_group("Libvirt guest connection") + vmconn.add_argument('--connect', '-c', default=3D"qemu:///system", + help=3D'libvirt connection URI') + vmconn.add_argument('--domain', '-o', + help=3D'domain ID / Name / UUID') + vmconn.add_argument('--insecure', '-i', action=3D'store_true', + help=3D'Proceed even if usage scenario is insecure= ') + vmconn.add_argument('--ignore-config', '-g', action=3D'store_true', + help=3D'Do not attempt to sanity check the guest c= onfig') + return parser.parse_args() =20 =20 @@ -206,21 +336,60 @@ def check_usage(args): raise UnsupportedUsageException( "Either --tk or both of --tek/--tik are required") =20 + if args.domain is None: + if args.measurement is None: + raise UnsupportedUsageException( + "Either --measurement or --domain is required") + + if args.api_major is None: + raise UnsupportedUsageException( + "Either --api-major or --domain is required") + + if args.api_minor is None: + raise UnsupportedUsageException( + "Either --api-minor or --domain is required") + + if args.build_id is None: + raise UnsupportedUsageException( + "Either --build-id or --domain is required") + + if args.policy is None: + raise UnsupportedUsageException( + "Either --policy or --domain is required") + + if args.firmware is None: + raise UnsupportedUsageException( + "Either --firmware or --domain is required") + =20 def attest(args): - cvm =3D ConfidentialVM(measurement=3Dargs.measurement, - api_major=3Dargs.api_major, - api_minor=3Dargs.api_minor, - build_id=3Dargs.build_id, - policy=3Dargs.policy) + if args.domain is None: + cvm =3D ConfidentialVM(measurement=3Dargs.measurement, + api_major=3Dargs.api_major, + api_minor=3Dargs.api_minor, + build_id=3Dargs.build_id, + policy=3Dargs.policy) + else: + cvm =3D LibvirtConfidentialVM(measurement=3Dargs.measurement, + api_major=3Dargs.api_major, + api_minor=3Dargs.api_minor, + build_id=3Dargs.build_id, + policy=3Dargs.policy) =20 - cvm.load_firmware(args.firmware) + if args.firmware is not None: + cvm.load_firmware(args.firmware) =20 if args.tk is not None: cvm.load_tk(args.tk) else: cvm.load_tik_tek(args.tik, args.tek) =20 + if args.domain is not None: + cvm.load_domain(args.connect, + args.domain, + not args.insecure, + args.ignore_config) + cvm.attest() =20 if not args.quiet: @@ -252,12 +421,24 @@ def main(): if not args.quiet: print("ERROR: %s" % e, file=3Dsys.stderr) sys.exit(2) + except InsecureUsageException as e: + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(3) + except IncorrectConfigException as e: + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(4) + except InvalidStateException as e: + if not args.quiet: + print("ERROR: %s" % e, file=3Dsys.stderr) + sys.exit(5) except Exception as e: if args.debug: traceback.print_tb(e.__traceback__) if not args.quiet: print("ERROR: %s" % e, file=3Dsys.stderr) - sys.exit(3) + sys.exit(6) =20 if __name__ =3D=3D "__main__": main() --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832136; cv=none; d=zohomail.com; s=zohoarc; b=RQzZuXPfim5mn2f26nk9Lgx0stLHVnlhvvJxSuWS3Z7j48Oa9jllscBPxV2QdsBynrhBYOcdQD4qRgMZV5m5I13pEZSw6AlZBGPKsVJpCM1WKQBOK+kqFrwAJBEOuJYkjXp3aMMOjbwoh84ngm/+7msvAnkczxY+OGrw7V7Jm0c= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832136; h=Content-Type:Content-Transfer-Encoding:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=yaXWC87cUbxAUfeJM1gdBir8NPrqsSKorK3DuFVbYVM=; b=KREovTab9Cm6QZE767s4uY/T9/G5zv7ITLpENBFdsGjNw/9Py4dsiVNv+UDmJen0LsnErCyEGO0AAz2XdY6Wt5WKr8kPp31bJ1hg2jLDi4JZTNzb3IIraxdQVhv5NGHjUe39B/Hzy8Svi4zxvYza0KybiAfQ1FzzLO/C8v+L5L0= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832136092333.61346451590873; Mon, 7 Nov 2022 06:42:16 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-142-RFOIIslfMUGbpdGzRHxAmw-1; Mon, 07 Nov 2022 09:42:06 -0500 Received: from smtp.corp.redhat.com (int-mx08.intmail.prod.int.rdu2.redhat.com [10.11.54.8]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 4D1C8101245E; Mon, 7 Nov 2022 14:41:52 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 39D2BC1908A; Mon, 7 Nov 2022 14:41:52 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 2E9531946A74; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 357AD1946587 for ; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 28F0740C2089; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 9315340C2064; Mon, 7 Nov 2022 14:41:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832135; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=yaXWC87cUbxAUfeJM1gdBir8NPrqsSKorK3DuFVbYVM=; b=XLLQmYo8OxpgEm2lJZmu9oYDXCbU+0CBZbVvfqQyMtX4F4s2xCljoUCOZkjUCy+dsyjdJn mJ9+ezNuv1MPPYmMV0qIC8rwL7moWmhn2t1LMAld4DOhiDlEkUXH7l1hOr39W9TceyNP0z XuPWN6ys3FHMmX4zSSy/0vsUfQAyO3U= X-MC-Unique: RFOIIslfMUGbpdGzRHxAmw-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 04/12] tools: support validating SEV direct kernel boot measurements Date: Mon, 7 Nov 2022 14:41:19 +0000 Message-Id: <20221107144127.973324-5-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.8 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832136689100001 When doing direct kernel boot we need to include the kernel, initrd and cmdline in the measurement. Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 43 +++++++++ tools/virt-qemu-sev-validate | 113 ++++++++++++++++++++++- 2 files changed, 155 insertions(+), 1 deletion(-) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index e2c4672a05..e8a868f5a8 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -102,6 +102,20 @@ initialize AMD SEV. For the validation to be trustwort= hy it important that the firmware build used has no support for loading non-volatile variables from NVRAM, even if NVRAM is expose to the guest. =20 +``-k PATH``, ``--kernel=3DPATH`` + +Path to the kernel binary if doing direct kernel boot. + +``-r PATH``, ``--initrd=3DPATH`` + +Path to the initrd binary if doing direct kernel boot. Defaults to zero le= ngth +content if omitted. + +``-e STRING``, ``--cmdline=3DSTRING`` + +String containing any kernel command line parameters used during boot of t= he +domain. Defaults to the empty string if omitted. + ``--tik PATH`` =20 TIK file for domain. This file must be exactly 16 bytes in size and contai= ns the @@ -182,6 +196,22 @@ Validate the measurement of a SEV guest booting from d= isk: --build-id 13 \ --policy 3 =20 +Validate the measurement of a SEV guest with direct kernel boot: + +:: + + # virt-dom-sev-validate \ + --firmware OVMF.sev.fd \ + --kernel vmlinuz-5.11.12 \ + --initrd initramfs-5.11.12 \ + --cmdline "root=3D/dev/vda1" \ + --tk this-guest-tk.bin \ + --measurement Zs2pf19ubFSafpZ2WKkwquXvACx9Wt/BV+eJwQ/taO8jhyIj/F8sw= FrybR1fZ2ID \ + --api-major 0 \ + --api-minor 24 \ + --build-id 13 \ + --policy 3 + Fetch from remote libvirt ------------------------- =20 @@ -202,6 +232,19 @@ Validate the measurement of a SEV guest booting from d= isk: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV guest with direct kernel boot: + +:: + + # virt-dom-sev-validate \ + --connect qemu+ssh://root@some.remote.host/system \ + --firmware OVMF.sev.fd \ + --kernel vmlinuz-5.11.12 \ + --initrd initramfs-5.11.12 \ + --cmdline "root=3D/dev/vda1" \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + Fetch from local libvirt ------------------------ =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index 31c739c10f..b978c3eb3d 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -34,6 +34,7 @@ # firmware versions with known flaws. # =20 +import abc import argparse from base64 import b64decode from hashlib import sha256 @@ -43,6 +44,7 @@ import re import socket import sys import traceback +from uuid import UUID =20 from lxml import etree import libvirt @@ -70,6 +72,91 @@ class InvalidStateException(Exception): pass =20 =20 +class GUIDTable(abc.ABC): + GUID_LEN =3D 16 + + def __init__(self, guid, lenlen=3D2): + self.guid =3D guid + self.lenlen =3D lenlen + + @abc.abstractmethod + def entries(self): + pass + + def build_entry(self, guid, payload, lenlen): + dummylen =3D int(0).to_bytes(lenlen, 'little') + entry =3D bytearray(guid + dummylen + payload) + + lenle =3D len(entry).to_bytes(lenlen, 'little') + entry[self.GUID_LEN:(self.GUID_LEN + lenlen)] =3D lenle + + return bytes(entry) + + def build(self): + payload =3D self.entries() + + if len(payload) =3D=3D 0: + return bytes([]) + + dummylen =3D int(0).to_bytes(self.lenlen, 'little') + table =3D bytearray(self.guid + dummylen + payload) + + guidlen =3D len(table).to_bytes(self.lenlen, 'little') + table[self.GUID_LEN:(self.GUID_LEN + self.lenlen)] =3D guidlen + + pad =3D 16 - (len(table) % 16) + table +=3D bytes([0]) * pad + + log.debug("Table(hex): %s", bytes(table).hex()) + return bytes(table) + + +class KernelTable(GUIDTable): + + TABLE_GUID =3D UUID('{9438d606-4f22-4cc9-b479-a793-d411fd21}').bytes_le + KERNEL_GUID =3D UUID('{4de79437-abd2-427f-b835-d5b1-72d2045b}').bytes_= le + INITRD_GUID =3D UUID('{44baf731-3a2f-4bd7-9af1-41e2-9169781d}').bytes_= le + CMDLINE_GUID =3D UUID('{97d02dd8-bd20-4c94-aa78-e771-4d36ab2a}').bytes= _le + + def __init__(self): + super().__init__(guid=3Dself.TABLE_GUID, + lenlen=3D2) + + self.kernel =3D None + self.initrd =3D None + self.cmdline =3D None + + def load_kernel(self, path): + with open(path, "rb") as fh: + self.kernel =3D sha256(fh.read()).digest() + + def load_initrd(self, path): + with open(path, "rb") as fh: + self.initrd =3D sha256(fh.read()).digest() + + def load_cmdline(self, val): + self.cmdline =3D sha256(val.encode("utf8") + bytes([0])).digest() + + def entries(self): + entries =3D bytes([]) + if self.kernel is None: + return entries + + if self.initrd is None: + self.initrd =3D sha256(bytes([])).digest() + if self.cmdline is None: + self.cmdline =3D sha256(bytes([0])).digest() + + log.debug("Kernel(sha256): %s", self.kernel.hex()) + log.debug("Initrd(sha256): %s", self.initrd.hex()) + log.debug("Cmdline(sha256): %s", self.cmdline.hex()) + entries +=3D self.build_entry(self.CMDLINE_GUID, self.cmdline, 2) + entries +=3D self.build_entry(self.INITRD_GUID, self.initrd, 2) + entries +=3D self.build_entry(self.KERNEL_GUID, self.kernel, 2) + + return entries + + class ConfidentialVM(object): =20 def __init__(self, @@ -88,6 +175,8 @@ class ConfidentialVM(object): self.tik =3D None self.tek =3D None =20 + self.kernel_table =3D KernelTable() + def load_tik_tek(self, tik_path, tek_path): with open(tik_path, 'rb') as fh: self.tik =3D fh.read() @@ -129,8 +218,10 @@ class ConfidentialVM(object): # of the following: # # - The firmware blob + # - The kernel GUID table def get_measured_data(self): - measured_data =3D self.firmware + measured_data =3D (self.firmware + + self.kernel_table.build()) log.debug("Measured-data(sha256): %s", sha256(measured_data).hexdigest()) return measured_data @@ -303,6 +394,12 @@ def parse_command_line(): vmconfig =3D parser.add_argument_group("Virtual machine config") vmconfig.add_argument('--firmware', '-f', help=3D'Path to the firmware binary') + vmconfig.add_argument('--kernel', '-k', + help=3D'Path to the kernel binary') + vmconfig.add_argument('--initrd', '-r', + help=3D'Path to the initrd binary') + vmconfig.add_argument('--cmdline', '-e', + help=3D'Cmdline string booted with') vmconfig.add_argument('--tik', help=3D'TIK file for domain') vmconfig.add_argument('--tek', @@ -361,6 +458,11 @@ def check_usage(args): raise UnsupportedUsageException( "Either --firmware or --domain is required") =20 + if args.kernel is None: + if args.initrd is not None or args.cmdline is not None: + raise UnsupportedUsageException( + "--initrd/--cmdline require --kernel") + =20 def attest(args): if args.domain is None: @@ -384,6 +486,15 @@ def attest(args): else: cvm.load_tik_tek(args.tik, args.tek) =20 + if args.kernel is not None: + cvm.kernel_table.load_kernel(args.kernel) + + if args.initrd is not None: + cvm.kernel_table.load_initrd(args.initrd) + + if args.cmdline is not None: + cvm.kernel_table.load_cmdline(args.cmdline) + if args.domain is not None: cvm.load_domain(args.connect, args.domain, --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832159; cv=none; d=zohomail.com; s=zohoarc; b=doJu5xZcX9g7m7eXlrx8cTLduOSCtiH3NzpIIssJevKasiOAGLbFwPt7MUT8g6ItP/Dsg1KCAX1lCq4l5Yefz+abT+epJvWbvkdmc8irTBUFPWwLCLUiLnE70CytYoGuVHXNz0iYLUZoFiDGkKMvaYJhGa9gCbECrellb28oxfM= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832159; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=F7Ew1RFW+7jMVOsVpCmaDID53eZfNSOlFmmFxVlVStQ=; b=FB9UhEU/rti2EysMoQMiWoKTJebE0n2WecGr/Warv+fw1tmh9ftFhH+HkOmdFb7cMObMolSUpXpyNyzGLiHi5hHy3I7ky9KoghY/fAyga8B2xoJM0op5H9+vpWzkzSWlL1I/oKvSYd/CbgeHmN+rIFM1LsIeGJ/rr9mi25tOn7w= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832159615916.0487103927888; Mon, 7 Nov 2022 06:42:39 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-214-TfVRnD9YMP-gOFYbFmDnGw-1; Mon, 07 Nov 2022 09:42:31 -0500 Received: from smtp.corp.redhat.com (int-mx02.intmail.prod.int.rdu2.redhat.com [10.11.54.2]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 14E2A806015; Mon, 7 Nov 2022 14:41:43 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 02D4140C6EC2; Mon, 7 Nov 2022 14:41:43 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id DF8CD1946A66; Mon, 7 Nov 2022 14:41:35 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 1F2E41946A4D for ; Mon, 7 Nov 2022 14:41:34 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 0FD7340C2089; Mon, 7 Nov 2022 14:41:34 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 6840140C2064; Mon, 7 Nov 2022 14:41:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832157; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=F7Ew1RFW+7jMVOsVpCmaDID53eZfNSOlFmmFxVlVStQ=; b=jScDX9NmrFSPcq4QsMSgzFMbWoFAx6DX4BO8o/3DYRswcks42kozZTv6xtnLOPyqki1n8i DgDblQCesw1LEsH7sxRuZnItrTfiImltGv4kQ339eJ1MVyeTjemo3+udWyBYKEGqo42H2e n4EcwiXqSrsWpiz3hLjdUe1BTCZIX2E= X-MC-Unique: TfVRnD9YMP-gOFYbFmDnGw-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 05/12] tools: load direct kernel config from libvirt Date: Mon, 7 Nov 2022 14:41:20 +0000 Message-Id: <20221107144127.973324-6-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.2 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832160887100001 When connected to libvirt we can validate that the guest configuration has the kernel hashes property enabled, otherwise including the kernel GUID table in our expected measurements is not likely to match the actual measurement. When running locally we can also automatically detect the kernel/initrd paths, along with the cmdline string from the XML. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 9 ++++ tools/virt-qemu-sev-validate | 59 ++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index e8a868f5a8..e374fecec0 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -265,6 +265,15 @@ Validate the measurement of a SEV guest booting from d= isk: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV guest with direct kernel boot: + +:: + + # virt-dom-sev-validate \ + --insecure \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index b978c3eb3d..301660ba8e 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -300,6 +300,35 @@ class LibvirtConfidentialVM(ConfidentialVM): raise IncorrectConfigException( "Domain must have one firmware path") =20 + measure_kernel_nodes =3D doc.xpath( + "/domain/launchSecurity[@type=3D'sev']/@kernelHashes") + measure_kernel =3D False + if len(measure_kernel_nodes) =3D=3D 1: + if measure_kernel_nodes[0] =3D=3D "yes": + measure_kernel =3D True + + xp_kernel =3D "/domain/os/kernel" + xp_initrd =3D "/domain/os/initrd" + xp_cmdline =3D "/domain/os/cmdline" + kern_nodes =3D (doc.xpath(xp_kernel) + + doc.xpath(xp_initrd) + + doc.xpath(xp_cmdline)) + if not measure_kernel: + if len(self.kernel_table.entries()) !=3D 0: + raise UnsupportedUsageException( + "kernel/initrd/cmdline provided but kernel " + "measurement not enabled") + + # Check for an insecure scenario + if len(kern_nodes) !=3D 0 and secure: + raise InsecureUsageException( + "direct kernel boot present without measurement") + else: + if len(kern_nodes) =3D=3D 0: + raise IncorrectConfigException( + "kernel/initrd/cmdline not provided but kernel " + "measurement is enabled") + def load_domain(self, uri, id_name_uuid, secure, ignore_config): self.conn =3D libvirt.open(uri) =20 @@ -368,6 +397,36 @@ class LibvirtConfidentialVM(ConfidentialVM): =20 self.load_firmware(loadernodes[0].text) =20 + if self.kernel_table.kernel is None: + kernelnodes =3D doc.xpath("/domain/os/kernel") + if len(kernelnodes) !=3D 0: + if remote: + raise UnsupportedUsageException( + "Cannot access kernel path remotely") + if secure: + raise InsecureUsageException( + "Using kernel path from XML is not secure") + self.kernel_table.load_kernel(kernelnodes[0].text) + + if self.kernel_table.initrd is None: + initrdnodes =3D doc.xpath("/domain/os/initrd") + if len(initrdnodes) !=3D 0: + if remote: + raise UnsupportedUsageException( + "Cannot access initrd path remotely") + if secure: + raise InsecureUsageException( + "Using initrd path from XML is not secure") + self.kernel_table.load_initrd(initrdnodes[0].text) + + if self.kernel_table.cmdline is None: + cmdlinenodes =3D doc.xpath("/domain/os/cmdline") + if len(cmdlinenodes) !=3D 0: + if secure: + raise InsecureUsageException( + "Using cmdline string from XML is not secure") + self.kernel_table.load_cmdline(cmdlinenodes[0].text) + =20 def parse_command_line(): parser =3D argparse.ArgumentParser( --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832115; cv=none; d=zohomail.com; s=zohoarc; b=edjTqU21gZjsaFlW+G9RLaUBcgAyp1wlSuz8PjqwcVMH0rqW2DlRN4e/duVEmKn5uLwdn3G7Y7Ndj7QRSsQ7yUn2Z/lmbMAdd1VjQq9ln+vy0h7678sljY8vbSL0TxjLgNcUSjCi5NwwUMf0akgZ/5r0TJfs2i0QZooczb9zLwY= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832115; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=RwaFAjVu0S0++3BT4Nm3HVptRQKYt3C4LYvqXgVhTk0=; b=kTbk83KWNqn7SBfmFWsOBxSQAAD6wLF5dBlRt7ZEWBTs4ez2yoMR/6xAgrnJj4WGR5QaYHeLB+Ch0JcJPOIFlKE/Ztqt/Mrm2TftS5tFQullphgn+97pjJcDBFLn776OAq8a55zRl+tlM5AlEZRt0gjaVFP7fZqQawI/NYxfwSY= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 166783211500149.21156508372428; Mon, 7 Nov 2022 06:41:55 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-10-wnXLTWxVOPGvtM9x7LeZKg-1; Mon, 07 Nov 2022 09:41:52 -0500 Received: from smtp.corp.redhat.com (int-mx05.intmail.prod.int.rdu2.redhat.com [10.11.54.5]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 6D14B101E9B1; Mon, 7 Nov 2022 14:41:48 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 5466F4EA48; Mon, 7 Nov 2022 14:41:48 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 903471947041; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 1E5FA1946A63 for ; Mon, 7 Nov 2022 14:41:35 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id EA52140C83AA; Mon, 7 Nov 2022 14:41:34 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 48DF840C2064; Mon, 7 Nov 2022 14:41:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832114; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=RwaFAjVu0S0++3BT4Nm3HVptRQKYt3C4LYvqXgVhTk0=; b=VDk/x13gNSZ1bJVnViLMYpjPwZXtEbB2ZD7gvwTACB8U8IQsUsYZseTd0t6iCI3gxF9v2Y Rw+DKDiCstTeoA4o+TQzhy/ueAO9pLALiPZQSdYHfgVAZmdXhCshdVr+LNte4MJBs64411 BDNKrW0+Is/ttwpvWz9sRSUO/vHDqak= X-MC-Unique: wnXLTWxVOPGvtM9x7LeZKg-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 06/12] tools: support validating SEV-ES initial vCPU state measurements Date: Mon, 7 Nov 2022 14:41:21 +0000 Message-Id: <20221107144127.973324-7-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.5 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832116527100001 With the SEV-ES policy the VMSA state of each vCPU must be included in the measured data. The VMSA state can be generated using the 'sevctl' tool, by telling it a QEMU VMSA is required, and passing the hypevisor's CPU SKU (family, model, stepping). Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 58 ++++++++++++++++++++ tools/virt-qemu-sev-validate | 69 ++++++++++++++++++++++-- 2 files changed, 124 insertions(+), 3 deletions(-) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index e374fecec0..d51969d0b2 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -116,6 +116,23 @@ content if omitted. String containing any kernel command line parameters used during boot of t= he domain. Defaults to the empty string if omitted. =20 +``-n COUNT``, ``--num-cpus=3DCOUNT`` + +The number of virtual CPUs for the domain. This is required when the +domain policy is set to require SEV-ES. + +``-0 PATH``, ``--vmsa-cpu0=3DPATH`` + +Path to the VMSA initial state for the boot CPU. This is required when +the domain policy is set to require SEV-ES. The file contents must be +exactly 4096 bytes in length. + +``-1 PATH``, ``--vmsa-cpu1=3DPATH`` + +Path to the VMSA initial state for the non-boot CPU. This is required when +the domain policy is set to require SEV-ES and the domain has more than one +CPU present. The file contents must be exactly 4096 bytes in length. + ``--tik PATH`` =20 TIK file for domain. This file must be exactly 16 bytes in size and contai= ns the @@ -212,6 +229,22 @@ Validate the measurement of a SEV guest with direct ke= rnel boot: --build-id 13 \ --policy 3 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk: + +:: + + # virt-dom-sev-validate \ + --firmware OVMF.sev.fd \ + --num-cpus 2 \ + --vmsa-cpu0 vmsa0.bin \ + --vmsa-cpu1 vmsa1.bin \ + --tk this-guest-tk.bin \ + --measurement Zs2pf19ubFSafpZ2WKkwquXvACx9Wt/BV+eJwQ/taO8jhyIj/F8sw= FrybR1fZ2ID \ + --api-major 0 \ + --api-minor 24 \ + --build-id 13 \ + --policy 7 + Fetch from remote libvirt ------------------------- =20 @@ -245,6 +278,19 @@ Validate the measurement of a SEV guest with direct ke= rnel boot: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk: + +:: + + # virt-dom-sev-validate \ + --connect qemu+ssh://root@some.remote.host/system \ + --firmware OVMF.sev.fd \ + --num-cpus 2 \ + --vmsa-cpu0 vmsa0.bin \ + --vmsa-cpu1 vmsa1.bin \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + Fetch from local libvirt ------------------------ =20 @@ -274,6 +320,18 @@ Validate the measurement of a SEV guest with direct ke= rnel boot: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk: + +:: + + # virt-dom-sev-validate \ + --insecure \ + --num-cpus 2 \ + --vmsa-cpu0 vmsa0.bin \ + --vmsa-cpu1 vmsa1.bin \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index 301660ba8e..6003ba2929 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -158,13 +158,16 @@ class KernelTable(GUIDTable): =20 =20 class ConfidentialVM(object): + POLICY_BIT_SEV_ES =3D 2 + POLICY_VAL_SEV_ES =3D (1 << POLICY_BIT_SEV_ES) =20 def __init__(self, measurement=3DNone, api_major=3DNone, api_minor=3DNone, build_id=3DNone, - policy=3DNone): + policy=3DNone, + num_cpus=3DNone): self.measurement =3D measurement self.api_major =3D api_major self.api_minor =3D api_minor @@ -175,8 +178,15 @@ class ConfidentialVM(object): self.tik =3D None self.tek =3D None =20 + self.num_cpus =3D num_cpus + self.vmsa_cpu0 =3D None + self.vmsa_cpu1 =3D None + self.kernel_table =3D KernelTable() =20 + def is_sev_es(self): + return self.policy & self.POLICY_VAL_SEV_ES + def load_tik_tek(self, tik_path, tek_path): with open(tik_path, 'rb') as fh: self.tik =3D fh.read() @@ -212,6 +222,43 @@ class ConfidentialVM(object): self.firmware =3D fh.read() log.debug("Firmware(sha256): %s", sha256(self.firmware).hexdigest(= )) =20 + @staticmethod + def _load_vmsa(path): + with open(path, 'rb') as fh: + vmsa =3D fh.read() + + if len(vmsa) !=3D 4096: + raise UnsupportedUsageException( + "VMSA must be 4096 bytes in length") + return vmsa + + def load_vmsa_cpu0(self, path): + self.vmsa_cpu0 =3D self._load_vmsa(path) + log.debug("VMSA CPU 0(sha256): %s", + sha256(self.vmsa_cpu0).hexdigest()) + + def load_vmsa_cpu1(self, path): + self.vmsa_cpu1 =3D self._load_vmsa(path) + log.debug("VMSA CPU 1(sha256): %s", + sha256(self.vmsa_cpu1).hexdigest()) + + def get_cpu_state(self): + if self.num_cpus is None: + raise UnsupportedUsageException( + "Number of virtual CPUs must be specified for SEV-ES domai= n") + + if self.vmsa_cpu0 is None: + raise UnsupportedUsageException( + "VMSA for boot CPU required for SEV-ES domain") + + if self.num_cpus > 1 and self.vmsa_cpu1 is None: + raise UnsupportedUsageException( + "VMSA for additional CPUs required for SEV-ES domain with = SMP") + + vmsa =3D self.vmsa_cpu0 + (self.vmsa_cpu1 * (self.num_cpus - 1)) + log.debug("VMSA(sha256): %s", sha256(vmsa).hexdigest()) + return vmsa + # Get the full set of measured launch data for the domain # # The measured data that the guest is initialized with is the concaten= ation @@ -222,6 +269,8 @@ class ConfidentialVM(object): def get_measured_data(self): measured_data =3D (self.firmware + self.kernel_table.build()) + if self.is_sev_es(): + measured_data +=3D self.get_cpu_state() log.debug("Measured-data(sha256): %s", sha256(measured_data).hexdigest()) return measured_data @@ -459,6 +508,12 @@ def parse_command_line(): help=3D'Path to the initrd binary') vmconfig.add_argument('--cmdline', '-e', help=3D'Cmdline string booted with') + vmconfig.add_argument('--num-cpus', '-n', type=3Dint, + help=3D'Number of virtual CPUs') + vmconfig.add_argument('--vmsa-cpu0', '-0', + help=3D'VMSA state for the boot CPU') + vmconfig.add_argument('--vmsa-cpu1', '-1', + help=3D'VMSA state for the additional CPUs') vmconfig.add_argument('--tik', help=3D'TIK file for domain') vmconfig.add_argument('--tek', @@ -529,13 +584,15 @@ def attest(args): api_major=3Dargs.api_major, api_minor=3Dargs.api_minor, build_id=3Dargs.build_id, - policy=3Dargs.policy) + policy=3Dargs.policy, + num_cpus=3Dargs.num_cpus) else: cvm =3D LibvirtConfidentialVM(measurement=3Dargs.measurement, api_major=3Dargs.api_major, api_minor=3Dargs.api_minor, build_id=3Dargs.build_id, - policy=3Dargs.policy) + policy=3Dargs.policy, + num_cpus=3Dargs.num_cpus) =20 if args.firmware is not None: cvm.load_firmware(args.firmware) @@ -554,6 +611,12 @@ def attest(args): if args.cmdline is not None: cvm.kernel_table.load_cmdline(args.cmdline) =20 + if args.vmsa_cpu0 is not None: + cvm.load_vmsa_cpu0(args.vmsa_cpu0) + + if args.vmsa_cpu1 is not None: + cvm.load_vmsa_cpu1(args.vmsa_cpu1) + if args.domain is not None: cvm.load_domain(args.connect, args.domain, --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) client-ip=170.10.129.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832127; cv=none; d=zohomail.com; s=zohoarc; b=EbIdv5XU8Ao+rvCfpmqvGcdl1c7M6/IOWb1GrD/m6Ywpvf5zZjAa2I24q1et/LDwC4ohk0ZWO3KHKzrAMcs8fPADolwzITAYxyMLlG49y/Kzb1SfG0aXZpcMjHoOjvCSQ+GZuQ0zT4MkYZJwp4BlQ2abesBCXPZRn47u5gq7gnw= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832127; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=Vb7q81qIGioNIqG10mFQ/KeyzU5yzWc1oGgLL0t85rc=; b=I5xpMpr8fkzjGGg9Ah1d4CbAf8rE24+0IXEVw2RVGE+293mGwXm14HRkFZVXJ5rIZ4IbufK1JGW1GmKNcbMialnchdNrfExET+4alzWkQTp+9G8H1LjM0E/zjBzYtABLx1YzRlVCaOWCQbLhZUvyIQJ0ICLA4jWQvSLv7epcFjg= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by mx.zohomail.com with SMTPS id 1667832127282200.91030733053663; Mon, 7 Nov 2022 06:42:07 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-630-Av-9npOvMSOwgaQkeUBYpg-1; Mon, 07 Nov 2022 09:41:53 -0500 Received: from smtp.corp.redhat.com (int-mx04.intmail.prod.int.rdu2.redhat.com [10.11.54.4]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id ACA22185A7AB; Mon, 7 Nov 2022 14:41:50 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 9A573200B42E; Mon, 7 Nov 2022 14:41:50 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id DA6EE194704B; Mon, 7 Nov 2022 14:41:37 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 43DDF1946A78 for ; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 2973940C2088; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 3FFE340C2064; Mon, 7 Nov 2022 14:41:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832125; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=Vb7q81qIGioNIqG10mFQ/KeyzU5yzWc1oGgLL0t85rc=; b=gw0xynEmsMgjaXR7J/tPjyXxoG3AyC680ZgBSZuiGmF7+s+h1tZ54jjte1O6Hs2MVdN8Ih 10zEHk/bmcLuoSx3K+Ijhs9crTyGJD4cKKCTJdT8OhYtWGt5dJu/2b03MFvT3SjLItqBVI DpEqvlDSeqBcDsVGdkzgEXep8jtVOVo= X-MC-Unique: Av-9npOvMSOwgaQkeUBYpg-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 07/12] tools: support automatically constructing SEV-ES vCPU state Date: Mon, 7 Nov 2022 14:41:22 +0000 Message-Id: <20221107144127.973324-8-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.4 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832128707100002 The VMSA files contain the expected CPU register state for the VM. Their content varies based on a few pieces of the stack - AMD CPU architectural initial state - KVM hypervisor VM CPU initialization - QEMU userspace VM CPU initialization - AMD CPU SKU (family/model/stepping) The first three pieces of information we can obtain through code inspection. The last piece of information we can take on the command line. This allows a user to validate a SEV-ES guest merely by providing the CPU SKU information, using --cpu-family, --cpu-model, --cpu-stepping. This avoids the need to obtain or construct VMSA files directly. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 45 +++ tools/virt-qemu-sev-validate | 467 +++++++++++++++++++++++ 2 files changed, 512 insertions(+) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index d51969d0b2..34ef328fe8 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -245,6 +245,24 @@ Validate the measurement of a SEV-ES SMP guest booting= from disk: --build-id 13 \ --policy 7 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk, with +automatically constructed VMSA: + +:: + + # virt-dom-sev-validate \ + --firmware OVMF.sev.fd \ + --num-cpus 2 \ + --cpu-family 23 \ + --cpu-model 49 \ + --cpu-stepping 0 \ + --tk this-guest-tk.bin \ + --measurement Zs2pf19ubFSafpZ2WKkwquXvACx9Wt/BV+eJwQ/taO8jhyIj/F8sw= FrybR1fZ2ID \ + --api-major 0 \ + --api-minor 24 \ + --build-id 13 \ + --policy 7 + Fetch from remote libvirt ------------------------- =20 @@ -291,6 +309,20 @@ Validate the measurement of a SEV-ES SMP guest booting= from disk: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk, with +automatically constructed VMSA: + +:: + + # virt-dom-sev-validate \ + --connect qemu+ssh://root@some.remote.host/system \ + --firmware OVMF.sev.fd \ + --cpu-family 23 \ + --cpu-model 49 \ + --cpu-stepping 0 \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + Fetch from local libvirt ------------------------ =20 @@ -332,6 +364,19 @@ Validate the measurement of a SEV-ES SMP guest booting= from disk: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV-ES SMP guest booting from disk, with +automatically constructed VMSA: + +:: + + # virt-dom-sev-validate \ + --insecure \ + --cpu-family 23 \ + --cpu-model 49 \ + --cpu-stepping 0 \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index 6003ba2929..ef8fa6fa27 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -42,6 +42,7 @@ import hmac import logging import re import socket +from struct import pack import sys import traceback from uuid import UUID @@ -72,6 +73,427 @@ class InvalidStateException(Exception): pass =20 =20 +class Field(object): + U8 =3D 0 + U16 =3D 2 + U32 =3D 4 + U64 =3D 8 + + SCALAR =3D 0 + BITMASK =3D 1 + ARRAY =3D 2 + + def __init__(self, name, size, fmt, value, order): + self.name =3D name + self.size =3D size + self.value =3D value + self.fmt =3D fmt + self.order =3D order + + +class Struct(object): + def __init__(self, size): + self._fields =3D {} + self.size =3D size + + def register_field(self, name, size, fmt=3DField.SCALAR, defvalue=3D0): + self._fields[name] =3D Field(name, size, fmt, + defvalue, len(self.fields)) + + @property + def fields(self): + return sorted(self._fields.values(), key=3Dlambda f: f.order) + + def __getattr__(self, name): + return self._fields[name] + + def __setattr__(self, name, value): + if name in ["_fields", "size"]: + super().__setattr__(name, value) + else: + self._fields[name].value =3D value + + def binary_format(self): + fmt =3D ["<"] + datalen =3D 0 + for field in self.fields: + if field.size =3D=3D Field.U8: + if field.fmt =3D=3D Field.ARRAY: + datalen +=3D len(field.value) + fmt +=3D ["%dB" % len(field.value)] + else: + datalen +=3D 1 + fmt +=3D ["B"] + elif field.size =3D=3D Field.U16: + datalen +=3D 2 + fmt +=3D ["H"] + elif field.size =3D=3D Field.U32: + datalen +=3D 4 + fmt +=3D ["L"] + elif field.size =3D=3D Field.U64: + datalen +=3D 8 + fmt +=3D ["Q"] + + pad =3D self.size - datalen + assert self.size >=3D 1 + fmt +=3D ["%dB" % pad] + + return "".join(fmt), pad + + def pack(self): + fmt, pad =3D self.binary_format() + + values =3D [] + for field in self.fields: + if field.size =3D=3D Field.U8 and field.fmt =3D=3D Field.ARRAY: + for _, k in enumerate(field.value): + values.append(k) + else: + values.append(field.value) + values.extend([0] * pad) + + return pack(fmt, *values) + + +class VMSA(Struct): + ATTR_G_SHIFT =3D 23 + ATTR_G_MASK =3D (1 << ATTR_G_SHIFT) + ATTR_B_SHIFT =3D 22 + ATTR_B_MASK =3D (1 << ATTR_B_SHIFT) + ATTR_L_SHIFT =3D 21 + ATTR_L_MASK =3D (1 << ATTR_L_SHIFT) + ATTR_AVL_SHIFT =3D 20 + ATTR_AVL_MASK =3D (1 << ATTR_AVL_SHIFT) + ATTR_P_SHIFT =3D 15 + ATTR_P_MASK =3D (1 << ATTR_P_SHIFT) + ATTR_DPL_SHIFT =3D 13 + ATTR_DPL_MASK =3D (3 << ATTR_DPL_SHIFT) + ATTR_S_SHIFT =3D 12 + ATTR_S_MASK =3D (1 << ATTR_S_SHIFT) + ATTR_TYPE_SHIFT =3D 8 + ATTR_TYPE_MASK =3D (15 << ATTR_TYPE_SHIFT) + ATTR_A_MASK =3D (1 << 8) + + ATTR_CS_MASK =3D (1 << 11) + ATTR_C_MASK =3D (1 << 10) + ATTR_R_MASK =3D (1 << 9) + + ATTR_E_MASK =3D (1 << 10) + ATTR_W_MASK =3D (1 << 9) + + def __init__(self): + super().__init__(4096) + + # From Linux arch/x86/include/asm/svm.h, we're unpacking the + # struct vmcb_save_area + + self.register_field("es_selector", Field.U16) + self.register_field("es_attrib", Field.U16, Field.BITMASK) + self.register_field("es_limit", Field.U32) + self.register_field("es_base", Field.U64) + + self.register_field("cs_selector", Field.U16) + self.register_field("cs_attrib", Field.U16, Field.BITMASK) + self.register_field("cs_limit", Field.U32) + self.register_field("cs_base", Field.U64) + + self.register_field("ss_selector", Field.U16) + self.register_field("ss_attrib", Field.U16, Field.BITMASK) + self.register_field("ss_limit", Field.U32) + self.register_field("ss_base", Field.U64) + + self.register_field("ds_selector", Field.U16) + self.register_field("ds_attrib", Field.U16, Field.BITMASK) + self.register_field("ds_limit", Field.U32) + self.register_field("ds_base", Field.U64) + + self.register_field("fs_selector", Field.U16) + self.register_field("fs_attrib", Field.U16, Field.BITMASK) + self.register_field("fs_limit", Field.U32) + self.register_field("fs_base", Field.U64) + + self.register_field("gs_selector", Field.U16) + self.register_field("gs_attrib", Field.U16, Field.BITMASK) + self.register_field("gs_limit", Field.U32) + self.register_field("gs_base", Field.U64) + + self.register_field("gdtr_selector", Field.U16) + self.register_field("gdtr_attrib", Field.U16, Field.BITMASK) + self.register_field("gdtr_limit", Field.U32) + self.register_field("gdtr_base", Field.U64) + + self.register_field("ldtr_selector", Field.U16) + self.register_field("ldtr_attrib", Field.U16, Field.BITMASK) + self.register_field("ldtr_limit", Field.U32) + self.register_field("ldtr_base", Field.U64) + + self.register_field("idtr_selector", Field.U16) + self.register_field("idtr_attrib", Field.U16, Field.BITMASK) + self.register_field("idtr_limit", Field.U32) + self.register_field("idtr_base", Field.U64) + + self.register_field("tr_selector", Field.U16) + self.register_field("tr_attrib", Field.U16, Field.BITMASK) + self.register_field("tr_limit", Field.U32) + self.register_field("tr_base", Field.U64) + + self.register_field("reserved_1", + Field.U8, Field.ARRAY, bytearray([0] * 43)) + + self.register_field("cpl", Field.U8) + + self.register_field("reserved_2", + Field.U8, Field.ARRAY, bytearray([0] * 4)) + + self.register_field("efer", Field.U64) + + self.register_field("reserved_3", + Field.U8, Field.ARRAY, bytearray([0] * 104)) + + self.register_field("xss", Field.U64) + self.register_field("cr4", Field.U64) + self.register_field("cr3", Field.U64) + self.register_field("cr0", Field.U64) + self.register_field("dr7", Field.U64) + self.register_field("dr6", Field.U64) + self.register_field("rflags", Field.U64) + self.register_field("rip", Field.U64) + + self.register_field("reserved_4", + Field.U8, Field.ARRAY, bytearray([0] * 88)) + + self.register_field("rsp", Field.U64) + + self.register_field("reserved_5", + Field.U8, Field.ARRAY, bytearray([0] * 24)) + + self.register_field("rax", Field.U64) + self.register_field("star", Field.U64) + self.register_field("lstar", Field.U64) + self.register_field("cstar", Field.U64) + self.register_field("sfmask", Field.U64) + self.register_field("kernel_gs_base", Field.U64) + self.register_field("sysenter_cs", Field.U64) + self.register_field("sysenter_esp", Field.U64) + self.register_field("sysenter_eip", Field.U64) + self.register_field("cr2", Field.U64) + + self.register_field("reserved_6", + Field.U8, Field.ARRAY, bytearray([0] * 32)) + + self.register_field("g_pat", Field.U64) + self.register_field("dbgctl", Field.U64) + self.register_field("br_from", Field.U64) + self.register_field("br_to", Field.U64) + self.register_field("last_excp_from", Field.U64) + self.register_field("last_excp_to", Field.U64) + + self.register_field("reserved_7", + Field.U8, Field.ARRAY, bytearray([0] * 72)) + + self.register_field("spec_ctrl", Field.U32) + + self.register_field("reserved_7b", + Field.U8, Field.ARRAY, bytearray([0] * 4)) + + self.register_field("pkru", Field.U32) + + self.register_field("reserved_7a", + Field.U8, Field.ARRAY, bytearray([0] * 20)) + + self.register_field("reserved_8", Field.U64) # rax duplicate + + self.register_field("rcx", Field.U64) + self.register_field("rdx", Field.U64, Field.BITMASK) + self.register_field("rbx", Field.U64) + + self.register_field("reserved_9", Field.U64) # rsp duplicate + + self.register_field("rbp", Field.U64) + self.register_field("rsi", Field.U64) + self.register_field("rdi", Field.U64) + self.register_field("r8", Field.U64) + self.register_field("r9", Field.U64) + self.register_field("r10", Field.U64) + self.register_field("r11", Field.U64) + self.register_field("r12", Field.U64) + self.register_field("r13", Field.U64) + self.register_field("r14", Field.U64) + self.register_field("r15", Field.U64) + + self.register_field("reserved_10", + Field.U8, Field.ARRAY, bytearray([0] * 16)) + + self.register_field("sw_exit_code", Field.U64) + self.register_field("sw_exit_info_1", Field.U64) + self.register_field("sw_exit_info_2", Field.U64) + self.register_field("sw_scratch", Field.U64) + + self.register_field("reserved_11", + Field.U8, Field.ARRAY, bytearray([0] * 56)) + + self.register_field("xcr0", Field.U64) + self.register_field("valid_bitmap", + Field.U8, Field.ARRAY, bytearray([0] * 16)) + self.register_field("x87_state_gpa", + Field.U64) + + def amd64_cpu_init(self): + # AMD64 Architecture Programmer=E2=80=99s Manual + # Volume 2: System Programming. + # + # 14.1.3 Processor Initialization State + # + # Values after INIT + + self.cr0 =3D (1 << 4) + self.rip =3D 0xfff0 + + self.cs_selector =3D 0xf000 + self.cs_base =3D 0xffff0000 + self.cs_limit =3D 0xffff + + self.ds_limit =3D 0xffff + + self.es_limit =3D 0xffff + self.fs_limit =3D 0xffff + self.gs_limit =3D 0xffff + self.ss_limit =3D 0xffff + + self.gdtr_limit =3D 0xffff + self.idtr_limit =3D 0xffff + + self.ldtr_limit =3D 0xffff + self.tr_limit =3D 0xffff + + self.dr6 =3D 0xffff0ff0 + self.dr7 =3D 0x0400 + self.rflags =3D 0x2 + self.xcr0 =3D 0x1 + + def kvm_cpu_init(self): + # svm_set_cr4() sets guest X86_CR4_MCE bit if host + # has X86_CR4_MCE enabled + self.cr4 =3D 0x40 + + # svm_set_efer sets guest EFER_SVME (Secure Virtual Machine enable) + self.efer =3D 0x1000 + + # init_vmcb + init_sys_seg() sets + # SVM_SELECTOR_P_MASK | SEG_TYPE_LDT + self.ldtr_attrib =3D 0x0082 + + # init_vmcb + init_sys_seg() sets + # SVM_SELECTOR_P_MASK | SEG_TYPE_BUSY_TSS16 + self.tr_attrib =3D 0x0083 + + # kvm_arch_vcpu_create() in arch/x86/kvm/x86.c + self.g_pat =3D 0x0007040600070406 + + def qemu_cpu_init(self): + # Based on logic in x86_cpu_reset() + # + # file target/i386/cpu.c + + def attr(mask): + return (mask >> VMSA.ATTR_TYPE_SHIFT) + + self.ldtr_attrib =3D attr(VMSA.ATTR_P_MASK | + (2 << VMSA.ATTR_TYPE_SHIFT)) + self.tr_attrib =3D attr(VMSA.ATTR_P_MASK | + (11 << VMSA.ATTR_TYPE_SHIFT)) + self.cs_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_CS_MASK | + VMSA.ATTR_R_MASK | + VMSA.ATTR_A_MASK) + self.ds_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_W_MASK | + VMSA.ATTR_A_MASK) + self.es_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_W_MASK | + VMSA.ATTR_A_MASK) + self.ss_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_W_MASK | + VMSA.ATTR_A_MASK) + self.fs_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_W_MASK | + VMSA.ATTR_A_MASK) + self.gs_attrib =3D attr(VMSA.ATTR_P_MASK | + VMSA.ATTR_S_MASK | + VMSA.ATTR_W_MASK | + VMSA.ATTR_A_MASK) + + self.g_pat =3D 0x0007040600070406 + + def cpu_sku(self, family, model, stepping): + stepping &=3D 0xf + model &=3D 0xff + family &=3D 0xfff + + self.rdx.value =3D stepping + + if family > 0xf: + self.rdx.value |=3D 0xf00 | ((family - 0x0f) << 20) + else: + self.rdx.value |=3D family << 8 + + self.rdx.value |=3D ((model & 0xf) << 4) | ((model >> 4) << 16) + + def reset_addr(self, reset_addr): + reset_cs =3D reset_addr & 0xffff0000 + reset_ip =3D reset_addr & 0x0000ffff + + self.rip.value =3D reset_ip + self.cs_base.value =3D reset_cs + + +class OVMF(object): + + OVMF_TABLE_FOOTER_GUID =3D UUID("96b582de-1fb2-45f7-baea-a366c55a082d") + SEV_INFO_BLOCK_GUID =3D UUID("00f771de-1a7e-4fcb-890e-68c77e2fb44e") + + def __init__(self): + self.entries =3D {} + + def load(self, content): + expect =3D OVMF.OVMF_TABLE_FOOTER_GUID.bytes_le + actual =3D content[-48:-32] + if expect !=3D actual: + raise Exception("OVMF footer GUID not found") + + tablelen =3D int.from_bytes(content[-50:-48], byteorder=3D'little') + + if tablelen =3D=3D 0: + raise Exception("OVMF tables zero length") + + table =3D content[-(32 + tablelen):-50] + + self.parse_table(table) + + def parse_table(self, data): + while len(data) > 0: + entryuuid =3D UUID(bytes_le=3Ddata[-16:]) + entrylen =3D int.from_bytes(data[-18:-16], byteorder=3D'little= ') + entrydata =3D data[-entrylen:-18] + + self.entries[str(entryuuid)] =3D entrydata + + data =3D data[0:-entrylen] + + def reset_addr(self): + if str(OVMF.SEV_INFO_BLOCK_GUID) not in self.entries: + raise Exception("SEV info block GUID not found") + + reset_addr =3D int.from_bytes( + self.entries[str(OVMF.SEV_INFO_BLOCK_GUID)], "little") + return reset_addr + + class GUIDTable(abc.ABC): GUID_LEN =3D 16 =20 @@ -242,6 +664,26 @@ class ConfidentialVM(object): log.debug("VMSA CPU 1(sha256): %s", sha256(self.vmsa_cpu1).hexdigest()) =20 + def build_vmsas(self, family, model, stepping): + ovmf =3D OVMF() + ovmf.load(self.firmware) + + vmsa =3D VMSA() + vmsa.amd64_cpu_init() + vmsa.kvm_cpu_init() + vmsa.qemu_cpu_init() + + vmsa.cpu_sku(family, model, stepping) + + self.vmsa_cpu0 =3D vmsa.pack() + log.debug("VMSA CPU 0(sha256): %s", + sha256(self.vmsa_cpu0).hexdigest()) + + vmsa.reset_addr(ovmf.reset_addr()) + self.vmsa_cpu1 =3D vmsa.pack() + log.debug("VMSA CPU 1(sha256): %s", + sha256(self.vmsa_cpu1).hexdigest()) + def get_cpu_state(self): if self.num_cpus is None: raise UnsupportedUsageException( @@ -514,6 +956,12 @@ def parse_command_line(): help=3D'VMSA state for the boot CPU') vmconfig.add_argument('--vmsa-cpu1', '-1', help=3D'VMSA state for the additional CPUs') + vmconfig.add_argument('--cpu-family', type=3Dint, + help=3D'Hypervisor host CPU family number') + vmconfig.add_argument('--cpu-model', type=3Dint, + help=3D'Hypervisor host CPU model number') + vmconfig.add_argument('--cpu-stepping', type=3Dint, + help=3D'Hypervisor host CPU stepping number') vmconfig.add_argument('--tik', help=3D'TIK file for domain') vmconfig.add_argument('--tek', @@ -577,6 +1025,20 @@ def check_usage(args): raise UnsupportedUsageException( "--initrd/--cmdline require --kernel") =20 + sku =3D [args.cpu_family, args.cpu_model, args.cpu_stepping] + if sku.count(None) =3D=3D len(sku): + if args.vmsa_cpu1 is not None and args.vmsa_cpu0 is None: + raise UnsupportedUsageException( + "VMSA for additional CPU also requires VMSA for boot CPU") + else: + if args.vmsa_cpu0 is not None or args.vmsa_cpu1 is not None: + raise UnsupportedUsageException( + "VMSA files are mutually exclusive with CPU SKU") + + if sku.count(None) !=3D 0: + raise UnsupportedUsageException( + "CPU SKU needs family, model and stepping for SEV-ES domai= n") + =20 def attest(args): if args.domain is None: @@ -617,6 +1079,11 @@ def attest(args): if args.vmsa_cpu1 is not None: cvm.load_vmsa_cpu1(args.vmsa_cpu1) =20 + if args.cpu_family is not None: + cvm.build_vmsas(args.cpu_family, + args.cpu_model, + args.cpu_stepping) + if args.domain is not None: cvm.load_domain(args.connect, args.domain, --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) client-ip=170.10.129.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832192; cv=none; d=zohomail.com; s=zohoarc; b=FVJPUC6SrlviG/vLgKux1HQkyOBgjWCtum07ym/URc+rWz47Cesn/eZhtbqKyWcpl0tUI88RTPKz9HDJWIN1K7SJ5k7MnyoRuJlBoNf9+kZZtdNNIo3kbUnU4bpZ2bgd7NNKPxteA9tsEo5mpT8B/KC4Wo5+dt3YdrZOz2Dau0s= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832192; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=99R5GioBNuArJgQvJbDj72nMtqFat3FDU2B/sz2CfFI=; b=DmAkGE54uP1VFnftc+/eM+VVtZEmH9tjAOSogn+g4KyMpmhwJHl4xWNMYrXicJtP/NfttjkDS2lHCZpkghOFocWZ2pQKEP6/XDbD/88ebxFuYU85hqEjuOrxgWsQxqGmITDSkM1eW6jE40AI2BITZ3DseQq6x2klD3rp18Q+Y80= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by mx.zohomail.com with SMTPS id 1667832192401488.7997962354676; Mon, 7 Nov 2022 06:43:12 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-590-eU960lNFOdmWV1bFt0L2ZA-1; Mon, 07 Nov 2022 09:42:12 -0500 Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 80DDB882826; Mon, 7 Nov 2022 14:42:10 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 6BCD240C2143; Mon, 7 Nov 2022 14:42:10 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 82A91194707E; Mon, 7 Nov 2022 14:41:46 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 263201946588 for ; Mon, 7 Nov 2022 14:41:42 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 12C3940C2089; Mon, 7 Nov 2022 14:41:37 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 6687E40C2064; Mon, 7 Nov 2022 14:41:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832191; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=99R5GioBNuArJgQvJbDj72nMtqFat3FDU2B/sz2CfFI=; b=bBqsxy94oaLCRcun46h1crV/ltt9G7VTIe17Vcf5agZXKBkgW+wJUxB/6MTalZDqYWwsvt scM2rjXaLkKkgcxb0V+hTS3nT72aS47oIgjrIvyrQ3fhdAdIN+JMBbQw3G0nDKZPoZR4ei Wn21BsL7JXswlB9pBjwlzoaRiDMpzWA= X-MC-Unique: eU960lNFOdmWV1bFt0L2ZA-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 08/12] tools: load CPU count and CPU SKU from libvirt Date: Mon, 7 Nov 2022 14:41:23 +0000 Message-Id: <20221107144127.973324-9-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832192920100001 When validating a SEV-ES guest, we need to know the CPU count and VMSA state. We can get the CPU count directly from libvirt's guest info. The VMSA state can be constructed automatically if we query the CPU SKU from host capabilities XML. Neither of these is secure, however, so this behaviour is restricted. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 4 ---- tools/virt-qemu-sev-validate | 26 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index 34ef328fe8..eef8a0281c 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -358,7 +358,6 @@ Validate the measurement of a SEV-ES SMP guest booting = from disk: =20 # virt-dom-sev-validate \ --insecure \ - --num-cpus 2 \ --vmsa-cpu0 vmsa0.bin \ --vmsa-cpu1 vmsa1.bin \ --tk this-guest-tk.bin \ @@ -371,9 +370,6 @@ automatically constructed VMSA: =20 # virt-dom-sev-validate \ --insecure \ - --cpu-family 23 \ - --cpu-model 49 \ - --cpu-stepping 0 \ --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index ef8fa6fa27..37f6f65bac 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -873,6 +873,14 @@ class LibvirtConfidentialVM(ConfidentialVM): if self.policy is None: self.policy =3D sevinfo["sev-policy"] =20 + if self.is_sev_es() and self.num_cpus is None: + if secure: + raise InsecureUsageException( + "Using CPU count from guest is not secure") + + info =3D self.dom.info() + self.num_cpus =3D info[3] + if self.firmware is None: if remote: raise UnsupportedUsageException( @@ -918,6 +926,24 @@ class LibvirtConfidentialVM(ConfidentialVM): "Using cmdline string from XML is not secure") self.kernel_table.load_cmdline(cmdlinenodes[0].text) =20 + capsxml =3D self.conn.getCapabilities() + capsdoc =3D etree.fromstring(capsxml) + + if self.is_sev_es() and self.vmsa_cpu0 is None: + if secure: + raise InsecureUsageException( + "Using CPU SKU from capabilities is not secure") + + sig =3D capsdoc.xpath("/capabilities/host/cpu/signature") + if len(sig) !=3D 1: + raise UnsupportedUsageException( + "Libvirt is too old to report host CPU signature") + + cpu_family =3D int(sig[0].get("family")) + cpu_model =3D int(sig[0].get("model")) + cpu_stepping =3D int(sig[0].get("stepping")) + self.build_vmsas(cpu_family, cpu_model, cpu_stepping) + =20 def parse_command_line(): parser =3D argparse.ArgumentParser( --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) client-ip=170.10.133.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832248; cv=none; d=zohomail.com; s=zohoarc; b=NApSsJkll1WwBgBaqS/NxpQ9f/FPEI7OfUqNqmaim0IjLe2nf9yjOydE5nY2f4kbqgv8U2qpJ+5p9KZN/0DP9akU6pRQyMlirDHVG1AcGUNb8X5GQhz19BxKySoxf2guXcaYQjAes+jI2GQzTIXcv/1+ds1Czw6eY2xQgXNL8Cw= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832248; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=T7fRg5soZLLFPCRRuquH4Usdu3dTRTuT+P0cGqAJ7d4=; b=WqJuiFmgVYo3p5CoxqqR2k2FTjke20aaUC3YgA25uO1QB3Q5MdoZgeI/0DFPYtRX03DdKeEwU1V+sGHZqJHu9rOux9sTz5x+R5TN9ZI5UYItPj6Gs3+Ugqsucga1Bnhjd+gzgi0bnek4HagyoPrVtI9R6jH+2eKFud7opiWUK8o= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.133.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by mx.zohomail.com with SMTPS id 1667832248353548.0181312750694; Mon, 7 Nov 2022 06:44:08 -0800 (PST) Received: from mimecast-mx02.redhat.com (mx3-rdu2.redhat.com [66.187.233.73]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-639-Q72fYl3-M_aAfcH8Ciuf9Q-1; Mon, 07 Nov 2022 09:42:00 -0500 Received: from smtp.corp.redhat.com (int-mx06.intmail.prod.int.rdu2.redhat.com [10.11.54.6]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 8FFE3293248F; Mon, 7 Nov 2022 14:41:57 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 7791A2166B29; Mon, 7 Nov 2022 14:41:57 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 410DB1946588; Mon, 7 Nov 2022 14:41:45 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 025DA1947051 for ; Mon, 7 Nov 2022 14:41:38 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id EBA7640C2143; Mon, 7 Nov 2022 14:41:37 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 4CDCE40C2064; Mon, 7 Nov 2022 14:41:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832247; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=T7fRg5soZLLFPCRRuquH4Usdu3dTRTuT+P0cGqAJ7d4=; b=OyK0Wnd8V7sM56waJmJlOcLywJJO/8HFeMaKGR7HfFzThMuAov7oa0b2R1mx78PUqnnlRa 3hnC8K0akTZgK1zNnb+F3TqrOQHkAnjAKYesBDZ0Z9R8Av/KuThfu4quzCoVXhN/iMi+SY KXonEkmdXe+/Wx6HJ8HinsMEJUbtlC4= X-MC-Unique: Q72fYl3-M_aAfcH8Ciuf9Q-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 09/12] tools: support generating SEV secret injection tables Date: Mon, 7 Nov 2022 14:41:24 +0000 Message-Id: <20221107144127.973324-10-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.6 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832249387100001 It is possible to build OVMF for SEV with an embedded Grub that can fetch LUKS disk secrets. This adds support for injecting secrets in the required format. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 83 ++++++++++ tools/virt-qemu-sev-validate | 183 +++++++++++++++++++++-- 2 files changed, 257 insertions(+), 9 deletions(-) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index eef8a0281c..24cdbb6d92 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -189,6 +189,46 @@ understand any configuration mistakes that have been m= ade. If the will be skipped. The result is that the validation will likely be reported= as failed. =20 +Secret injection options +------------------------ + +These options provide a way to inject a secret if validation of the +launch measurement passes. + +``--inject-secret ALIAS-OR-GUID:PATH`` + +Path to a file containing a secret to inject into the guest OS. Typical +usage would be to supply a password for unlocking the root filesystem +full disk encryption. ``ALIAS`` can be one of the well known secrets: + +* ``luks-key`` - bytes to use as a key for unlocking a LUKS key slot. + GUID of ``736869e5-84f0-4973-92ec-06879ce3da0b``. + +Alternatively ``GUID`` refers to an arbitrary UUID of the callers +choosing. The contents of ``PATH`` are defined by the requirements +of the associated GUID, and will used as-is without modification. +In particular be aware: + + * Avoid unwanted trailing newline characters in ``PATH`` unless + mandated by the ``GUID``. + * Any trailing ``NUL`` byte must be explicitly included in ``PATH`` + if mandated by the ``GUID``. + +This argument can be repeated multiple times, provided a different +``GUID`` is given for each instance. + +``--secret-header PATH`` + +Path to a file in which the injected secret header will be written in base= 64 +format and later injected into the domain. This is required if there is no +connection to libvirt, otherwise the secret will be directly injected. + +``--secret-payload PATH`` + +Path to a file in which the injected secret payload will be written in bas= e64 +format and later injected into the domain. This is required if there is no +connection to libvirt, otherwise the secret will be directly injected. + EXAMPLES =3D=3D=3D=3D=3D=3D=3D=3D =20 @@ -263,6 +303,26 @@ automatically constructed VMSA: --build-id 13 \ --policy 7 =20 +Validate the measurement of a SEV guest booting from disk and +inject a disk password on success: + +:: + + # virt-dom-sev-validate \ + --loader OVMF.sev.fd \ + --tk this-guest-tk.bin \ + --measurement Zs2pf19ubFSafpZ2WKkwquXvACx9Wt/BV+eJwQ/taO8jhyIj/F8sw= FrybR1fZ2ID \ + --api-major 0 \ + --api-minor 24 \ + --build-id 13 \ + --policy 3 \ + --disk-password passwd.txt \ + --secret-header secret-header.b64 \ + --secret-payload secret-payload.b64 + +The ``secret-header.b64`` and ``secret-payload.b64`` files can now be sent= to +the virtualization host for injection. + Fetch from remote libvirt ------------------------- =20 @@ -323,6 +383,18 @@ automatically constructed VMSA: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV guest booting from disk and +inject a disk password on success: + +:: + + # virt-dom-sev-validate \ + --connect qemu+ssh://root@some.remote.host/system \ + --loader OVMF.sev.fd \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 \ + --disk-password passwd.txt + Fetch from local libvirt ------------------------ =20 @@ -373,6 +445,17 @@ automatically constructed VMSA: --tk this-guest-tk.bin \ --domain fedora34x86_64 =20 +Validate the measurement of a SEV guest booting from disk and +inject a disk password on success: + +:: + + # virt-dom-sev-validate \ + --insecure \ + --tk this-guest-tk.bin \ + --domain fedora34x86_64 \ + --disk-password passwd.txt + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 diff --git a/tools/virt-qemu-sev-validate b/tools/virt-qemu-sev-validate index 37f6f65bac..712a4e4593 100755 --- a/tools/virt-qemu-sev-validate +++ b/tools/virt-qemu-sev-validate @@ -36,16 +36,19 @@ =20 import abc import argparse -from base64 import b64decode +from base64 import b64decode, b64encode from hashlib import sha256 import hmac import logging +import os import re import socket from struct import pack import sys import traceback from uuid import UUID +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, mod= es + =20 from lxml import etree import libvirt @@ -579,7 +582,46 @@ class KernelTable(GUIDTable): return entries =20 =20 -class ConfidentialVM(object): +class SecretsTable(GUIDTable): + + TABLE_GUID =3D UUID('{1e74f542-71dd-4d66-963e-ef4287ff173b}').bytes_le + + GUID_ALIASES =3D { + "luks-key": UUID('{736869e5-84f0-4973-92ec-06879ce3da0b}') + } + + def __init__(self): + super().__init__(guid=3Dself.TABLE_GUID, + lenlen=3D4) + self.secrets =3D {} + + def load_secret(self, alias_or_guid, path): + guid =3D None + if re.match(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-= fA-F]{4}-[0-9a-fA-F]{12}$", + alias_or_guid): + guid =3D UUID(alias_or_guid) + else: + if alias_or_guid not in self.GUID_ALIASES: + raise UnsupportedUsageException( + "Secret alias '%s' is not known" % alias_or_guid) + + guid =3D self.GUID_ALIASES[alias_or_guid] + + if guid in self.secrets: + raise UnsupportedUsageException( + "Secret for GUID %s already loaded" % guid) + + with open(path, 'rb') as fh: + self.secrets[guid] =3D fh.read() + + def entries(self): + entries =3D bytes([]) + for guid, value in self.secrets.items(): + entries +=3D self.build_entry(guid.bytes_le, value, 4) + return entries + + +class ConfidentialVM(abc.ABC): POLICY_BIT_SEV_ES =3D 2 POLICY_VAL_SEV_ES =3D (1 << POLICY_BIT_SEV_ES) =20 @@ -605,6 +647,7 @@ class ConfidentialVM(object): self.vmsa_cpu1 =3D None =20 self.kernel_table =3D KernelTable() + self.secrets_table =3D SecretsTable() =20 def is_sev_es(self): return self.policy & self.POLICY_VAL_SEV_ES @@ -757,6 +800,82 @@ class ConfidentialVM(object): raise AttestationFailedException( "Measurement does not match, VM is not trustworthy") =20 + def build_secrets(self): + measurement, _ =3D self.get_measurements() + + iv =3D os.urandom(16) + + secret_table =3D self.secrets_table.build() + + cipher =3D Cipher(algorithms.AES(self.tek), modes.CTR(iv)) + enc =3D cipher.encryptor() + secret_table_ciphertext =3D (enc.update(secret_table) + + enc.finalize()) + + flags =3D 0 + + ## + # Table 55. LAUNCH_SECRET Packet Header Buffer + ## + header =3D ( + flags.to_bytes(4, byteorder=3D'little') + + iv + ) + + # AMD Secure Encrypted Virtualization API , section 6.6 + # + # hdrmac =3D HMAC(0x01 || FLAGS || IV || GUEST_LENGTH || + # TRANS_LENGTH || DATA || + # MEASURE; GCTX.TIK) + # + msg =3D ( + bytes([0x01]) + + flags.to_bytes(4, byteorder=3D'little') + + iv + + len(secret_table).to_bytes(4, byteorder=3D'little') + + len(secret_table).to_bytes(4, byteorder=3D'little') + + secret_table_ciphertext + + measurement + ) + + h =3D hmac.new(self.tik, msg, 'sha256') + header =3D ( + flags.to_bytes(4, byteorder=3D'little') + + iv + + h.digest() + ) + + header64 =3D b64encode(header).decode('utf8') + secret64 =3D b64encode(secret_table_ciphertext).decode('utf8') + log.debug("Header: %s (%d bytes)", header64, len(header)) + log.debug("Secret: %s (%d bytes)", + secret64, len(secret_table_ciphertext)) + + return header64, secret64 + + @abc.abstractmethod + def inject_secrets(self): + pass + + +class OfflineConfidentialVM(ConfidentialVM): + def __init__(self, + secret_header=3DNone, + secret_payload=3DNone, + **kwargs): + super().__init__(**kwargs) + + self.secret_header =3D secret_header + self.secret_payload =3D secret_payload + + def inject_secrets(self): + header64, secret64 =3D self.build_secrets() + + with open(self.secret_header, "wb") as fh: + fh.write(header64.encode('utf8')) + with open(self.secret_payload, "wb") as fh: + fh.write(secret64.encode('utf8')) + =20 class LibvirtConfidentialVM(ConfidentialVM): def __init__(self, **kwargs): @@ -944,6 +1063,14 @@ class LibvirtConfidentialVM(ConfidentialVM): cpu_stepping =3D int(sig[0].get("stepping")) self.build_vmsas(cpu_family, cpu_model, cpu_stepping) =20 + def inject_secrets(self): + header64, secret64 =3D self.build_secrets() + + params =3D {"sev-secret": secret64, + "sev-secret-header": header64} + self.dom.setLaunchSecurityState(params, 0) + self.dom.resume() + =20 def parse_command_line(): parser =3D argparse.ArgumentParser( @@ -1006,6 +1133,15 @@ def parse_command_line(): vmconn.add_argument('--ignore-config', '-g', action=3D'store_true', help=3D'Do not attempt to sanity check the guest c= onfig') =20 + # Arguments related to secret injection + inject =3D parser.add_argument_group("Secret injection parameters") + inject.add_argument('--inject-secret', '-s', action=3D'append', defaul= t=3D[], + help=3D'ALIAS-OR-GUID:PATH file containing secret = to inject') + inject.add_argument('--secret-payload', + help=3D'Path to file to write secret data payload = to') + inject.add_argument('--secret-header', + help=3D'Path to file to write secret data header t= o') + return parser.parse_args() =20 =20 @@ -1046,6 +1182,15 @@ def check_usage(args): raise UnsupportedUsageException( "Either --firmware or --domain is required") =20 + if len(args.inject_secret) > 0: + if args.secret_header is None: + raise UnsupportedUsageException( + "Either --secret-header or --domain is required") + + if args.secret_payload is None: + raise UnsupportedUsageException( + "Either --secret-payload or --domain is required") + if args.kernel is None: if args.initrd is not None or args.cmdline is not None: raise UnsupportedUsageException( @@ -1065,15 +1210,22 @@ def check_usage(args): raise UnsupportedUsageException( "CPU SKU needs family, model and stepping for SEV-ES domai= n") =20 + secret =3D [args.secret_payload, args.secret_header] + if secret.count(None) > 0 and secret.count(None) !=3D len(secret): + raise UnsupportedUsageException( + "Both --secret-payload and --secret-header are required") + =20 def attest(args): if args.domain is None: - cvm =3D ConfidentialVM(measurement=3Dargs.measurement, - api_major=3Dargs.api_major, - api_minor=3Dargs.api_minor, - build_id=3Dargs.build_id, - policy=3Dargs.policy, - num_cpus=3Dargs.num_cpus) + cvm =3D OfflineConfidentialVM(measurement=3Dargs.measurement, + api_major=3Dargs.api_major, + api_minor=3Dargs.api_minor, + build_id=3Dargs.build_id, + policy=3Dargs.policy, + num_cpus=3Dargs.num_cpus, + secret_header=3Dargs.secret_header, + secret_payload=3Dargs.secret_payload) else: cvm =3D LibvirtConfidentialVM(measurement=3Dargs.measurement, api_major=3Dargs.api_major, @@ -1117,10 +1269,23 @@ def attest(args): args.ignore_config) =20 cvm.attest() - if not args.quiet: print("OK: Looks good to me") =20 + for secret in args.inject_secret: + bits =3D secret.split(":") + if len(bits) !=3D 2: + raise UnsupportedUsageException( + "Expecting ALIAS-OR-GUID:PATH for injected secret") + + cvm.secrets_table.load_secret(bits[0], bits[1]) + + if len(args.inject_secret) > 0: + cvm.inject_secrets() + if not args.quiet: + print("OK: Injected %d secrets" % len(args.inject_secret)) + + def main(): args =3D parse_command_line() if args.debug: --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) client-ip=170.10.129.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832119; cv=none; d=zohomail.com; s=zohoarc; b=YVN8j+P4Y5qCPo307fxYMjfiBznhJuxTrZ8zfLWq0ymqWS1919AjMCD6OA41cULZMQrBHXzn0Sb1K16v0LS9/zMaqnO3bi6NoPjK94xTWNtJ/n3MHYAZD961eMICm+/ov4Mm6ovmQWlxnqEs1+GZeYCsPbTf7NlZtDjWGwpA6g8= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832119; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=zmDFwD/ffZPwBMlLubdfoqkkP+dH3BKrGMuF8hepxh4=; b=f2+V0aIhMPj+SVra96c4Px1J1Yh31XV093OPkMt0x2IIvYuBwAa8j2Geng2wp3QIxoLV2hRsl6PUaiIwUQpzY+XZxr/md2HbG+qudhYF0PMIBi0dN2LiWJZ/albsSWBBIDYmccuxQSqowfX7XtT7xCx7u1AlBaUFWI4rxlHPEcw= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by mx.zohomail.com with SMTPS id 1667832119282266.48100465556445; Mon, 7 Nov 2022 06:41:59 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-537-sk5N8oNfPQ2KH9WHm3En-Q-1; Mon, 07 Nov 2022 09:41:56 -0500 Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 68845857FAC; Mon, 7 Nov 2022 14:41:53 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 55FB840C2143; Mon, 7 Nov 2022 14:41:53 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 4F6CA19465A2; Mon, 7 Nov 2022 14:41:45 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id DC765194705D for ; Mon, 7 Nov 2022 14:41:38 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id CA81840C2144; Mon, 7 Nov 2022 14:41:38 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 3312440C2064; Mon, 7 Nov 2022 14:41:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832118; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=zmDFwD/ffZPwBMlLubdfoqkkP+dH3BKrGMuF8hepxh4=; b=amsTiLCB/aj9bZ8evRUv+GWuIVxsvF7F4VjK8RT+df50cr45fQj/+oUrW7JmWrXIjyQ5Al KmnrbYNLJ0enlmAprjN9bRZWJTmnxemxyrV/Jj92TFOXfeoYJOd6v3FQ1+by6JxAf86pNd Yrqv+Cxwl/xDPLttscg9ZPEOLlH598U= X-MC-Unique: sk5N8oNfPQ2KH9WHm3En-Q-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 10/12] docs/kbase: describe attestation for SEV guests Date: Mon, 7 Nov 2022 14:41:25 +0000 Message-Id: <20221107144127.973324-11-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832120550100001 Expand the SEV guest kbase guide with information about how to configure a SEV/SEV-ES guest when attestation is required, and mention the use of virt-qemu-sev-validate as a way to confirm it. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/kbase/launch_security_sev.rst | 105 +++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/docs/kbase/launch_security_sev.rst b/docs/kbase/launch_securit= y_sev.rst index 2734832487..7f692af748 100644 --- a/docs/kbase/launch_security_sev.rst +++ b/docs/kbase/launch_security_sev.rst @@ -206,6 +206,20 @@ libvirt to the correct OVMF binary. ... =20 +If intending to attest the boot measurement, it is required to use a +firmware binary that is stateless, as persistent NVRAM can undermine +the trust of the secure guest. This is achieved by telling libvirt +that a stateless binary is required + +:: + + ... + + hvm + + + ... + Memory ------ =20 @@ -373,6 +387,97 @@ running: # dmesg | grep -i sev AMD Secure Encrypted Virtualization (SEV) active =20 +Guest attestation for SEV/SEV-ES from a trusted host +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D + +Before a confidential guest is used, it may be desirable to attest the boot +measurement. To be trustworthy the attestation process needs to be perform= ed +from a machine that is already trusted. This would typically be a physical +machine that the guest owner controls, or could be a previously launched +confidential guest that has already itself been attested. Most notably, it= is +**not** possible to securely attest a guest from the hypervisor host itsel= f, +as the goal of the attestation process is to detect whether the hypervisor= is +malicious. + +Performing an attestation requires that the ```` element is +configured with a guest owner Diffie-Hellman (DH) certificate, and a sessi= on +data blob. These must be unique for every guest launch attempt. Any reuse = will +open avenues of attack for the hypervisor to fake the measurement. Unique = data +can be generated using the `sevctl `_ to= ol. + +First of all the Platform Diffie-Hellman key (PDH) for the hypervisor host +needs to be obtained. The PDH is used to negotiate a master secret between +the SEV firmware and external entities. + +The admin of the hypervisor can extract the PDH using:: + + $ sevctl export --full ${hostname}.pdh + +Upon receiving the PDH associated with the hypervisor, the guest owner sho= uld +validate its integrity:: + + $ sevctl verify --sev ${hostname}.pdh + PDH EP384 D256 008cec87d6bd9df67a35e7d6057a933463cd8a02440f60c5df150821b= 5662ee0 + =E2=AC=91 PEK EP384 E256 431ba88424378200d58b6fb5db9657268c599b1be25f80= 47ac2e2981eff667e6 + =E2=80=A2=E2=AC=91 OCA EP384 E256 b4f1d0a2144186d1aa9c63f19039834e729= f508000aa05a76ba044f8e1419765 + =E2=AC=91 CEK EP384 E256 22c27ee3c1c33287db24d3c06869a5ae933eb44148f= db70838019e267077c6b8 + =E2=AC=91 ASK R4096 R384 d8cd9d1798c311c96e009a91552f17b4ddc4886a= 064ec933697734965b9ab29db803c79604e2725658f0861bfaf09ad4 + =E2=80=A2=E2=AC=91 ARK R4096 R384 3d2c1157c29ef7bd4207fc0c8b08d= b080e579ceba267f8c93bec8dce73f5a5e2e60d959ac37ea82176c1a0c61ae203ed + + =E2=80=A2 =3D self signed, =E2=AC=91 =3D signs, =E2=80=A2=CC=B7 =3D inv= alid self sign, =E2=AC=91=CC=B8 =3D invalid signs + +Assuming this is successful, it is now possible to generate a unique launch +data for the guest boot attempt:: + + $ sevctl session --name ${myvmname} ${hostname}.pdh ${policy} + +This will generate four files + + * ``${myvmname}_tik.bin`` + * ``${myvmname}_tek.bin`` + * ``${myvmname}_godh.bin`` + * ``${myvmname}_session.bin`` + +The ``tik.bin`` and ``tek.bin`` files will be needed to perform the boot +attestation, and must be kept somewhere secure, away from the hypervisor +host. + +The ``godh.bin`` file contents should be copied into the ```` field +in the ```` configuration, while the ``session.bin`` file +contents should be copied into the ```` field. + +When launching the guest, it should be set to remain in the paused state w= ith +no vCPUs running:: + + $ virsh start --paused ${myvmname} + +With it launched, it is possible to query the launch measurement:: + + $ virsh domlaunchsecinfo ${myvmname} + sev-measurement: LMnv8i8N2QejezMPkscShF0cyPYCslgUoCxGWRqQuyt0Q0aUjVkH/T6= NcmkwZkWp + sev-api-major : 0 + sev-api-minor : 24 + sev-build-id : 15 + sev-policy : 3 + +The techiques required to validate the measurement reported are beyond the +scope of this document. Fortunately, libvirt provides a tool that can be u= sed +to perform this validation:: + + $ virt-qemu-sev-validate \ + --measurement LMnv8i8N2QejezMPkscShF0cyPYCslgUoCxGWRqQuyt0Q0aUjVkH/T= 6NcmkwZkWp + --api-major 0 + --api-minor 24 + --build-id 15 + --policy 3 + --tik ${myvmname}_tik.bin + --tek ${myvmname}_tek.bin + OK: Looks good to me + +The `man page <../manpages/virt-qemu-sev-validate.html>`__ for +``virt-qemu-sev-validate`` outlines a great many other ways to invoke this +tool. + Limitations =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) client-ip=170.10.129.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832131; cv=none; d=zohomail.com; s=zohoarc; b=HN9nN1bCPzS188Hgk9T7sW4pSeRDM1zPIMdVSKjorsbyjsGcKE/MWotYQ9hMS6G0tMdPp1PJua8tXdXI+DVRM8lPAdwudKVggisCj6oIp3s/abepaTlvg9r82EBN4xzEGWoJ7jhmrhX+wkeisLejW2iyGPiC/F96y0VL+AWd1CA= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832131; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=CCjziqOwaRQ+N/5QSdWc294OPH9/QNqKQeTNwSJJ/io=; b=GQ8Q9LhdWT03IPrbTz/YNEG0rlEktycYzyTdRxDiDZEEcICZ3FuSUv55fqcs7VTQUuyOcGsKOv20IZiuUWVHQN5rKOeWJMLW4SrMezgwcqBlWd2eRwxqtOVPYJLcKxlpvxgTU6uMLt21SVSRGybC9zxpwL8r4NT21wiR1jS3KDg= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by mx.zohomail.com with SMTPS id 1667832131907631.2622462660659; Mon, 7 Nov 2022 06:42:11 -0800 (PST) Received: from mimecast-mx02.redhat.com (mimecast-mx02.redhat.com [66.187.233.88]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-385-6nTvVmzcMrqZQXWqFOMlag-1; Mon, 07 Nov 2022 09:42:07 -0500 Received: from smtp.corp.redhat.com (int-mx09.intmail.prod.int.rdu2.redhat.com [10.11.54.9]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id D3C971012464; Mon, 7 Nov 2022 14:42:02 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id BE7954B400F; Mon, 7 Nov 2022 14:42:02 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id 99C211946A50; Mon, 7 Nov 2022 14:41:45 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id B1F5719465A0 for ; Mon, 7 Nov 2022 14:41:39 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id AD19D40C83AD; Mon, 7 Nov 2022 14:41:39 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id 1236940C2064; Mon, 7 Nov 2022 14:41:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832130; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=CCjziqOwaRQ+N/5QSdWc294OPH9/QNqKQeTNwSJJ/io=; b=VrPUSwNysrsM/TC9ztBTB6qbE+ilO6NWyCbYp7IZuf3hDH9vbLeFeda0Qs6UdZjTS/R9fv i6qwrIZbsPammL9u8XHuvpaJaxCmSK+2JD7QDRkJ+fcz2ehBiWvSw+kcbvhLeHuOG15xr1 SAhaTohwn3fn5Uv5M2VnvkARYMTR3SY= X-MC-Unique: 6nTvVmzcMrqZQXWqFOMlag-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 11/12] scripts: add systemtap script for capturing SEV-ES VMSA Date: Mon, 7 Nov 2022 14:41:26 +0000 Message-Id: <20221107144127.973324-12-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.9 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832132616100001 In general we expect to be able to construct a SEV-ES VMSA blob from knowledge about the AMD achitectural CPU register defaults, KVM setup and QEMU setup. If any of this unexpectedly changes, figuring out what's wrong could be horrible. This systemtap script demonstrates how to capture the real VMSA that is used for a SEV-ES as it is booted. The captured data can be fed into the 'sevctl vmsa show' command in order to produce formatted info with named registers, allowing a 'diff' to be performed. This script will need updating for any kernel version that is not 6.0, to set the correct line numbers. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- examples/systemtap/amd-sev-es-vmsa.stp | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 examples/systemtap/amd-sev-es-vmsa.stp diff --git a/examples/systemtap/amd-sev-es-vmsa.stp b/examples/systemtap/am= d-sev-es-vmsa.stp new file mode 100644 index 0000000000..551ed739b7 --- /dev/null +++ b/examples/systemtap/amd-sev-es-vmsa.stp @@ -0,0 +1,48 @@ +#!/usr/bin/stap +# +# Copyright (C) 2022 Red Hat, Inc. +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . +# +# A script that captures the VMSA blob for the boot vCPU and +# first additional vCPU, when a KVM guest is booted with SEV-ES +# +# The captured VMSA will be printed to the console in hex format, +# and can be converted to the required binary format by feeding +# it through +# +# perl -e 'while (<>) { print pack("C64", map { hex($_) } ( $_ =3D~ m/../g= )); }' > vmsa.bin +# + +probe begin { + printf("Running\n") +} + +function dump_vmsa(addr:long) { + printf("VMSA\n") + for (i =3D 0; i < 4096 ; i+=3D 64) { + printf("%.64M\n", addr + i); + } +} + +# This line number will need to be updated for the specific kernel +# version that is being probed. The line that needs to be targetted +# is the one beween the call to clflush_cache_range(...) and the +# call to sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE...). +# +# Line 632 is correct for Linux v6.0 +probe module("kvm_amd").statement("__sev_launch_update_vmsa@arch/x86/kvm/s= vm/sev.c:632") { + dump_vmsa($svm->vmsa) +} --=20 2.37.3 From nobody Wed Apr 24 22:47:24 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) client-ip=170.10.129.124; envelope-from=libvir-list-bounces@redhat.com; helo=us-smtp-delivery-124.mimecast.com; Authentication-Results: mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass(p=none dis=none) header.from=redhat.com ARC-Seal: i=1; a=rsa-sha256; t=1667832301; cv=none; d=zohomail.com; s=zohoarc; b=fdENZGL+KIg8rHfKZwQtjEYaHu6RhNJ9hALuV5bU/l80Pr79xHuUJG/t2F+SrP6CFXDHWnxh9DRTtAexpCuG5ti1smNhl1xnHxmrihHHoQw/hfXb7+iKkWo01nBLQRXO+OLc1rxU+mdQM7csls0Q7sTqiXM3VOf/SZzoD9g4TDg= ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com; s=zohoarc; t=1667832301; h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To; bh=ywSwys/TVvmvyJHiTQ74k7zQ8egP8yRRy4KOxODBLeE=; b=Q4kSuzJpIruroo3wv99En4DAu+aafjmNgdGbqCcrwpSr6INhRHnOOo8qr/9DIVkGaAURKXWWTvOxc93J2q1DRrAPHUqevh8U7ipJXxSE3AOjqK0GMfoPWmzlTSGuJYW2RvdPX4H/va5snGy+8HSMTR8r7djxnU6sY4icVFEwGFA= ARC-Authentication-Results: i=1; mx.zohomail.com; dkim=pass; spf=pass (zohomail.com: domain of redhat.com designates 170.10.129.124 as permitted sender) smtp.mailfrom=libvir-list-bounces@redhat.com; dmarc=pass header.from= (p=none dis=none) Return-Path: Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) by mx.zohomail.com with SMTPS id 16678323014021016.6485546384718; Mon, 7 Nov 2022 06:45:01 -0800 (PST) Received: from mimecast-mx02.redhat.com (mx3-rdu2.redhat.com [66.187.233.73]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id us-mta-193-j0wx80XnMhShKN4Y65DCqg-1; Mon, 07 Nov 2022 09:44:50 -0500 Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx02.redhat.com (Postfix) with ESMTPS id 30B293C0DDDD; Mon, 7 Nov 2022 14:42:03 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (unknown [10.30.29.100]) by smtp.corp.redhat.com (Postfix) with ESMTP id 120C740C83AD; Mon, 7 Nov 2022 14:42:03 +0000 (UTC) Received: from mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (localhost [IPv6:::1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id F2E561947069; Mon, 7 Nov 2022 14:41:45 +0000 (UTC) Received: from smtp.corp.redhat.com (int-mx01.intmail.prod.int.rdu2.redhat.com [10.11.54.1]) by mm-prod-listman-01.mail-001.prod.us-east-1.aws.redhat.com (Postfix) with ESMTP id A262A19465BA for ; Mon, 7 Nov 2022 14:41:40 +0000 (UTC) Received: by smtp.corp.redhat.com (Postfix) id 98DCA40C2143; Mon, 7 Nov 2022 14:41:40 +0000 (UTC) Received: from localhost.localdomain.com (unknown [10.33.36.58]) by smtp.corp.redhat.com (Postfix) with ESMTP id E7EAD40C2064; Mon, 7 Nov 2022 14:41:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1667832299; h=from:from:sender:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:list-id:list-help: list-unsubscribe:list-subscribe:list-post; bh=ywSwys/TVvmvyJHiTQ74k7zQ8egP8yRRy4KOxODBLeE=; b=LtUuLN51fouWqxAIeYyEYpqWb3SdhjxMk6bMhlkslfSO1Fk9g1P+hsYPakys9vSong3lEn /oflMyKy6QxvxGvly8R5Poiz/uywQ0s9bH4KMrEK8ogiOCQxDTGgmtfkao4zqLyO1VRE+i G9USMIoGtDjCI6nNlm8hgYhbpUEC3W8= X-MC-Unique: j0wx80XnMhShKN4Y65DCqg-1 X-Original-To: libvir-list@listman.corp.redhat.com From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: libvir-list@redhat.com Subject: [libvirt PATCH v4 12/12] docs/manpages: add checklist of problems for SEV attestation Date: Mon, 7 Nov 2022 14:41:27 +0000 Message-Id: <20221107144127.973324-13-berrange@redhat.com> In-Reply-To: <20221107144127.973324-1-berrange@redhat.com> References: <20221107144127.973324-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-BeenThere: libvir-list@redhat.com X-Mailman-Version: 2.1.29 Precedence: list List-Id: Development discussions about the libvirt library & tools List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?J=C3=A1n=20Tomko?= Errors-To: libvir-list-bounces@redhat.com Sender: "libvir-list" X-Scanned-By: MIMEDefang 3.1 on 10.11.54.1 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-ZohoMail-DKIM: pass (identity @redhat.com) X-ZM-MESSAGEID: 1667832301991100001 Despite efforts to make the virt-qemu-sev-validate tool friendly, it is a certainty that almost everyone who tries it will hit false negative results, getting a failure despite the VM being trustworthy. Diagnosing these problems is no easy matter, especially for those not familiar with SEV/SEV-ES in general. This extra docs text attempts to set out a checklist of items to look at to identify what went wrong. Reviewed-by: J=C3=A1n Tomko Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Cole Robinson --- docs/manpages/virt-qemu-sev-validate.rst | 116 +++++++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/docs/manpages/virt-qemu-sev-validate.rst b/docs/manpages/virt-= qemu-sev-validate.rst index 24cdbb6d92..f5f928603a 100644 --- a/docs/manpages/virt-qemu-sev-validate.rst +++ b/docs/manpages/virt-qemu-sev-validate.rst @@ -456,6 +456,122 @@ inject a disk password on success: --domain fedora34x86_64 \ --disk-password passwd.txt =20 +COMMON MISTAKES CHECKLIST +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D + +The complexity of configuring a guest and validating its boot measurement +means it is very likely to see the failure:: + + ERROR: Measurement does not match, VM is not trustworthy + +This error message assumes the worst, but in most cases will failure will = be +a result of either mis-configuring the guest, or passing the wrong informa= tion +when trying to validate it. The following information is a guide for what +items to check in order to stand the best chance of diagnosing the problem + +* Check the VM configuration for the DH certificate and session + blob in the libvirt guest XML. + + The content for these fields should be in base64 format, which is + what ``sevctl session`` generates. Other tools may generate the files + in binary format, so ensure it has been correctly converted to base64. + +* Check the VM configuration policy value matches the session blob + + The ```` value in libvirt guest XML has to match the value + passed to the ``sevctl session`` command. If this is mismatched + then the guest will not even start, and QEMU will show an error + such as:: + + sev_launch_start: LAUNCH_START ret=3D1 fw_error=3D11 'Bad measurement' + +* Check the correct TIK/TEK keypair are passed + + The TIK/TEK keypair are uniquely tied to each DH cert and session + blob. Make sure that the TIK/TEK keypair passed to this program + the ones matched to the DH cert and session blob configured for + the libvirt guest XML. This is one of the most common mistakes. + Further ensure that the TIK and TEK files are not swapped. + +* Check the firmware binary matches the one used to boot + + The firmware binary content is part of the data covered by the + launch measurement. Ensure that the firmware binary passed to + this program matches the one used to launch the guest. The + hypervisor host will periodically get software updates which + introduce a new firmware binary version. + +* Check the kernel, initrd and cmdline match the one used to boot + + If the guest is configured to use direct kernel boot, check that + the kernel, initrd and cmdline passed to this program match the + ones used to boot the guest. In the kernel cmdline whitespace + must be preserved exactly, including any leading or trailing + spaces. + +* Check whether the kernel hash measurement is enabled + + The ``kernelHashes`` property in the libvirt guest XML controls + whether hashes of the kernel, initrd and cmdline content are + covered by the boot measurement. If enabled, then the matching + content must be passed to this program. UIf disabled, then + the content must **NOT** be passed. + +* Check that the correct measurement hash is passed + + The measurement hash includes a nonce, so it will be different + on every boot attempt. Thus when validating the measuremnt it + is important ensure the most recent measurement is used. + +* Check the correct VMSA blobs / CPU SKU values for the host are used + + The VMSA blobs provide the initial register state for the + boot CPU and any additional CPUs. One of the registers + encodes the CPU SKU (family, model, stepping) of the physical + host CPU. Make sure that the VMSA blob used for validation + is one that matches the SKU of the host the guest is booted + on. Passing the CPU SKU values directly to the tool can + reduce the likelihood of using the wrong ones. + +* Check the CPU count is correct + + When passing VMSA blobs for SEV-ES guests, the number of CPUs + present will influence the measurement result. Ensure that the + correct vCPU count is used corresponding to the guest boot + attempt. + + +Best practice is to run this tool in completely offline mode and pass +all information as explicit command line parameters. When debugging +failures, however, it can be useful to tell it to connect to libvirt +and fetch information. If connecting to a remote libvirt instance, +it will fetch any information that can be trusted, which is the basic +VM launch state data. It will also sanity check the XML configuration +to identify some common mistakes. If the ``--insecure`` flag is passed +it can extract some configuration information and use that for the +attestation process. + +If the mistake still can't be identified, then this tool can be run +on the virtualization host. In that scenario the only three command +line parameters required are for the TIK, TEK and libvirt domain +name. It should be able to automatically determine all the other +information required. If it still reports a failure, this points +very strongly to the TIK/TEK pair not maching the configured +DH certificate and session blob. + +The ``--debug`` flag will display hashes and/or hex dumps for various +pieces of information used in the attestation process. Comparing the +``--debug`` output from running on the hypervisor host, against that +obtained when running in offline mode can give further guidance to +which parameter is inconsistent. + +As mentioned earlier in this document, bear in mind that in general +any attestation answers obtained from running on the hypervisor host +should not be trusted. So if a configuration mistake is identified +it is strongly recommended to re-run the attestation in offline mode +on a trusted machine. + + EXIT STATUS =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 --=20 2.37.3