From patchwork Tue Apr 14 02:51:38 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270030 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=xiH9S7+/; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VQj3Qnhz9s71 for ; Tue, 14 Apr 2020 12:52:44 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 6CFB081656; Tue, 14 Apr 2020 04:52:29 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="xiH9S7+/"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 5A2E481656; Tue, 14 Apr 2020 04:52:27 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1042.google.com (mail-pj1-x1042.google.com [IPv6:2607:f8b0:4864:20::1042]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id AF7F281469 for ; Tue, 14 Apr 2020 04:52:22 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1042.google.com with SMTP id o1so3785284pjs.4 for ; Mon, 13 Apr 2020 19:52:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=SIf054SS+BGBpefIvH+Iib1zi051VVq46HFn1JAxICM=; b=xiH9S7+/x3SAGnq001mu4mXpCe7CgzAgBs3s2SO/ctCYMEXCcNqx4YHzYovLHs0fXk QDlZVhpP92m6zDzZ4wetrXRS29c7X4hFp4czDet5/dJSHKO77tHBdCOTjvH5vKttUqUX I406Zfqr+EwK+N5okV2Kf5xxxLFduTSxErTHKGaSTU575JYI8zjx4dcOYmPQa23sZ0UX fN6IRdXFSB8PGdt10Cz57zu4F1TtnpqkExOsCm9FHbBcUMM+migdhD+W+m/7KQm57jsZ 4/zNaNIhd0f4zNFHra7IPNPlzlinbIoqWuB1UdZoWjKQP3daKT8hAOkwOpvb1x+vXaeo +PVg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=SIf054SS+BGBpefIvH+Iib1zi051VVq46HFn1JAxICM=; b=h3eSVra56NrffVvH0bMhLhP6uSd81PUvXM2TC+bw9ljiuWDSFa97wTgiBfIjl+UIHw kLxgH4A4uk4HKUsmieqekj868nJ+6EpIKkwli1sG48BEPotZy3GAHLEGHczsJZCgCVwp ZS8jL2OhLvXdyHJYG86zqB55RXNk6HZZd8Z17Df+srOGnNZmu7c6kcYXunxf0zMaDdRX YObOFOCgTM3zKJCnS02IwKBpPNp8sXYMNq9a7wOkKlyOXkw71K/3Pgzzr5SN6KfCzayl gMeCj6DFPUVC01SxAClV2OH0ZWYh7HsUnj1ptfxB4p5PVsQo24zSWxf/xOIMXyZ3s2lR 5HDA== X-Gm-Message-State: AGi0PubaXK1AbDSIOp/Cdj+I2b2k8YJuzQwP4XmPU+qsp0ASwS3Cp/Ox Ozu21NGLnrQPfeH9sr0Ib8jDKw== X-Google-Smtp-Source: APiQypLLcuJ/yvy6eL1BMcwl9AhtrvfQqQ/fiIDVvAn4/5E1CEJn6gtcqfqbDysl7ovwvmS/47JYeg== X-Received: by 2002:a17:902:8d8e:: with SMTP id v14mr19344024plo.186.1586832740842; Mon, 13 Apr 2020 19:52:20 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.18 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:20 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 01/17] efi_loader: add CONFIG_EFI_SECURE_BOOT config option Date: Tue, 14 Apr 2020 11:51:38 +0900 Message-Id: <20200414025154.27283-2-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean Under this configuration, UEFI secure boot support will be added in later patches. Signed-off-by: AKASHI Takahiro --- lib/efi_loader/Kconfig | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/efi_loader/Kconfig b/lib/efi_loader/Kconfig index 9890144d4161..71a0d003c914 100644 --- a/lib/efi_loader/Kconfig +++ b/lib/efi_loader/Kconfig @@ -145,4 +145,22 @@ config EFI_INITRD_FILESPEC help Full path of the initramfs file, e.g. mmc 0:2 initramfs.cpio.gz. +config EFI_SECURE_BOOT + bool "Enable EFI secure boot support" + depends on EFI_LOADER + select SHA256 + select RSA + select RSA_VERIFY_WITH_PKEY + select IMAGE_SIGN_INFO + select ASYMMETRIC_KEY_TYPE + select ASYMMETRIC_PUBLIC_KEY_SUBTYPE + select X509_CERTIFICATE_PARSER + select PKCS7_MESSAGE_PARSER + default n + help + Select this option to enable EFI secure boot support. + Once SecureBoot mode is enforced, any EFI binary can run only if + it is signed with a trusted key. To do that, you need to install, + at least, PK, KEK and db. + endif From patchwork Tue Apr 14 02:51:39 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270032 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=yRwg1T5p; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VR72Qmcz9s71 for ; Tue, 14 Apr 2020 12:53:06 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 1667E818E7; Tue, 14 Apr 2020 04:53:02 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="yRwg1T5p"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 24E5981718; Tue, 14 Apr 2020 04:52:38 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pf1-x442.google.com (mail-pf1-x442.google.com [IPv6:2607:f8b0:4864:20::442]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 1E195815F4 for ; Tue, 14 Apr 2020 04:52:26 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pf1-x442.google.com with SMTP id x3so5177280pfp.7 for ; Mon, 13 Apr 2020 19:52:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=UluuZgdsdFHP3XRpRioxK/wwS0oyVzBuHqylC7hjeH0=; b=yRwg1T5px7kRPS40EVG+esnPoebYYVAuX6fDpL2wsBeN8j69HLKnTN2iaYgIvfhSfd MtLy6klCa42h/+OLVbNoJ3C+0iK3tVFunvUszDNjN6qzOf4TtyrxMbWCz4/HopxpkQ9o JA9DpEpUgM8uD5qohAogt4DuoXGUZUVdB5mUnpYpd3LxyyWUCOLin4ChzL0S2O1q9vMK axtbppt19HFe1vp7VqoqZM54WL4pHD+pdgAWUu/t26PAlaLUtkGGIjKoTg8hgjd6McC1 stDKB43AJoosgDXQIvhGj5CYiRGnKsbN0ejlGSei3RHWVyePZyWYZP2fPCcflI0uuK1r K6DA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=UluuZgdsdFHP3XRpRioxK/wwS0oyVzBuHqylC7hjeH0=; b=YXkjs9DHdbN49qJM9A4tr4bHheGylt+SF6/RNcv5hQNpXehQBsbWoW4KB+//kIPdxs LoFrYtMWrcDgeb01/WYiH7eDcZfaO8PVglEO45ogbcmcIUCrEVEhyiokzXsI/+dF3TVe V0WEqdon2HwFuMqC0SIZ6P1eVqYNBnnNnucthm3TG+DdCqdPM7kkK0JMB9m/+1BLmp4U oWxy0IrzkJrIE6cXPwSdLB9IftUxyeIECIn8aspXpQe+rMQmiT0k1r2eC4Lor9QcCbjc oVYKIBkMYWxwkUradUGuKg6i7IecbHf58kpFmeYJDR6sLRA7MTnkRA/uerAVWwX1yFiy LFug== X-Gm-Message-State: AGi0PuY3ml1z4Gn/7viDvAQANqke5AOfNF6rXXMzFIGSLLb3RogMOBSi xE4YVOy3frQ0HcUhOAiloppHlw== X-Google-Smtp-Source: APiQypL3OVfv/PtrCo6g3tVB04fi9my+JUDMcreCiYo+qyC4ymlOhjKc1cgGQN0apZeMTFeliFm99A== X-Received: by 2002:a63:c149:: with SMTP id p9mr19467350pgi.389.1586832744281; Mon, 13 Apr 2020 19:52:24 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:23 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 02/17] efi_loader: add signature verification functions Date: Tue, 14 Apr 2020 11:51:39 +0900 Message-Id: <20200414025154.27283-3-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches. Signed-off-by: AKASHI Takahiro --- include/efi_api.h | 87 +++++ include/efi_loader.h | 72 ++++ lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++ 4 files changed, 743 insertions(+) create mode 100644 lib/efi_loader/efi_signature.c diff --git a/include/efi_api.h b/include/efi_api.h index 1c40ffc4f56c..77d6bf2660b9 100644 --- a/include/efi_api.h +++ b/include/efi_api.h @@ -18,6 +18,7 @@ #include #include +#include #ifdef CONFIG_EFI_LOADER #include @@ -329,6 +330,10 @@ struct efi_runtime_services { EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \ 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c) +#define EFI_IMAGE_SECURITY_DATABASE_GUID \ + EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \ + 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f) + #define EFI_FDT_GUID \ EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \ 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0) @@ -1682,4 +1687,86 @@ struct efi_load_file_protocol { #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000 +/* Certificate types in signature database */ +#define EFI_CERT_SHA256_GUID \ + EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \ + 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28) +#define EFI_CERT_RSA2048_GUID \ + EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \ + 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6) +#define EFI_CERT_X509_GUID \ + EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \ + 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72) +#define EFI_CERT_X509_SHA256_GUID \ + EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \ + 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed) +#define EFI_CERT_TYPE_PKCS7_GUID \ + EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \ + 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7) + +/** + * win_certificate_uefi_guid - A certificate that encapsulates + * a GUID-specific signature + * + * @hdr: Windows certificate header + * @cert_type: Certificate type + * @cert_data: Certificate data + */ +struct win_certificate_uefi_guid { + WIN_CERTIFICATE hdr; + efi_guid_t cert_type; + u8 cert_data[]; +} __attribute__((__packed__)); + +/** + * efi_variable_authentication_2 - A time-based authentication method + * descriptor + * + * This structure describes an authentication information for + * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS + * and should be included as part of a variable's value. + * Only EFI_CERT_TYPE_PKCS7_GUID is accepted. + * + * @time_stamp: Descriptor's time stamp + * @auth_info: Authentication info + */ +struct efi_variable_authentication_2 { + struct efi_time time_stamp; + struct win_certificate_uefi_guid auth_info; +} __attribute__((__packed__)); + +/** + * efi_signature_data - A format of signature + * + * This structure describes a single signature in signature database. + * + * @signature_owner: Signature owner + * @signature_data: Signature data + */ +struct efi_signature_data { + efi_guid_t signature_owner; + u8 signature_data[]; +} __attribute__((__packed__)); + +/** + * efi_signature_list - A format of signature database + * + * This structure describes a list of signatures with the same type. + * An authenticated variable's value is a concatenation of one or more + * efi_signature_list's. + * + * @signature_type: Signature type + * @signature_list_size: Size of signature list + * @signature_header_size: Size of signature header + * @signature_size: Size of signature + */ +struct efi_signature_list { + efi_guid_t signature_type; + u32 signature_list_size; + u32 signature_header_size; + u32 signature_size; +/* u8 signature_header[signature_header_size]; */ +/* struct efi_signature_data signatures[...][signature_size]; */ +} __attribute__((__packed__)); + #endif diff --git a/include/efi_loader.h b/include/efi_loader.h index 3f2792892f34..8cf85d2fb7e2 100644 --- a/include/efi_loader.h +++ b/include/efi_loader.h @@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src) #if CONFIG_IS_ENABLED(EFI_LOADER) #include +#include /* Maximum number of configuration tables */ #define EFI_MAX_CONFIGURATION_TABLES 16 @@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol; extern const efi_guid_t efi_guid_hii_config_access_protocol; extern const efi_guid_t efi_guid_hii_database_protocol; extern const efi_guid_t efi_guid_hii_string_protocol; +/* GUIDs for authentication */ +extern const efi_guid_t efi_guid_image_security_database; +extern const efi_guid_t efi_guid_sha256; +extern const efi_guid_t efi_guid_cert_x509; +extern const efi_guid_t efi_guid_cert_x509_sha256; /* GUID of RNG protocol */ extern const efi_guid_t efi_guid_rng_protocol; @@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data); efi_status_t efi_bootmgr_load(efi_handle_t *handle); +#ifdef CONFIG_EFI_SECURE_BOOT +#include + +/** + * efi_image_regions - A list of memory regions + * + * @max: Maximum number of regions + * @num: Number of regions + * @reg: array of regions + */ +struct efi_image_regions { + int max; + int num; + struct image_region reg[]; +}; + +/** + * efi_sig_data - A decoded data of struct efi_signature_data + * + * This structure represents an internal form of signature in + * signature database. A listed list may represent a signature list. + * + * @next: Pointer to next entry + * @onwer: Signature owner + * @data: Pointer to signature data + * @size: Size of signature data + */ +struct efi_sig_data { + struct efi_sig_data *next; + efi_guid_t owner; + void *data; + size_t size; +}; + +/** + * efi_signature_store - A decoded data of signature database + * + * This structure represents an internal form of signature database. + * + * @next: Pointer to next entry + * @sig_type: Signature type + * @sig_data_list: Pointer to signature list + */ +struct efi_signature_store { + struct efi_signature_store *next; + efi_guid_t sig_type; + struct efi_sig_data *sig_data_list; +}; + +struct x509_certificate; +struct pkcs7_message; + +bool efi_signature_verify_cert(struct x509_certificate *cert, + struct efi_signature_store *dbx); +bool efi_signature_verify_signers(struct pkcs7_message *msg, + struct efi_signature_store *dbx); +bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs, + struct pkcs7_message *msg, + struct efi_signature_store *db, + struct x509_certificate **cert); + +efi_status_t efi_image_region_add(struct efi_image_regions *regs, + const void *start, const void *end, + int nocheck); +#endif /* CONFIG_EFI_SECURE_BOOT */ + #else /* CONFIG_IS_ENABLED(EFI_LOADER) */ /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */ diff --git a/lib/efi_loader/Makefile b/lib/efi_loader/Makefile index 9b3b70447336..eff3c25ec301 100644 --- a/lib/efi_loader/Makefile +++ b/lib/efi_loader/Makefile @@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o +obj-y += efi_signature.o diff --git a/lib/efi_loader/efi_signature.c b/lib/efi_loader/efi_signature.c new file mode 100644 index 000000000000..23dac94c0593 --- /dev/null +++ b/lib/efi_loader/efi_signature.c @@ -0,0 +1,583 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Copyright (c) 2018 Patrick Wildt + * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* + * avoid duplicated inclusion: + * #include "../lib/crypto/x509_parser.h" + */ +#include "../lib/crypto/pkcs7_parser.h" + +const efi_guid_t efi_guid_image_security_database = + EFI_IMAGE_SECURITY_DATABASE_GUID; +const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID; +const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID; +const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID; +const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID; + +#ifdef CONFIG_EFI_SECURE_BOOT + +/** + * efi_hash_regions - calculate a hash value + * @regs: List of regions + * @hash: Pointer to a pointer to buffer holding a hash value + * @size: Size of buffer to be returned + * + * Calculate a sha256 value of @regs and return a value in @hash. + * + * Return: true on success, false on error + */ +static bool efi_hash_regions(struct efi_image_regions *regs, void **hash, + size_t *size) +{ + *size = 0; + *hash = calloc(1, SHA256_SUM_LEN); + if (!*hash) { + debug("Out of memory\n"); + return false; + } + *size = SHA256_SUM_LEN; + + hash_calculate("sha256", regs->reg, regs->num, *hash); +#ifdef DEBUG + debug("hash calculated:\n"); + print_hex_dump(" ", DUMP_PREFIX_OFFSET, 16, 1, + *hash, SHA256_SUM_LEN, false); +#endif + + return true; +} + +/** + * efi_hash_msg_content - calculate a hash value of contentInfo + * @msg: Signature + * @hash: Pointer to a pointer to buffer holding a hash value + * @size: Size of buffer to be returned + * + * Calculate a sha256 value of contentInfo in @msg and return a value in @hash. + * + * Return: true on success, false on error + */ +static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash, + size_t *size) +{ + struct image_region regtmp; + + *size = 0; + *hash = calloc(1, SHA256_SUM_LEN); + if (!*hash) { + debug("Out of memory\n"); + free(msg); + return false; + } + *size = SHA256_SUM_LEN; + + regtmp.data = msg->data; + regtmp.size = msg->data_len; + + hash_calculate("sha256", ®tmp, 1, *hash); +#ifdef DEBUG + debug("hash calculated based on contentInfo:\n"); + print_hex_dump(" ", DUMP_PREFIX_OFFSET, 16, 1, + *hash, SHA256_SUM_LEN, false); +#endif + + return true; +} + +/** + * efi_signature_verify - verify a signature with a certificate + * @regs: List of regions to be authenticated + * @signed_info: Pointer to PKCS7's signed_info + * @cert: x509 certificate + * + * Signature pointed to by @signed_info against image pointed to by @regs + * is verified by a certificate pointed to by @cert. + * @signed_info holds a signature, including a message digest which is to be + * compared with a hash value calculated from @regs. + * + * Return: true if signature is verified, false if not + */ +static bool efi_signature_verify(struct efi_image_regions *regs, + struct pkcs7_message *msg, + struct pkcs7_signed_info *ps_info, + struct x509_certificate *cert) +{ + struct image_sign_info info; + struct image_region regtmp[2]; + void *hash; + size_t size; + char c; + bool verified; + + debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__, + regs, ps_info, cert, cert->issuer, cert->subject); + + verified = false; + + memset(&info, '\0', sizeof(info)); + info.padding = image_get_padding_algo("pkcs-1.5"); + /* + * Note: image_get_[checksum|crypto]_algo takes an string + * argument like "," + * TODO: support other hash algorithms + */ + if (!strcmp(ps_info->sig->hash_algo, "sha1")) { + info.checksum = image_get_checksum_algo("sha1,rsa2048"); + info.name = "sha1,rsa2048"; + } else if (!strcmp(ps_info->sig->hash_algo, "sha256")) { + info.checksum = image_get_checksum_algo("sha256,rsa2048"); + info.name = "sha256,rsa2048"; + } else { + debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo); + goto out; + } + info.crypto = image_get_crypto_algo(info.name); + + info.key = cert->pub->key; + info.keylen = cert->pub->keylen; + + /* verify signature */ + debug("%s: crypto: %s, signature len:%x\n", __func__, + info.name, ps_info->sig->s_size); + if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) { + debug("%s: RSA verify authentication attribute\n", __func__); + /* + * NOTE: This path will be executed only for + * PE image authentication + */ + + /* check if hash matches digest first */ + debug("checking msg digest first, len:0x%x\n", + ps_info->msgdigest_len); + +#ifdef DEBUG + debug("hash in database:\n"); + print_hex_dump(" ", DUMP_PREFIX_OFFSET, 16, 1, + ps_info->msgdigest, ps_info->msgdigest_len, + false); +#endif + /* against contentInfo first */ + if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) || + /* for signed image */ + efi_hash_regions(regs, &hash, &size)) { + /* for authenticated variable */ + if (ps_info->msgdigest_len != size || + memcmp(hash, ps_info->msgdigest, size)) { + debug("Digest doesn't match\n"); + free(hash); + goto out; + } + + free(hash); + } else { + debug("Digesting image failed\n"); + goto out; + } + + /* against digest */ + c = 0x31; + regtmp[0].data = &c; + regtmp[0].size = 1; + regtmp[1].data = ps_info->authattrs; + regtmp[1].size = ps_info->authattrs_len; + + if (!rsa_verify(&info, regtmp, 2, + ps_info->sig->s, ps_info->sig->s_size)) + verified = true; + } else { + debug("%s: RSA verify content data\n", __func__); + /* against all data */ + if (!rsa_verify(&info, regs->reg, regs->num, + ps_info->sig->s, ps_info->sig->s_size)) + verified = true; + } + +out: + debug("%s: Exit, verified: %d\n", __func__, verified); + return verified; +} + +/** + * efi_signature_verify_with_list - verify a signature with signature list + * @regs: List of regions to be authenticated + * @msg: Signature + * @signed_info: Pointer to PKCS7's signed_info + * @siglist: Signature list for certificates + * @valid_cert: x509 certificate that verifies this signature + * + * Signature pointed to by @signed_info against image pointed to by @regs + * is verified by signature list pointed to by @siglist. + * Signature database is a simple concatenation of one or more + * signature list(s). + * + * Return: true if signature is verified, false if not + */ +static +bool efi_signature_verify_with_list(struct efi_image_regions *regs, + struct pkcs7_message *msg, + struct pkcs7_signed_info *signed_info, + struct efi_signature_store *siglist, + struct x509_certificate **valid_cert) +{ + struct x509_certificate *cert; + struct efi_sig_data *sig_data; + bool verified = false; + + debug("%s: Enter, %p, %p, %p, %p\n", __func__, + regs, signed_info, siglist, valid_cert); + + if (!signed_info) { + void *hash; + size_t size; + + debug("%s: unsigned image\n", __func__); + /* + * verify based on calculated hash value + * TODO: support other hash algorithms + */ + if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) { + debug("Digest algorithm is not supported: %pUl\n", + &siglist->sig_type); + goto out; + } + + if (!efi_hash_regions(regs, &hash, &size)) { + debug("Digesting unsigned image failed\n"); + goto out; + } + + /* go through the list */ + for (sig_data = siglist->sig_data_list; sig_data; + sig_data = sig_data->next) { +#ifdef DEBUG + debug("Msg digest in database:\n"); + print_hex_dump(" ", DUMP_PREFIX_OFFSET, 16, 1, + sig_data->data, sig_data->size, false); +#endif + if ((sig_data->size == size) && + !memcmp(sig_data->data, hash, size)) { + verified = true; + free(hash); + goto out; + } + } + free(hash); + goto out; + } + + debug("%s: signed image\n", __func__); + if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) { + debug("Signature type is not supported: %pUl\n", + &siglist->sig_type); + goto out; + } + + /* go through the list */ + for (sig_data = siglist->sig_data_list; sig_data; + sig_data = sig_data->next) { + /* TODO: support owner check based on policy */ + + cert = x509_cert_parse(sig_data->data, sig_data->size); + if (IS_ERR(cert)) { + debug("Parsing x509 certificate failed\n"); + goto out; + } + + verified = efi_signature_verify(regs, msg, signed_info, cert); + + if (verified) { + if (valid_cert) + *valid_cert = cert; + else + x509_free_certificate(cert); + break; + } + x509_free_certificate(cert); + } + +out: + debug("%s: Exit, verified: %d\n", __func__, verified); + return verified; +} + +/** + * efi_signature_verify_with_sigdb - verify a signature with db + * @regs: List of regions to be authenticated + * @msg: Signature + * @db: Signature database for trusted certificates + * @cert: x509 certificate that verifies this signature + * + * Signature pointed to by @msg against image pointed to by @regs + * is verified by signature database pointed to by @db. + * + * Return: true if signature is verified, false if not + */ +bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs, + struct pkcs7_message *msg, + struct efi_signature_store *db, + struct x509_certificate **cert) +{ + struct pkcs7_signed_info *info; + struct efi_signature_store *siglist; + bool verified = false; + + debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert); + + if (!db) + goto out; + + if (!db->sig_data_list) + goto out; + + /* for unsigned image */ + if (!msg) { + debug("%s: Verify unsigned image with db\n", __func__); + for (siglist = db; siglist; siglist = siglist->next) + if (efi_signature_verify_with_list(regs, NULL, NULL, + siglist, cert)) { + verified = true; + goto out; + } + + goto out; + } + + /* for signed image or variable */ + debug("%s: Verify signed image with db\n", __func__); + for (info = msg->signed_infos; info; info = info->next) { + debug("Signed Info: digest algo: %s, pkey algo: %s\n", + info->sig->hash_algo, info->sig->pkey_algo); + + for (siglist = db; siglist; siglist = siglist->next) { + if (efi_signature_verify_with_list(regs, msg, info, + siglist, cert)) { + verified = true; + goto out; + } + } + } + +out: + debug("%s: Exit, verified: %d\n", __func__, verified); + return verified; +} + +/** + * efi_search_siglist - search signature list for a certificate + * @cert: x509 certificate + * @siglist: Signature list + * @revoc_time: Pointer to buffer for revocation time + * + * Search signature list pointed to by @siglist and find a certificate + * pointed to by @cert. + * If found, revocation time that is specified in signature database is + * returned in @revoc_time. + * + * Return: true if certificate is found, false if not + */ +static bool efi_search_siglist(struct x509_certificate *cert, + struct efi_signature_store *siglist, + time64_t *revoc_time) +{ + struct image_region reg[1]; + void *hash = NULL, *msg = NULL; + struct efi_sig_data *sig_data; + bool found = false; + + /* can be null */ + if (!siglist->sig_data_list) + return false; + + if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) { + /* TODO: other hash algos */ + debug("Certificate's digest type is not supported: %pUl\n", + &siglist->sig_type); + goto out; + } + + /* calculate hash of TBSCertificate */ + msg = calloc(1, SHA256_SUM_LEN); + if (!msg) { + debug("Out of memory\n"); + goto out; + } + + hash = calloc(1, SHA256_SUM_LEN); + if (!hash) { + debug("Out of memory\n"); + goto out; + } + + reg[0].data = cert->tbs; + reg[0].size = cert->tbs_size; + hash_calculate("sha256", reg, 1, msg); + + /* go through signature list */ + for (sig_data = siglist->sig_data_list; sig_data; + sig_data = sig_data->next) { + /* + * struct efi_cert_x509_sha256 { + * u8 tbs_hash[256/8]; + * time64_t revocation_time; + * }; + */ + if ((sig_data->size == SHA256_SUM_LEN) && + !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) { + memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN, + sizeof(*revoc_time)); + found = true; + goto out; + } + } + +out: + free(hash); + free(msg); + + return found; +} + +/** + * efi_signature_verify_cert - verify a certificate with dbx + * @cert: x509 certificate + * @dbx: Signature database + * + * Search signature database pointed to by @dbx and find a certificate + * pointed to by @cert. + * This function is expected to be used against "dbx". + * + * Return: true if a certificate is not rejected, false otherwise. + */ +bool efi_signature_verify_cert(struct x509_certificate *cert, + struct efi_signature_store *dbx) +{ + struct efi_signature_store *siglist; + time64_t revoc_time; + bool found = false; + + debug("%s: Enter, %p, %p\n", __func__, dbx, cert); + + if (!cert) + return false; + + for (siglist = dbx; siglist; siglist = siglist->next) { + if (efi_search_siglist(cert, siglist, &revoc_time)) { + /* TODO */ + /* compare signing time with revocation time */ + + found = true; + break; + } + } + + debug("%s: Exit, verified: %d\n", __func__, !found); + return !found; +} + +/** + * efi_signature_verify_signers - verify signers' certificates with dbx + * @msg: Signature + * @dbx: Signature database + * + * Determine if any of signers' certificates in @msg may be verified + * by any of certificates in signature database pointed to by @dbx. + * This function is expected to be used against "dbx". + * + * Return: true if none of certificates is rejected, false otherwise. + */ +bool efi_signature_verify_signers(struct pkcs7_message *msg, + struct efi_signature_store *dbx) +{ + struct pkcs7_signed_info *info; + bool found = false; + + debug("%s: Enter, %p, %p\n", __func__, msg, dbx); + + if (!msg) + goto out; + + for (info = msg->signed_infos; info; info = info->next) { + if (info->signer && + !efi_signature_verify_cert(info->signer, dbx)) { + found = true; + goto out; + } + } +out: + debug("%s: Exit, verified: %d\n", __func__, !found); + return !found; +} + +/** + * efi_image_region_add - add an entry of region + * @regs: Pointer to array of regions + * @start: Start address of region + * @end: End address of region + * @nocheck: flag against overlapped regions + * + * Take one entry of region [@start, @end] and append it to the list + * pointed to by @regs. If @nocheck is false, overlapping among entries + * will be checked first. + * + * Return: 0 on success, status code (negative) on error + */ +efi_status_t efi_image_region_add(struct efi_image_regions *regs, + const void *start, const void *end, + int nocheck) +{ + struct image_region *reg; + int i, j; + + if (regs->num >= regs->max) { + debug("%s: no more room for regions\n", __func__); + return EFI_OUT_OF_RESOURCES; + } + + if (end < start) + return EFI_INVALID_PARAMETER; + + for (i = 0; i < regs->num; i++) { + reg = ®s->reg[i]; + if (nocheck) + continue; + + if (start > reg->data + reg->size) + continue; + + if ((start >= reg->data && start < reg->data + reg->size) || + (end > reg->data && end < reg->data + reg->size)) { + debug("%s: new region already part of another\n", + __func__); + return EFI_INVALID_PARAMETER; + } + + if (start < reg->data && end < reg->data + reg->size) { + for (j = regs->num - 1; j >= i; j--) + memcpy(®s->reg[j], ®s->reg[j + 1], + sizeof(*reg)); + break; + } + } + + reg = ®s->reg[i]; + reg->data = start; + reg->size = end - start; + regs->num++; + + return EFI_SUCCESS; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ From patchwork Tue Apr 14 02:51:40 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270031 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=pm9hnO3R; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VQw39jqz9s71 for ; Tue, 14 Apr 2020 12:52:55 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id E290C818C7; Tue, 14 Apr 2020 04:52:44 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="pm9hnO3R"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 6FB4D81834; Tue, 14 Apr 2020 04:52:37 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pg1-x52b.google.com (mail-pg1-x52b.google.com [IPv6:2607:f8b0:4864:20::52b]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 1E1E281469 for ; Tue, 14 Apr 2020 04:52:29 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pg1-x52b.google.com with SMTP id c23so5384491pgj.3 for ; Mon, 13 Apr 2020 19:52:29 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=XkZt5hv1jMPGwWLfqd0O7MdVnni8G0pb5gEcyJ9VkvQ=; b=pm9hnO3ReDeRlNTpL4Zx9N9zwhu+LNahtuOrE6gvPlkPEmA059Jm1LaHs3cFrL+1I7 gs1RK7b+7O7/jbPwRmhWuXKs88qaLz8E2zD0XpvPAx+DGyClDayE/+eDs+RD2woirNPn pi+tloQajYYzp92gMz0N7bn4lFS4EJWSw4C0aWfPeubkR8bA+A1JO09LDk/M3HyroUXk o9EIU7wkAW8SlRn8C945Me3uUidufTwDgdUTHfEruMZLLPncgbnDutDt7w+4iyAlodXU yDbNcWhq87zX2x1rRjZf0WsYEDNn8+BcftAVHARPfUj6sHnHRL6aLZ4yLvV8MaHLSwB/ wHSg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=XkZt5hv1jMPGwWLfqd0O7MdVnni8G0pb5gEcyJ9VkvQ=; b=fBgB4THdMB5jpX4YAL90s9G1h5pOuYUcF5H14XW5ubaSY2Jq5fgZ0XI8IXlffmzmyC xUVwH5AM8ko7NAsTZeW4W+tyzdUabbVpwQmubcUwAKbQLum3KxRx3oJO52mbyrVi+36D a+QH/n5oOvoM8/j7/33ZCEfHjqG2djwMHXSW8w0NEDluSaKS/Fjp2Ie4TkRUcx+Veb+v 4wW3718UrVKRSPaLaqvgUUD85HcUT7o02SbyknI1e5F14AEqOAdTwmNb2GXYll6SsTBw mdPc+nnJFZc6LJ5rcZf8b+jo8wcSfIGKtYvB2IbVqGeDvoGElH5q+Mlgu4BWI5145mu+ dZ7A== X-Gm-Message-State: AGi0PubOl/vyA0zVZF3BXwP8xk1T7T0qFZOD1YzTqWQbiHANSvt9FeT8 U8MQ4Oyk07QtRMhv2WD7ehsRPQ== X-Google-Smtp-Source: APiQypJpMPu470t63WSsHze84UIo/P6p98J2Th7YF6GNxt/azdaOCLa5ge871V3/mFsUndqbcbgafQ== X-Received: by 2002:a63:2347:: with SMTP id u7mr9260731pgm.183.1586832747538; Mon, 13 Apr 2020 19:52:27 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.24 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:26 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 03/17] efi_loader: add signature database parser Date: Tue, 14 Apr 2020 11:51:40 +0900 Message-Id: <20200414025154.27283-4-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean efi_signature_parse_sigdb() is a helper function will be used to parse signature database variable and instantiate a signature store structure in later patches. Signed-off-by: AKASHI Takahiro --- include/efi_loader.h | 3 + lib/efi_loader/efi_signature.c | 226 +++++++++++++++++++++++++++++++++ 2 files changed, 229 insertions(+) diff --git a/include/efi_loader.h b/include/efi_loader.h index 8cf85d2fb7e2..fea2ead02e93 100644 --- a/include/efi_loader.h +++ b/include/efi_loader.h @@ -750,6 +750,9 @@ bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs, efi_status_t efi_image_region_add(struct efi_image_regions *regs, const void *start, const void *end, int nocheck); + +void efi_sigstore_free(struct efi_signature_store *sigstore); +struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name); #endif /* CONFIG_EFI_SECURE_BOOT */ #else /* CONFIG_IS_ENABLED(EFI_LOADER) */ diff --git a/lib/efi_loader/efi_signature.c b/lib/efi_loader/efi_signature.c index 23dac94c0593..2d1f38980e5f 100644 --- a/lib/efi_loader/efi_signature.c +++ b/lib/efi_loader/efi_signature.c @@ -580,4 +580,230 @@ efi_status_t efi_image_region_add(struct efi_image_regions *regs, return EFI_SUCCESS; } + +/** + * efi_sigstore_free - free signature store + * @sigstore: Pointer to signature store structure + * + * Feee all the memories held in signature store and itself, + * which were allocated by efi_sigstore_parse_sigdb(). + */ +void efi_sigstore_free(struct efi_signature_store *sigstore) +{ + struct efi_signature_store *sigstore_next; + struct efi_sig_data *sig_data, *sig_data_next; + + while (sigstore) { + sigstore_next = sigstore->next; + + sig_data = sigstore->sig_data_list; + while (sig_data) { + sig_data_next = sig_data->next; + free(sig_data->data); + free(sig_data); + sig_data = sig_data_next; + } + + free(sigstore); + sigstore = sigstore_next; + } +} + +/** + * efi_sigstore_parse_siglist - parse a signature list + * @name: Pointer to signature list + * + * Parse signature list and instantiate a signature store structure. + * Signature database is a simple concatenation of one or more + * signature list(s). + * + * Return: Pointer to signature store on success, NULL on error + */ +static struct efi_signature_store * +efi_sigstore_parse_siglist(struct efi_signature_list *esl) +{ + struct efi_signature_store *siglist = NULL; + struct efi_sig_data *sig_data, *sig_data_next; + struct efi_signature_data *esd; + size_t left; + + /* + * UEFI specification defines certificate types: + * for non-signed images, + * EFI_CERT_SHA256_GUID + * EFI_CERT_RSA2048_GUID + * EFI_CERT_RSA2048_SHA256_GUID + * EFI_CERT_SHA1_GUID + * EFI_CERT_RSA2048_SHA_GUID + * EFI_CERT_SHA224_GUID + * EFI_CERT_SHA384_GUID + * EFI_CERT_SHA512_GUID + * + * for signed images, + * EFI_CERT_X509_GUID + * NOTE: Each certificate will normally be in a separate + * EFI_SIGNATURE_LIST as the size may vary depending on + * its algo's. + * + * for timestamp revocation of certificate, + * EFI_CERT_X509_SHA512_GUID + * EFI_CERT_X509_SHA256_GUID + * EFI_CERT_X509_SHA384_GUID + */ + + if (esl->signature_list_size + <= (sizeof(*esl) + esl->signature_header_size)) { + debug("Siglist in wrong format\n"); + return NULL; + } + + /* Create a head */ + siglist = calloc(sizeof(*siglist), 1); + if (!siglist) { + debug("Out of memory\n"); + goto err; + } + memcpy(&siglist->sig_type, &esl->signature_type, sizeof(efi_guid_t)); + + /* Go through the list */ + sig_data_next = NULL; + left = esl->signature_list_size + - (sizeof(*esl) + esl->signature_header_size); + esd = (struct efi_signature_data *) + ((u8 *)esl + sizeof(*esl) + esl->signature_header_size); + + while ((left > 0) && left >= esl->signature_size) { + /* Signature must exist if there is remaining data. */ + if (left < esl->signature_size) { + debug("Certificate is too small\n"); + goto err; + } + + sig_data = calloc(esl->signature_size + - sizeof(esd->signature_owner), 1); + if (!sig_data) { + debug("Out of memory\n"); + goto err; + } + + /* Append signature data */ + memcpy(&sig_data->owner, &esd->signature_owner, + sizeof(efi_guid_t)); + sig_data->size = esl->signature_size + - sizeof(esd->signature_owner); + sig_data->data = malloc(sig_data->size); + if (!sig_data->data) { + debug("Out of memory\n"); + goto err; + } + memcpy(sig_data->data, esd->signature_data, sig_data->size); + + sig_data->next = sig_data_next; + sig_data_next = sig_data; + + /* Next */ + esd = (struct efi_signature_data *) + ((u8 *)esd + esl->signature_size); + left -= esl->signature_size; + } + siglist->sig_data_list = sig_data_next; + + return siglist; + +err: + efi_sigstore_free(siglist); + + return NULL; +} + +/** + * efi_sigstore_parse_sigdb - parse a signature database variable + * @name: Variable's name + * + * Read in a value of signature database variable pointed to by + * @name, parse it and instantiate a signature store structure. + * + * Return: Pointer to signature store on success, NULL on error + */ +struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name) +{ + struct efi_signature_store *sigstore = NULL, *siglist; + struct efi_signature_list *esl; + const efi_guid_t *vendor; + void *db; + efi_uintn_t db_size; + efi_status_t ret; + + if (!u16_strcmp(name, L"PK") || !u16_strcmp(name, L"KEK")) { + vendor = &efi_global_variable_guid; + } else if (!u16_strcmp(name, L"db") || !u16_strcmp(name, L"dbx")) { + vendor = &efi_guid_image_security_database; + } else { + debug("unknown signature database, %ls\n", name); + return NULL; + } + + /* retrieve variable data */ + db_size = 0; + ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, NULL)); + if (ret == EFI_NOT_FOUND) { + debug("variable, %ls, not found\n", name); + sigstore = calloc(sizeof(*sigstore), 1); + return sigstore; + } else if (ret != EFI_BUFFER_TOO_SMALL) { + debug("Getting variable, %ls, failed\n", name); + return NULL; + } + + db = malloc(db_size); + if (!db) { + debug("Out of memory\n"); + return NULL; + } + + ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, db)); + if (ret != EFI_SUCCESS) { + debug("Getting variable, %ls, failed\n", name); + goto err; + } + + /* Parse siglist list */ + esl = db; + while (db_size > 0) { + /* List must exist if there is remaining data. */ + if (db_size < sizeof(*esl)) { + debug("variable, %ls, in wrong format\n", name); + goto err; + } + + if (db_size < esl->signature_list_size) { + debug("variable, %ls, in wrong format\n", name); + goto err; + } + + /* Parse a single siglist. */ + siglist = efi_sigstore_parse_siglist(esl); + if (!siglist) { + debug("Parsing signature list of %ls failed\n", name); + goto err; + } + + /* Append siglist */ + siglist->next = sigstore; + sigstore = siglist; + + /* Next */ + db_size -= esl->signature_list_size; + esl = (void *)esl + esl->signature_list_size; + } + free(db); + + return sigstore; + +err: + efi_sigstore_free(sigstore); + free(db); + + return NULL; +} #endif /* CONFIG_EFI_SECURE_BOOT */ From patchwork Tue Apr 14 02:51:41 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270035 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=Z2qQczB9; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VRt5zhTz9sPF for ; Tue, 14 Apr 2020 12:53:46 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 58AB4818F3; Tue, 14 Apr 2020 04:53:27 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="Z2qQczB9"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 54A4C818E7; Tue, 14 Apr 2020 04:52:57 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pf1-x42b.google.com (mail-pf1-x42b.google.com [IPv6:2607:f8b0:4864:20::42b]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 68DC58180B for ; Tue, 14 Apr 2020 04:52:33 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pf1-x42b.google.com with SMTP id x3so5177399pfp.7 for ; Mon, 13 Apr 2020 19:52:33 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=q52d626ampZZnMrHtEgGlZA3QYI2S/IvHzfsFO28u8U=; b=Z2qQczB9s37kKx3oJ3Ew4Q34qbYKxipcSBz3nOTXi2gF2kXjTJ8imLRmAFU9YH3a0G Tt3L+M6cbWc8gIHo0fDkIBQ1bZi0Jcca8CnZUeyoRF1WzjDvAzLntggylpn43wfnJKyW rUk9uEKcivEpY9E43wbtOJwl03Jl8ByfBVCqOHePUprGWkGC/VsTCDd1j2pZwMzOmwhc MihIYh2N8+sDxojFdjbUrvYiHffJfauYqWtBEpDpzZqy38aWRxp/hj+TT4JJSW7keWur Xd15Y5rzLowmzqprxh/XFmMLFqbU9Sq3st+OUORXPbGqDGIir8JjdJ24gFxVnm155G73 oGNA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=q52d626ampZZnMrHtEgGlZA3QYI2S/IvHzfsFO28u8U=; b=c79l8xfuKv7hYCbJqFjuvDIKCu8UQn5SuVveJOhE5D2/M/AVuU2eIkgj9EAMdVyvj8 z2tayXleon3w/EVxCTZe9Mp0zDEwpof0BumW9xQ7R0tZtc1EB8GIQuYxqBnraLXV7iki 9zon05qHXjODPle4i7w6U59jCZBhjC/egda5CNn3vK/ZJeedPZo5AhPAsP80zRdBknvA ZOnAPn26qbXAEcWnhkV01mCJYsTg759Wz/tIA+Wk1tJRgHEMxdbps40nbyA+kxO1k+Gt W48K7rNk1DFNPlUSvrd3jMgpmaA10FuOYURih1FvzHYHFXWkDZ6hlwvhd3p5SrCsklh3 Yehg== X-Gm-Message-State: AGi0PuaOGqM+FwO3VM/8ZwMrBuODU1FRsD53zHwEpUwbHK40wAQV9Mn8 uZMtkAuwkTcOv322v6QRyyAqTA== X-Google-Smtp-Source: APiQypJGdxFS1U9h/1J35kS0ZBkNekMkDIjUSS9X+dDgEIBDjHyTE/BeFUwry12KoKNP/dQUf9eOxQ== X-Received: by 2002:a62:160b:: with SMTP id 11mr21723257pfw.189.1586832751589; Mon, 13 Apr 2020 19:52:31 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.27 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:30 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 04/17] efi_loader: variable: support variable authentication Date: Tue, 14 Apr 2020 11:51:41 +0900 Message-Id: <20200414025154.27283-5-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean With this commit, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes. Internally, authentication data is stored as part of authenticated variable's value. It is nothing but a pkcs7 message (but we need some wrapper, see efi_variable_parse_signature()) and will be validated by efi_variable_authenticate(), hence efi_signature_verify_with_db(). Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes. Signed-off-by: AKASHI Takahiro --- include/efi_loader.h | 3 + lib/efi_loader/efi_variable.c | 666 ++++++++++++++++++++++++++++------ 2 files changed, 565 insertions(+), 104 deletions(-) diff --git a/include/efi_loader.h b/include/efi_loader.h index fea2ead02e93..ef8d184a6ee7 100644 --- a/include/efi_loader.h +++ b/include/efi_loader.h @@ -184,6 +184,7 @@ extern const efi_guid_t efi_guid_image_security_database; extern const efi_guid_t efi_guid_sha256; extern const efi_guid_t efi_guid_cert_x509; extern const efi_guid_t efi_guid_cert_x509_sha256; +extern const efi_guid_t efi_guid_cert_type_pkcs7; /* GUID of RNG protocol */ extern const efi_guid_t efi_guid_rng_protocol; @@ -753,6 +754,8 @@ efi_status_t efi_image_region_add(struct efi_image_regions *regs, void efi_sigstore_free(struct efi_signature_store *sigstore); struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name); + +bool efi_secure_boot_enabled(void); #endif /* CONFIG_EFI_SECURE_BOOT */ #else /* CONFIG_IS_ENABLED(EFI_LOADER) */ diff --git a/lib/efi_loader/efi_variable.c b/lib/efi_loader/efi_variable.c index fe2f26459136..adb78470f2d6 100644 --- a/lib/efi_loader/efi_variable.c +++ b/lib/efi_loader/efi_variable.c @@ -10,8 +10,14 @@ #include #include #include +#include #include +#include #include +#include "../lib/crypto/pkcs7_parser.h" + +const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID; +static bool efi_secure_boot; #define READ_ONLY BIT(31) @@ -106,9 +112,10 @@ static const char *prefix(const char *str, const char *prefix) * * @str: value of U-Boot variable * @attrp: pointer to UEFI attributes + * @timep: pointer to time attribute * Return: pointer to remainder of U-Boot variable value */ -static const char *parse_attr(const char *str, u32 *attrp) +static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) { u32 attr = 0; char sep = '{'; @@ -131,6 +138,12 @@ static const char *parse_attr(const char *str, u32 *attrp) attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS; } else if ((s = prefix(str, "run"))) { attr |= EFI_VARIABLE_RUNTIME_ACCESS; + } else if ((s = prefix(str, "time="))) { + attr |= EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS; + hex2bin((u8 *)timep, s, sizeof(*timep)); + s += sizeof(*timep) * 2; + } else if (*str == '}') { + break; } else { printf("invalid attribute: %s\n", str); break; @@ -148,48 +161,291 @@ static const char *parse_attr(const char *str, u32 *attrp) } /** - * efi_get_variable() - retrieve value of a UEFI variable + * efi_secure_boot_enabled - return if secure boot is enabled or not * - * This function implements the GetVariable runtime service. + * Return: true if enabled, false if disabled + */ +bool efi_secure_boot_enabled(void) +{ + return efi_secure_boot; +} + +#ifdef CONFIG_EFI_SECURE_BOOT +static u8 pkcs7_hdr[] = { + /* SEQUENCE */ + 0x30, 0x82, 0x05, 0xc7, + /* OID: pkcs7-signedData */ + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, + /* Context Structured? */ + 0xa0, 0x82, 0x05, 0xb8, +}; + +/** + * efi_variable_parse_signature - parse a signature in variable + * @buf: Pointer to variable's value + * @buflen: Length of @buf * - * See the Unified Extensible Firmware Interface (UEFI) specification for - * details. + * Parse a signature embedded in variable's value and instantiate + * a pkcs7_message structure. Since pkcs7_parse_message() accepts only + * pkcs7's signedData, some header needed be prepended for correctly + * parsing authentication data, particularly for variable's. * - * @variable_name: name of the variable - * @vendor: vendor GUID - * @attributes: attributes of the variable - * @data_size: size of the buffer to which the variable value is copied - * @data: buffer to which the variable value is copied - * Return: status code + * Return: Pointer to pkcs7_message structure on success, NULL on error */ -efi_status_t EFIAPI efi_get_variable(u16 *variable_name, - const efi_guid_t *vendor, u32 *attributes, - efi_uintn_t *data_size, void *data) +static struct pkcs7_message *efi_variable_parse_signature(const void *buf, + size_t buflen) +{ + u8 *ebuf; + size_t ebuflen, len; + struct pkcs7_message *msg; + + /* + * This is the best assumption to check if the binary is + * already in a form of pkcs7's signedData. + */ + if (buflen > sizeof(pkcs7_hdr) && + !memcmp(&((u8 *)buf)[4], &pkcs7_hdr[4], 11)) { + msg = pkcs7_parse_message(buf, buflen); + goto out; + } + + /* + * Otherwise, we should add a dummy prefix sequence for pkcs7 + * message parser to be able to process. + * NOTE: EDK2 also uses similar hack in WrapPkcs7Data() + * in CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c + * TODO: + * The header should be composed in a more refined manner. + */ + debug("Makeshift prefix added to authentication data\n"); + ebuflen = sizeof(pkcs7_hdr) + buflen; + if (ebuflen <= 0x7f) { + debug("Data is too short\n"); + return NULL; + } + + ebuf = malloc(ebuflen); + if (!ebuf) { + debug("Out of memory\n"); + return NULL; + } + + memcpy(ebuf, pkcs7_hdr, sizeof(pkcs7_hdr)); + memcpy(ebuf + sizeof(pkcs7_hdr), buf, buflen); + len = ebuflen - 4; + ebuf[2] = (len >> 8) & 0xff; + ebuf[3] = len & 0xff; + len = ebuflen - 0x13; + ebuf[0x11] = (len >> 8) & 0xff; + ebuf[0x12] = len & 0xff; + + msg = pkcs7_parse_message(ebuf, ebuflen); + + free(ebuf); + +out: + if (IS_ERR(msg)) + return NULL; + + return msg; +} + +/** + * efi_variable_authenticate - authenticate a variable + * @variable: Variable name in u16 + * @vendor: Guid of variable + * @data_size: Size of @data + * @data: Pointer to variable's value + * @given_attr: Attributes to be given at SetVariable() + * @env_attr: Attributes that an existing variable holds + * @time: signed time that an existing variable holds + * + * Called by efi_set_variable() to verify that the input is correct. + * Will replace the given data pointer with another that points to + * the actual data to store in the internal memory. + * On success, @data and @data_size will be replaced with variable's + * actual data, excluding authentication data, and its size, and variable's + * attributes and signed time will also be returned in @env_attr and @time, + * respectively. + * + * Return: EFI_SUCCESS on success, status code (negative) on error + */ +static efi_status_t efi_variable_authenticate(u16 *variable, + const efi_guid_t *vendor, + efi_uintn_t *data_size, + const void **data, u32 given_attr, + u32 *env_attr, u64 *time) +{ + const struct efi_variable_authentication_2 *auth; + struct efi_signature_store *truststore, *truststore2; + struct pkcs7_message *var_sig; + struct efi_image_regions *regs; + struct efi_time timestamp; + struct rtc_time tm; + u64 new_time; + efi_status_t ret; + + var_sig = NULL; + truststore = NULL; + truststore2 = NULL; + regs = NULL; + ret = EFI_SECURITY_VIOLATION; + + if (*data_size < sizeof(struct efi_variable_authentication_2)) + goto err; + + /* authentication data */ + auth = *data; + if (*data_size < (sizeof(auth->time_stamp) + + auth->auth_info.hdr.dwLength)) + goto err; + + if (guidcmp(&auth->auth_info.cert_type, &efi_guid_cert_type_pkcs7)) + goto err; + + *data += sizeof(auth->time_stamp) + auth->auth_info.hdr.dwLength; + *data_size -= (sizeof(auth->time_stamp) + + auth->auth_info.hdr.dwLength); + + memcpy(×tamp, &auth->time_stamp, sizeof(timestamp)); + memset(&tm, 0, sizeof(tm)); + tm.tm_year = timestamp.year; + tm.tm_mon = timestamp.month; + tm.tm_mday = timestamp.day; + tm.tm_hour = timestamp.hour; + tm.tm_min = timestamp.minute; + tm.tm_sec = timestamp.second; + new_time = rtc_mktime(&tm); + + if (!efi_secure_boot_enabled()) { + /* finished checking */ + *time = new_time; + return EFI_SUCCESS; + } + + if (new_time <= *time) + goto err; + + /* data to be digested */ + regs = calloc(sizeof(*regs) + sizeof(struct image_region) * 5, 1); + if (!regs) + goto err; + regs->max = 5; + efi_image_region_add(regs, (uint8_t *)variable, + (uint8_t *)variable + + u16_strlen(variable) * sizeof(u16), 1); + efi_image_region_add(regs, (uint8_t *)vendor, + (uint8_t *)vendor + sizeof(*vendor), 1); + efi_image_region_add(regs, (uint8_t *)&given_attr, + (uint8_t *)&given_attr + sizeof(given_attr), 1); + efi_image_region_add(regs, (uint8_t *)×tamp, + (uint8_t *)×tamp + sizeof(timestamp), 1); + efi_image_region_add(regs, (uint8_t *)*data, + (uint8_t *)*data + *data_size, 1); + + /* variable's signature list */ + if (auth->auth_info.hdr.dwLength < sizeof(auth->auth_info)) + goto err; + var_sig = efi_variable_parse_signature(auth->auth_info.cert_data, + auth->auth_info.hdr.dwLength + - sizeof(auth->auth_info)); + if (IS_ERR(var_sig)) { + debug("Parsing variable's signature failed\n"); + var_sig = NULL; + goto err; + } + + /* signature database used for authentication */ + if (u16_strcmp(variable, L"PK") == 0 || + u16_strcmp(variable, L"KEK") == 0) { + /* with PK */ + truststore = efi_sigstore_parse_sigdb(L"PK"); + if (!truststore) + goto err; + } else if (u16_strcmp(variable, L"db") == 0 || + u16_strcmp(variable, L"dbx") == 0) { + /* with PK and KEK */ + truststore = efi_sigstore_parse_sigdb(L"KEK"); + truststore2 = efi_sigstore_parse_sigdb(L"PK"); + + if (!truststore) { + if (!truststore2) + goto err; + + truststore = truststore2; + truststore2 = NULL; + } + } else { + /* TODO: support private authenticated variables */ + goto err; + } + + /* verify signature */ + if (efi_signature_verify_with_sigdb(regs, var_sig, truststore, NULL)) { + debug("Verified\n"); + } else { + if (truststore2 && + efi_signature_verify_with_sigdb(regs, var_sig, + truststore2, NULL)) { + debug("Verified\n"); + } else { + debug("Verifying variable's signature failed\n"); + goto err; + } + } + + /* finished checking */ + *time = rtc_mktime(&tm); + ret = EFI_SUCCESS; + +err: + efi_sigstore_free(truststore); + efi_sigstore_free(truststore2); + pkcs7_free_message(var_sig); + free(regs); + + return ret; +} +#else +static efi_status_t efi_variable_authenticate(u16 *variable, + const efi_guid_t *vendor, + efi_uintn_t *data_size, + const void **data, u32 given_attr, + u32 *env_attr, u64 *time) +{ + return EFI_SUCCESS; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ + +static +efi_status_t EFIAPI efi_get_variable_common(u16 *variable_name, + const efi_guid_t *vendor, + u32 *attributes, + efi_uintn_t *data_size, void *data, + bool is_non_volatile) { char *native_name; efi_status_t ret; unsigned long in_size; - const char *val, *s; + const char *val = NULL, *s; + u64 time = 0; u32 attr; - EFI_ENTRY("\"%ls\" %pUl %p %p %p", variable_name, vendor, attributes, - data_size, data); - if (!variable_name || !vendor || !data_size) return EFI_EXIT(EFI_INVALID_PARAMETER); ret = efi_to_native(&native_name, variable_name, vendor); if (ret) - return EFI_EXIT(ret); + return ret; EFI_PRINT("get '%s'\n", native_name); val = env_get(native_name); free(native_name); if (!val) - return EFI_EXIT(EFI_NOT_FOUND); + return EFI_NOT_FOUND; - val = parse_attr(val, &attr); + val = parse_attr(val, &attr, &time); in_size = *data_size; @@ -198,7 +454,7 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, /* number of hexadecimal digits must be even */ if (len & 1) - return EFI_EXIT(EFI_DEVICE_ERROR); + return EFI_DEVICE_ERROR; /* two characters per byte: */ len /= 2; @@ -209,11 +465,13 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } - if (!data) - return EFI_EXIT(EFI_INVALID_PARAMETER); + if (!data) { + debug("Variable with no data shouldn't exist.\n"); + return EFI_INVALID_PARAMETER; + } if (hex2bin(data, s, len)) - return EFI_EXIT(EFI_DEVICE_ERROR); + return EFI_DEVICE_ERROR; EFI_PRINT("got value: \"%s\"\n", s); } else if ((s = prefix(val, "(utf8)"))) { @@ -226,8 +484,10 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } - if (!data) - return EFI_EXIT(EFI_INVALID_PARAMETER); + if (!data) { + debug("Variable with no data shouldn't exist.\n"); + return EFI_INVALID_PARAMETER; + } memcpy(data, s, len); ((char *)data)[len] = '\0'; @@ -235,13 +495,67 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, EFI_PRINT("got value: \"%s\"\n", (char *)data); } else { EFI_PRINT("invalid value: '%s'\n", val); - return EFI_EXIT(EFI_DEVICE_ERROR); + return EFI_DEVICE_ERROR; } out: if (attributes) *attributes = attr & EFI_VARIABLE_MASK; + return ret; +} + +static +efi_status_t EFIAPI efi_get_volatile_variable(u16 *variable_name, + const efi_guid_t *vendor, + u32 *attributes, + efi_uintn_t *data_size, + void *data) +{ + return efi_get_variable_common(variable_name, vendor, attributes, + data_size, data, false); +} + +efi_status_t EFIAPI efi_get_nonvolatile_variable(u16 *variable_name, + const efi_guid_t *vendor, + u32 *attributes, + efi_uintn_t *data_size, + void *data) +{ + return efi_get_variable_common(variable_name, vendor, attributes, + data_size, data, true); +} + +/** + * efi_efi_get_variable() - retrieve value of a UEFI variable + * + * This function implements the GetVariable runtime service. + * + * See the Unified Extensible Firmware Interface (UEFI) specification for + * details. + * + * @variable_name: name of the variable + * @vendor: vendor GUID + * @attributes: attributes of the variable + * @data_size: size of the buffer to which the variable value is copied + * @data: buffer to which the variable value is copied + * Return: status code + */ +efi_status_t EFIAPI efi_get_variable(u16 *variable_name, + const efi_guid_t *vendor, u32 *attributes, + efi_uintn_t *data_size, void *data) +{ + efi_status_t ret; + + EFI_ENTRY("\"%ls\" %pUl %p %p %p", variable_name, vendor, attributes, + data_size, data); + + ret = efi_get_volatile_variable(variable_name, vendor, attributes, + data_size, data); + if (ret == EFI_NOT_FOUND) + ret = efi_get_nonvolatile_variable(variable_name, vendor, + attributes, data_size, data); + return EFI_EXIT(ret); } @@ -275,6 +589,7 @@ static efi_status_t parse_uboot_variable(char *variable, char *guid, *name, *end, c; size_t name_len; efi_uintn_t old_variable_name_size; + u64 time; u16 *p; guid = strchr(variable, '_'); @@ -309,7 +624,7 @@ static efi_status_t parse_uboot_variable(char *variable, *(name - 1) = c; /* attributes */ - parse_attr(end, attributes); + parse_attr(end, attributes, &time); return EFI_SUCCESS; } @@ -391,7 +706,7 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size, list_len = hexport_r(&env_htab, '\n', H_MATCH_REGEX | H_MATCH_KEY, &efi_variables_list, 0, 1, regexlist); - /* 1 indicates that no match was found */ + if (list_len <= 1) return EFI_EXIT(EFI_NOT_FOUND); @@ -404,143 +719,286 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size, return EFI_EXIT(ret); } -/** - * efi_set_variable() - set value of a UEFI variable - * - * This function implements the SetVariable runtime service. - * - * See the Unified Extensible Firmware Interface (UEFI) specification for - * details. - * - * @variable_name: name of the variable - * @vendor: vendor GUID - * @attributes: attributes of the variable - * @data_size: size of the buffer with the variable value - * @data: buffer with the variable value - * Return: status code - */ -efi_status_t EFIAPI efi_set_variable(u16 *variable_name, - const efi_guid_t *vendor, u32 attributes, - efi_uintn_t data_size, const void *data) +static +efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name, + const efi_guid_t *vendor, + u32 attributes, + efi_uintn_t data_size, + const void *data, + bool ro_check, + bool is_non_volatile) { - char *native_name = NULL, *val = NULL, *s; - const char *old_val; - size_t old_size; - efi_status_t ret = EFI_SUCCESS; + char *native_name = NULL, *old_data = NULL, *val = NULL, *s; + efi_uintn_t old_size; + bool append, delete; + u64 time = 0; u32 attr; + efi_status_t ret = EFI_SUCCESS; - EFI_ENTRY("\"%ls\" %pUl %x %zu %p", variable_name, vendor, attributes, - data_size, data); + debug("%s: set '%s'\n", __func__, native_name); if (!variable_name || !*variable_name || !vendor || ((attributes & EFI_VARIABLE_RUNTIME_ACCESS) && !(attributes & EFI_VARIABLE_BOOTSERVICE_ACCESS))) { ret = EFI_INVALID_PARAMETER; - goto out; + goto err; } ret = efi_to_native(&native_name, variable_name, vendor); if (ret) - goto out; + goto err; + + /* check if a variable exists */ + old_size = 0; + attr = 0; + ret = EFI_CALL(efi_get_variable(variable_name, vendor, &attr, + &old_size, NULL)); + if (ret == EFI_BUFFER_TOO_SMALL) { + if ((is_non_volatile && !(attr & EFI_VARIABLE_NON_VOLATILE)) || + (!is_non_volatile && (attr & EFI_VARIABLE_NON_VOLATILE))) { + ret = EFI_INVALID_PARAMETER; + goto err; + } + } - old_val = env_get(native_name); - if (old_val) { - old_val = parse_attr(old_val, &attr); + append = !!(attributes & EFI_VARIABLE_APPEND_WRITE); + attributes &= ~(u32)EFI_VARIABLE_APPEND_WRITE; + delete = !append && (!data_size || !attributes); - /* check read-only first */ - if (attr & READ_ONLY) { + /* check attributes */ + if (old_size) { + if (ro_check && (attr & READ_ONLY)) { ret = EFI_WRITE_PROTECTED; - goto out; - } - - if ((data_size == 0 && - !(attributes & EFI_VARIABLE_APPEND_WRITE)) || - !attributes) { - /* delete the variable: */ - env_set(native_name, NULL); - ret = EFI_SUCCESS; - goto out; + goto err; } /* attributes won't be changed */ - if (attr != (attributes & ~EFI_VARIABLE_APPEND_WRITE)) { + if (!delete && + ((ro_check && attr != attributes) || + (!ro_check && ((attr & ~(u32)READ_ONLY) + != (attributes & ~(u32)READ_ONLY))))) { ret = EFI_INVALID_PARAMETER; - goto out; - } - - if (attributes & EFI_VARIABLE_APPEND_WRITE) { - if (!prefix(old_val, "(blob)")) { - ret = EFI_DEVICE_ERROR; - goto out; - } - old_size = strlen(old_val); - } else { - old_size = 0; + goto err; } } else { - if (data_size == 0 || !attributes || - (attributes & EFI_VARIABLE_APPEND_WRITE)) { + if (delete || append) { /* * Trying to delete or to update a non-existent * variable. */ ret = EFI_NOT_FOUND; - goto out; + goto err; + } + } + + if (((!u16_strcmp(variable_name, L"PK") || + !u16_strcmp(variable_name, L"KEK")) && + !guidcmp(vendor, &efi_global_variable_guid)) || + ((!u16_strcmp(variable_name, L"db") || + !u16_strcmp(variable_name, L"dbx")) && + !guidcmp(vendor, &efi_guid_image_security_database))) { + /* authentication is mandatory */ + if (!(attributes & + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) { + debug("%ls: AUTHENTICATED_WRITE_ACCESS required\n", + variable_name); + ret = EFI_INVALID_PARAMETER; + goto err; } + } + + /* authenticate a variable */ + if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) { + if (attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) { + ret = EFI_INVALID_PARAMETER; + goto err; + } + if (attributes & + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) { + ret = efi_variable_authenticate(variable_name, vendor, + &data_size, &data, + attributes, &attr, + &time); + if (ret != EFI_SUCCESS) + goto err; + + /* last chance to check for delete */ + if (!data_size) + delete = true; + } + } else { + if (attributes & + (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)) { + debug("Secure boot is not configured\n"); + ret = EFI_INVALID_PARAMETER; + goto err; + } + } + + /* delete a variable */ + if (delete) { + /* !old_size case has been handled before */ + val = NULL; + ret = EFI_SUCCESS; + goto out; + } + if (append) { + old_data = malloc(old_size); + if (!old_data) { + return EFI_OUT_OF_RESOURCES; + goto err; + } + ret = EFI_CALL(efi_get_variable(variable_name, vendor, + &attr, &old_size, old_data)); + if (ret != EFI_SUCCESS) + goto err; + } else { old_size = 0; } - val = malloc(old_size + 2 * data_size - + strlen("{ro,run,boot,nv}(blob)") + 1); + val = malloc(2 * old_size + 2 * data_size + + strlen("{ro,run,boot,nv,time=0123456701234567}(blob)") + + 1); if (!val) { ret = EFI_OUT_OF_RESOURCES; - goto out; + goto err; } s = val; - /* store attributes */ - attributes &= (EFI_VARIABLE_NON_VOLATILE | + /* + * store attributes + */ + attributes &= (READ_ONLY | + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | - EFI_VARIABLE_RUNTIME_ACCESS); + EFI_VARIABLE_RUNTIME_ACCESS | + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS); s += sprintf(s, "{"); while (attributes) { - u32 attr = 1 << (ffs(attributes) - 1); + attr = 1 << (ffs(attributes) - 1); - if (attr == EFI_VARIABLE_NON_VOLATILE) + if (attr == READ_ONLY) { + s += sprintf(s, "ro"); + } else if (attr == EFI_VARIABLE_NON_VOLATILE) { s += sprintf(s, "nv"); - else if (attr == EFI_VARIABLE_BOOTSERVICE_ACCESS) + } else if (attr == EFI_VARIABLE_BOOTSERVICE_ACCESS) { s += sprintf(s, "boot"); - else if (attr == EFI_VARIABLE_RUNTIME_ACCESS) + } else if (attr == EFI_VARIABLE_RUNTIME_ACCESS) { s += sprintf(s, "run"); + } else if (attr == + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) { + s += sprintf(s, "time="); + s = bin2hex(s, (u8 *)&time, sizeof(time)); + } attributes &= ~attr; if (attributes) s += sprintf(s, ","); } s += sprintf(s, "}"); - - if (old_size) - /* APPEND_WRITE */ - s += sprintf(s, old_val); - else - s += sprintf(s, "(blob)"); + s += sprintf(s, "(blob)"); /* store payload: */ + if (append) + s = bin2hex(s, old_data, old_size); s = bin2hex(s, data, data_size); *s = '\0'; EFI_PRINT("setting: %s=%s\n", native_name, val); +out: if (env_set(native_name, val)) ret = EFI_DEVICE_ERROR; + else + ret = EFI_SUCCESS; -out: +err: free(native_name); + free(old_data); free(val); - return EFI_EXIT(ret); + return ret; +} + +static +efi_status_t EFIAPI efi_set_volatile_variable(u16 *variable_name, + const efi_guid_t *vendor, + u32 attributes, + efi_uintn_t data_size, + const void *data, + bool ro_check) +{ + return efi_set_variable_common(variable_name, vendor, attributes, + data_size, data, ro_check, false); +} + +efi_status_t EFIAPI efi_set_nonvolatile_variable(u16 *variable_name, + const efi_guid_t *vendor, + u32 attributes, + efi_uintn_t data_size, + const void *data, + bool ro_check) +{ + efi_status_t ret; + + ret = efi_set_variable_common(variable_name, vendor, attributes, + data_size, data, ro_check, true); + + return ret; +} + +static efi_status_t efi_set_variable_internal(u16 *variable_name, + const efi_guid_t *vendor, + u32 attributes, + efi_uintn_t data_size, + const void *data, + bool ro_check) +{ + efi_status_t ret; + + if (attributes & EFI_VARIABLE_NON_VOLATILE) + ret = efi_set_nonvolatile_variable(variable_name, vendor, + attributes, + data_size, data, ro_check); + else + ret = efi_set_volatile_variable(variable_name, vendor, + attributes, data_size, data, + ro_check); + + return ret; +} + +/** + * efi_set_variable() - set value of a UEFI variable + * + * This function implements the SetVariable runtime service. + * + * See the Unified Extensible Firmware Interface (UEFI) specification for + * details. + * + * @variable_name: name of the variable + * @vendor: vendor GUID + * @attributes: attributes of the variable + * @data_size: size of the buffer with the variable value + * @data: buffer with the variable value + * Return: status code + */ +efi_status_t EFIAPI efi_set_variable(u16 *variable_name, + const efi_guid_t *vendor, u32 attributes, + efi_uintn_t data_size, const void *data) +{ + EFI_ENTRY("\"%ls\" %pUl %x %zu %p", variable_name, vendor, attributes, + data_size, data); + + /* READ_ONLY bit is not part of API */ + attributes &= ~(u32)READ_ONLY; + + return EFI_EXIT(efi_set_variable_internal(variable_name, vendor, + attributes, data_size, data, + true)); } /** From patchwork Tue Apr 14 02:51:42 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270034 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=MOADvP7m; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VRr6m84z9s71 for ; Tue, 14 Apr 2020 12:53:34 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id A551F8058D; Tue, 14 Apr 2020 04:53:22 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="MOADvP7m"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 10F0881819; Tue, 14 Apr 2020 04:52:50 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1043.google.com (mail-pj1-x1043.google.com [IPv6:2607:f8b0:4864:20::1043]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 6A9518181D for ; Tue, 14 Apr 2020 04:52:36 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1043.google.com with SMTP id a22so254511pjk.5 for ; Mon, 13 Apr 2020 19:52:36 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=C153axOPrne4OfcCmsm2gDDJrX6pgSvZ2vwgoBE+My8=; b=MOADvP7mrQfK9Z+uUm/cZM+GzR4Boj+cALXTCncX/3ZCP5xoH6TOVWQ41Zn5xCnUAp IoHhaMxZlTN8BVfHScFPNiwkVTk9j8hSi2ftmmKWsryr5dmEh0hcY56B1lhwuYoE+kHC vm84iDrW4EuFtzkUy8Jvm2G1GX1OHtdU0fbfcU2QQpZozt31XaTnMaJRAdyEkpNRy5BB cvdwvExMUIGpKyjtZEeRkUQxYcYFgbOvzVEU3naHdRDaMe7yKkr0GLwQwPa5vAMbg2Di ac4AD2VvHBsR2n22tDHi9ukjAszdSdoVHyN6Zz5UvAFqKz6dtW6PjWy3ogvWtBh2tADM 918Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=C153axOPrne4OfcCmsm2gDDJrX6pgSvZ2vwgoBE+My8=; b=QIihlo48YTfZw+VMT5vkOpFVQHWge2bB7KPTtn5ys9pXBglyoXL4/dNTFJ0qsAg43r sJ46eMhbXpQQuNoODmG/TC+8whdEBKkhdaAgIeXmQFjaMvnh0G/HDb9BjKghSFfeoPUD XjQcRY04Smbedfm+PoDD5qsg4hgiiEaZsxzVWERLTgy2yGgLkE7cPYOM2rILt76uLb64 Hp0ml2Wr5i5RioWK0W+7g/lMD2e1eCAQ6INqHaN0olDXgECEw0gHiQvkynSvz6XRFlZ9 9dW5HhZewplHUoFC3NXMz/PTAuTMCpcQ6W53AYVFWT1mKqt1EEJpX6bOy1uibMLJRYjJ 4/GQ== X-Gm-Message-State: AGi0PuaOvFwIuDvqMk/+OQ8TiQ9PVDx29pmNtBugIqevUr1GbNQbVZMB FdbmQNXWOP945t/yxLbpFv0Z0Q== X-Google-Smtp-Source: APiQypKEm03kxWoN09icDqUDmd1hwjRpPtehaOjqm+rb/rdXZQ8NXVUPD7lc1Ad6xa4mCgeP5ohz3g== X-Received: by 2002:a17:902:6544:: with SMTP id d4mr20534955pln.310.1586832754917; Mon, 13 Apr 2020 19:52:34 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:34 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 05/17] efi_loader: variable: add secure boot state transition Date: Tue, 14 Apr 2020 11:51:42 +0900 Message-Id: <20200414025154.27283-6-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean UEFI specification defines several global variables which are related to the current secure boot state. In this commit, those values will be maintained according to operations. Currently, AuditMode and DeployedMode are defined but not implemented. Signed-off-by: AKASHI Takahiro --- lib/efi_loader/efi_variable.c | 231 +++++++++++++++++++++++++++++++++- 1 file changed, 228 insertions(+), 3 deletions(-) diff --git a/lib/efi_loader/efi_variable.c b/lib/efi_loader/efi_variable.c index adb78470f2d6..fd5c41f830b1 100644 --- a/lib/efi_loader/efi_variable.c +++ b/lib/efi_loader/efi_variable.c @@ -16,8 +16,16 @@ #include #include "../lib/crypto/pkcs7_parser.h" +enum efi_secure_mode { + EFI_MODE_SETUP, + EFI_MODE_USER, + EFI_MODE_AUDIT, + EFI_MODE_DEPLOYED, +}; + const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID; static bool efi_secure_boot; +static int efi_secure_mode; #define READ_ONLY BIT(31) @@ -160,6 +168,210 @@ static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) return str; } +static efi_status_t efi_set_variable_internal(u16 *variable_name, + const efi_guid_t *vendor, + u32 attributes, + efi_uintn_t data_size, + const void *data, + bool ro_check); + +/** + * efi_transfer_secure_state - handle a secure boot state transition + * @mode: new state + * + * Depending on @mode, secure boot related variables are updated. + * Those variables are *read-only* for users, efi_set_variable_internal() + * is called here. + * + * Return: EFI_SUCCESS on success, status code (negative) on error + */ +static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode) +{ + u32 attributes; + u8 val; + efi_status_t ret; + + debug("Secure state from %d to %d\n", efi_secure_mode, mode); + + attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS | + EFI_VARIABLE_RUNTIME_ACCESS; + if (mode == EFI_MODE_DEPLOYED) { + val = 1; + ret = efi_set_variable_internal(L"SecureBoot", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"SetupMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"AuditMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 1; + ret = efi_set_variable_internal(L"DeployedMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + + efi_secure_boot = true; + } else if (mode == EFI_MODE_AUDIT) { + ret = efi_set_variable_internal(L"PK", + &efi_global_variable_guid, + attributes, + 0, NULL, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"SecureBoot", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 1; + ret = efi_set_variable_internal(L"SetupMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 1; + ret = efi_set_variable_internal(L"AuditMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"DeployedMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + + efi_secure_boot = true; + } else if (mode == EFI_MODE_USER) { + val = 1; + ret = efi_set_variable_internal(L"SecureBoot", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"SetupMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"AuditMode", + &efi_global_variable_guid, + attributes, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"DeployedMode", + &efi_global_variable_guid, + attributes, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + + efi_secure_boot = true; + } else if (mode == EFI_MODE_SETUP) { + val = 0; + ret = efi_set_variable_internal(L"SecureBoot", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 1; + ret = efi_set_variable_internal(L"SetupMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"AuditMode", + &efi_global_variable_guid, + attributes, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + val = 0; + ret = efi_set_variable_internal(L"DeployedMode", + &efi_global_variable_guid, + attributes | READ_ONLY, + sizeof(val), &val, + false); + if (ret != EFI_SUCCESS) + goto err; + } else { + return EFI_INVALID_PARAMETER; + } + + return EFI_SUCCESS; + +err: + /* TODO: What action should be taken here? */ + printf("ERROR: Secure state transition failed\n"); + return ret; +} + +/** + * efi_init_secure_state - initialize secure boot state + * + * Return: EFI_SUCCESS on success, status code (negative) on error + */ +static efi_status_t efi_init_secure_state(void) +{ + efi_uintn_t size = 0; + efi_status_t ret; + + ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid, + NULL, &size, NULL)); + if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) + ret = efi_transfer_secure_state(EFI_MODE_USER); + else + ret = efi_transfer_secure_state(EFI_MODE_SETUP); + + return ret; +} + /** * efi_secure_boot_enabled - return if secure boot is enabled or not * @@ -910,10 +1122,19 @@ efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name, EFI_PRINT("setting: %s=%s\n", native_name, val); out: - if (env_set(native_name, val)) + if (env_set(native_name, val)) { ret = EFI_DEVICE_ERROR; - else + } else { + if ((u16_strcmp(variable_name, L"PK") == 0 && + guidcmp(vendor, &efi_global_variable_guid) == 0)) { + ret = efi_transfer_secure_state( + (delete ? EFI_MODE_SETUP : + EFI_MODE_USER)); + if (ret != EFI_SUCCESS) + goto err; + } ret = EFI_SUCCESS; + } err: free(native_name); @@ -1098,5 +1319,9 @@ void efi_variables_boot_exit_notify(void) */ efi_status_t efi_init_variables(void) { - return EFI_SUCCESS; + efi_status_t ret; + + ret = efi_init_secure_state(); + + return ret; } From patchwork Tue Apr 14 02:51:43 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270033 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=Gh3k5g8p; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VRQ5PSFz9sSq for ; Tue, 14 Apr 2020 12:53:21 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 25FD681819; Tue, 14 Apr 2020 04:53:17 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="Gh3k5g8p"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 52B8281759; Tue, 14 Apr 2020 04:52:49 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1043.google.com (mail-pj1-x1043.google.com [IPv6:2607:f8b0:4864:20::1043]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id BFAAC81819 for ; Tue, 14 Apr 2020 04:52:39 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1043.google.com with SMTP id t40so4623674pjb.3 for ; Mon, 13 Apr 2020 19:52:39 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=33BF95YzXeRCaBOOpY3cA+qRMkn9Mj2cWT7+bMQRvNI=; b=Gh3k5g8pemDXUC/g5AdeCn9N39chSVtPVx97Rzsz/YjjEeZ8AX6bPH/F+rxeDX2DmM FSirXEp3aaaLyf2pPGJI/Ca3GuN8MGtkU8y21rv9nOlyMqPqvqSQ2zcbJHdNOc3hK3Yz mKrKdXALZrH/Onr/8C70hDkX9tDRJHcIe7pELUNFFjaA50rcCJ8golKyyfOvPHMDo50q 53jw1ISCX8HQUhoAyyKDp5AniQYZ7oieS1qwd3MfM8pOCpoifeQ8CFzUogQqdfQG9JhB CBAfQQSHv+vMaS/1UzvGI1T59sVDwkTgS796MdXpwnyk73hGTb2TiecdkjCquefAzywl E8BQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=33BF95YzXeRCaBOOpY3cA+qRMkn9Mj2cWT7+bMQRvNI=; b=hVqyZTlpH8SS4A5OeHxk1N9NPqvMN4OVX6+5DkLkyJznrUaVBLGnpd+6DzCJaxwx50 1nIdyvUEbo8mPGyUohG/ZiF/FbGF3UNgm+ROtla9D2ASFUWUwOXuO3ZzO7Hw+IUA3+iZ fsB1OwwSJ6XFCu9+TAKK5UBeEneXenuKsb2b6Jgs/RnL7jVQ6il6FH84pzAyc/jvpNcF SXftjSfF/oWloyIhPma2cAv9K0MXrIBd9JldF1GOJVvfpL1/CmJoOKByNBNooW/1zk7D vakW2ar8UDrpKZyN6oTbHhePuiB+9BBWs5sen1bERJVVV3DsWhf5N4BGQ8EEOC0QzNs4 HAHQ== X-Gm-Message-State: AGi0PubJvQ0XcVRMrDt/r1nPaYj0qopgbgmLWXjEJe+WXKEVRVYjCRQg 7IaHh/+sIYoVb3l1x7og7BPksg== X-Google-Smtp-Source: APiQypLopT5q1NWb7ohGURy1+n0mn0T10OWpF7OVKEkYIVIgp+HnyTkSWL5VDQu4k5xNv4Nhcwg4zw== X-Received: by 2002:a17:902:ea8a:: with SMTP id x10mr20664083plb.328.1586832758308; Mon, 13 Apr 2020 19:52:38 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.35 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:37 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 06/17] efi_loader: variable: add VendorKeys variable Date: Tue, 14 Apr 2020 11:51:43 +0900 Message-Id: <20200414025154.27283-7-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean The following variable is exported as UEFI specification defines: VendorKeys: whether the system is configured to use only vendor-provided keys or not The value will have to be modified if a platform has its own way of initializing signature database, in particular, PK. Signed-off-by: AKASHI Takahiro --- lib/efi_loader/efi_variable.c | 69 ++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/lib/efi_loader/efi_variable.c b/lib/efi_loader/efi_variable.c index fd5c41f830b1..7df881a74b44 100644 --- a/lib/efi_loader/efi_variable.c +++ b/lib/efi_loader/efi_variable.c @@ -26,6 +26,7 @@ enum efi_secure_mode { const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID; static bool efi_secure_boot; static int efi_secure_mode; +static u8 efi_vendor_keys; #define READ_ONLY BIT(31) @@ -344,6 +345,8 @@ static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode) return EFI_INVALID_PARAMETER; } + efi_secure_mode = mode; + return EFI_SUCCESS; err: @@ -359,16 +362,46 @@ err: */ static efi_status_t efi_init_secure_state(void) { - efi_uintn_t size = 0; + enum efi_secure_mode mode; + efi_uintn_t size; efi_status_t ret; + /* + * TODO: + * Since there is currently no "platform-specific" installation + * method of Platform Key, we can't say if VendorKeys is 0 or 1 + * precisely. + */ + + size = 0; ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid, NULL, &size, NULL)); - if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) - ret = efi_transfer_secure_state(EFI_MODE_USER); - else - ret = efi_transfer_secure_state(EFI_MODE_SETUP); + if (ret == EFI_BUFFER_TOO_SMALL) { + if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT)) + mode = EFI_MODE_USER; + else + mode = EFI_MODE_SETUP; + + efi_vendor_keys = 0; + } else if (ret == EFI_NOT_FOUND) { + mode = EFI_MODE_SETUP; + efi_vendor_keys = 1; + } else { + goto err; + } + ret = efi_transfer_secure_state(mode); + if (ret == EFI_SUCCESS) + ret = efi_set_variable_internal(L"VendorKeys", + &efi_global_variable_guid, + EFI_VARIABLE_BOOTSERVICE_ACCESS + | EFI_VARIABLE_RUNTIME_ACCESS + | READ_ONLY, + sizeof(efi_vendor_keys), + &efi_vendor_keys, + false); + +err: return ret; } @@ -1125,6 +1158,8 @@ out: if (env_set(native_name, val)) { ret = EFI_DEVICE_ERROR; } else { + bool vendor_keys_modified = false; + if ((u16_strcmp(variable_name, L"PK") == 0 && guidcmp(vendor, &efi_global_variable_guid) == 0)) { ret = efi_transfer_secure_state( @@ -1132,8 +1167,30 @@ out: EFI_MODE_USER)); if (ret != EFI_SUCCESS) goto err; + + if (efi_secure_mode != EFI_MODE_SETUP) + vendor_keys_modified = true; + } else if ((u16_strcmp(variable_name, L"KEK") == 0 && + guidcmp(vendor, &efi_global_variable_guid) == 0)) { + if (efi_secure_mode != EFI_MODE_SETUP) + vendor_keys_modified = true; + } + + /* update VendorKeys */ + if (vendor_keys_modified & efi_vendor_keys) { + efi_vendor_keys = 0; + ret = efi_set_variable_internal( + L"VendorKeys", + &efi_global_variable_guid, + EFI_VARIABLE_BOOTSERVICE_ACCESS + | EFI_VARIABLE_RUNTIME_ACCESS + | READ_ONLY, + sizeof(efi_vendor_keys), + &efi_vendor_keys, + false); + } else { + ret = EFI_SUCCESS; } - ret = EFI_SUCCESS; } err: From patchwork Tue Apr 14 02:51:44 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270037 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=R5z6eW4y; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VSJ3jT3z9s71 for ; Tue, 14 Apr 2020 12:54:07 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id A9C3C8180B; Tue, 14 Apr 2020 04:53:40 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="R5z6eW4y"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 02B3D81759; Tue, 14 Apr 2020 04:53:05 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pl1-x62d.google.com (mail-pl1-x62d.google.com [IPv6:2607:f8b0:4864:20::62d]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id B36BA81824 for ; Tue, 14 Apr 2020 04:52:43 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pl1-x62d.google.com with SMTP id v2so4131170plp.9 for ; Mon, 13 Apr 2020 19:52:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=kpUUvql5T/RmbCjq3XSDkcBz/K39xwz6l40dvgvP7cM=; b=R5z6eW4yu4c/tut58O0Q0ci13t9tYy4VVi4lXl4daT3O1Y1vj2Gpw1oPbnAYCfoGRg IGvkO1K1dXtKBBg/IJ2KeMpNIsP84+n37IZwfaPNqdCo3G9m3vrb0Jq8L1Q1RGRm/zOk 5g77ZOVFzstHs863D1kO3saIbWOOS+urkYBEJZZspPwD5ad0+4zJe3b3jR6MnPQrdMwi lmPEDl3WvE+IcbxrP4jqd19T1jTzbi+9w1fLG5D5G+qi9tas81LNlaZL1PHsqocijKQF FDHB+IIB2VgnfQXqlkKm4IcqQn0qK4AlP3klGmunc1anPCiWQ0cfknsu6haENaAL9Icu 3AJw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=kpUUvql5T/RmbCjq3XSDkcBz/K39xwz6l40dvgvP7cM=; b=ZhtmzZdBvN+diIFAFMJY9W1ApsSNb0Ap+oCmUo1h5M1gMcBJGfN7OYVrc4v0LXNMTH mb7LLtnt+2W3YaWFJPb+tb7jKBt71fkBlnvFsn0VhpSF2iUn7JCPcAnpYouXdR3L7lph HZaOuksSQUELr33I0+2d6HOljr2yXxKKN3Kxoaxv/l9/wn2fmvLAUAtGzh7sQT9YGg0A eYMsqDozZdy0OmJ4E1RU88C/7qrCf0kk1eUsrCEpIYd6Qh7pcQIT8QYlxBc8QsqhMF2Q PYJDDl2daoBzG9vMafcBfMVF/84NVamGWStn+nELbcdJ1wXiYHtF830EpfNKZtoIU4iQ lBaA== X-Gm-Message-State: AGi0PuaG/CFUzaa2JcRVmtnm7xWvjtaEhzLnkLc7P6ZqIrD4e+jGsHWU UEU+NXsC0MShw0/7qxXFJcLI+Q== X-Google-Smtp-Source: APiQypIX6llznLV6t4lz9oIA8vMp/PsLKCwQKRuUgauI9svIyjMLOzdR20mAGthd8H0lUj13tt+uDA== X-Received: by 2002:a17:90a:4f46:: with SMTP id w6mr24423957pjl.161.1586832761722; Mon, 13 Apr 2020 19:52:41 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.38 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:41 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 07/17] efi_loader: image_loader: support image authentication Date: Tue, 14 Apr 2020 11:51:44 +0900 Message-Id: <20200414025154.27283-8-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean With this commit, image validation can be enforced, as UEFI specification section 32.5 describes, if CONFIG_EFI_SECURE_BOOT is enabled. Currently we support * authentication based on db and dbx, so dbx-validated image will always be rejected. * following signature types: EFI_CERT_SHA256_GUID (SHA256 digest for unsigned images) EFI_CERT_X509_GUID (x509 certificate for signed images) Timestamp-based certificate revocation is not supported here. Internally, authentication data is stored in one of certificates tables of PE image (See efi_image_parse()) and will be verified by efi_image_authenticate() before loading a given image. It seems that UEFI specification defines the verification process in a bit ambiguous way. I tried to implement it as closely to as EDK2 does. Signed-off-by: AKASHI Takahiro --- include/efi_loader.h | 13 +- lib/efi_loader/efi_boottime.c | 10 +- lib/efi_loader/efi_image_loader.c | 462 +++++++++++++++++++++++++++++- 3 files changed, 469 insertions(+), 16 deletions(-) diff --git a/include/efi_loader.h b/include/efi_loader.h index ef8d184a6ee7..0ba9a1f702a6 100644 --- a/include/efi_loader.h +++ b/include/efi_loader.h @@ -11,6 +11,7 @@ #include #include #include +#include static inline int guidcmp(const void *g1, const void *g2) { @@ -263,6 +264,11 @@ struct efi_object { enum efi_object_type type; }; +enum efi_image_auth_status { + EFI_IMAGE_AUTH_FAILED = 0, + EFI_IMAGE_AUTH_PASSED, +}; + /** * struct efi_loaded_image_obj - handle of a loaded image * @@ -282,6 +288,7 @@ struct efi_loaded_image_obj { EFIAPI efi_status_t (*entry)(efi_handle_t image_handle, struct efi_system_table *st); u16 image_type; + enum efi_image_auth_status auth_status; }; /** @@ -415,7 +422,8 @@ efi_status_t efi_set_watchdog(unsigned long timeout); /* Called from places to check whether a timer expired */ void efi_timer_check(void); /* PE loader implementation */ -efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, +efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, + void *efi, size_t efi_size, struct efi_loaded_image *loaded_image_info); /* Called once to store the pristine gd pointer */ void efi_save_gd(void); @@ -756,6 +764,9 @@ void efi_sigstore_free(struct efi_signature_store *sigstore); struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name); bool efi_secure_boot_enabled(void); + +bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp, + WIN_CERTIFICATE **auth, size_t *auth_len); #endif /* CONFIG_EFI_SECURE_BOOT */ #else /* CONFIG_IS_ENABLED(EFI_LOADER) */ diff --git a/lib/efi_loader/efi_boottime.c b/lib/efi_loader/efi_boottime.c index 3b79a88a480f..a3f11eaf6228 100644 --- a/lib/efi_loader/efi_boottime.c +++ b/lib/efi_loader/efi_boottime.c @@ -1882,12 +1882,12 @@ efi_status_t EFIAPI efi_load_image(bool boot_policy, efi_dp_split_file_path(file_path, &dp, &fp); ret = efi_setup_loaded_image(dp, fp, image_obj, &info); if (ret == EFI_SUCCESS) - ret = efi_load_pe(*image_obj, dest_buffer, info); + ret = efi_load_pe(*image_obj, dest_buffer, source_size, info); if (!source_buffer) /* Release buffer to which file was loaded */ efi_free_pages((uintptr_t)dest_buffer, efi_size_in_pages(source_size)); - if (ret == EFI_SUCCESS) { + if (ret == EFI_SUCCESS || ret == EFI_SECURITY_VIOLATION) { info->system_table = &systab; info->parent_handle = parent_image; } else { @@ -2885,10 +2885,16 @@ efi_status_t EFIAPI efi_start_image(efi_handle_t image_handle, EFI_ENTRY("%p, %p, %p", image_handle, exit_data_size, exit_data); + if (!efi_search_obj(image_handle)) + return EFI_EXIT(EFI_INVALID_PARAMETER); + /* Check parameters */ if (image_obj->header.type != EFI_OBJECT_TYPE_LOADED_IMAGE) return EFI_EXIT(EFI_INVALID_PARAMETER); + if (image_obj->auth_status != EFI_IMAGE_AUTH_PASSED) + return EFI_EXIT(EFI_SECURITY_VIOLATION); + ret = EFI_CALL(efi_open_protocol(image_handle, &efi_guid_loaded_image, &info, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL)); diff --git a/lib/efi_loader/efi_image_loader.c b/lib/efi_loader/efi_image_loader.c index d5de6df16d84..6c270ce94f44 100644 --- a/lib/efi_loader/efi_image_loader.c +++ b/lib/efi_loader/efi_image_loader.c @@ -10,7 +10,10 @@ #include #include #include +#include #include +#include +#include "../lib/crypto/pkcs7_parser.h" const efi_guid_t efi_global_variable_guid = EFI_GLOBAL_VARIABLE_GUID; const efi_guid_t efi_guid_device_path = EFI_DEVICE_PATH_PROTOCOL_GUID; @@ -206,6 +209,386 @@ static void efi_set_code_and_data_type( } } +#ifdef CONFIG_EFI_SECURE_BOOT +/** + * cmp_pe_section - compare two sections + * @arg1: Pointer to pointer to first section + * @arg2: Pointer to pointer to second section + * + * Compare two sections in PE image. + * + * Return: -1, 0, 1 respectively if arg1 < arg2, arg1 == arg2 or + * arg1 > arg2 + */ +static int cmp_pe_section(const void *arg1, const void *arg2) +{ + const IMAGE_SECTION_HEADER *section1, *section2; + + section1 = *((const IMAGE_SECTION_HEADER **)arg1); + section2 = *((const IMAGE_SECTION_HEADER **)arg2); + + if (section1->VirtualAddress < section2->VirtualAddress) + return -1; + else if (section1->VirtualAddress == section2->VirtualAddress) + return 0; + else + return 1; +} + +/** + * efi_image_parse - parse a PE image + * @efi: Pointer to image + * @len: Size of @efi + * @regp: Pointer to a list of regions + * @auth: Pointer to a pointer to authentication data in PE + * @auth_len: Size of @auth + * + * Parse image binary in PE32(+) format, assuming that sanity of PE image + * has been checked by a caller. + * On success, an address of authentication data in @efi and its size will + * be returned in @auth and @auth_len, respectively. + * + * Return: true on success, false on error + */ +bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp, + WIN_CERTIFICATE **auth, size_t *auth_len) +{ + struct efi_image_regions *regs; + IMAGE_DOS_HEADER *dos; + IMAGE_NT_HEADERS32 *nt; + IMAGE_SECTION_HEADER *sections, **sorted; + int num_regions, num_sections, i; + int ctidx = IMAGE_DIRECTORY_ENTRY_SECURITY; + u32 align, size, authsz, authoff; + size_t bytes_hashed; + + dos = (void *)efi; + nt = (void *)(efi + dos->e_lfanew); + + /* + * Count maximum number of regions to be digested. + * We don't have to have an exact number here. + * See efi_image_region_add()'s in parsing below. + */ + num_regions = 3; /* for header */ + num_regions += nt->FileHeader.NumberOfSections; + num_regions++; /* for extra */ + + regs = calloc(sizeof(*regs) + sizeof(struct image_region) * num_regions, + 1); + if (!regs) + goto err; + regs->max = num_regions; + + /* + * Collect data regions for hash calculation + * 1. File headers + */ + if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) { + IMAGE_NT_HEADERS64 *nt64 = (void *)nt; + IMAGE_OPTIONAL_HEADER64 *opt = &nt64->OptionalHeader; + + /* Skip CheckSum */ + efi_image_region_add(regs, efi, &opt->CheckSum, 0); + if (nt64->OptionalHeader.NumberOfRvaAndSizes <= ctidx) { + efi_image_region_add(regs, + &opt->CheckSum + 1, + efi + opt->SizeOfHeaders, 0); + } else { + /* Skip Certificates Table */ + efi_image_region_add(regs, + &opt->CheckSum + 1, + &opt->DataDirectory[ctidx], 0); + efi_image_region_add(regs, + &opt->DataDirectory[ctidx] + 1, + efi + opt->SizeOfHeaders, 0); + } + + bytes_hashed = opt->SizeOfHeaders; + align = opt->FileAlignment; + authoff = opt->DataDirectory[ctidx].VirtualAddress; + authsz = opt->DataDirectory[ctidx].Size; + } else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC) { + IMAGE_OPTIONAL_HEADER32 *opt = &nt->OptionalHeader; + + efi_image_region_add(regs, efi, &opt->CheckSum, 0); + efi_image_region_add(regs, &opt->CheckSum + 1, + &opt->DataDirectory[ctidx], 0); + efi_image_region_add(regs, &opt->DataDirectory[ctidx] + 1, + efi + opt->SizeOfHeaders, 0); + + bytes_hashed = opt->SizeOfHeaders; + align = opt->FileAlignment; + authoff = opt->DataDirectory[ctidx].VirtualAddress; + authsz = opt->DataDirectory[ctidx].Size; + } else { + debug("%s: Invalid optional header magic %x\n", __func__, + nt->OptionalHeader.Magic); + goto err; + } + + /* 2. Sections */ + num_sections = nt->FileHeader.NumberOfSections; + sections = (void *)((uint8_t *)&nt->OptionalHeader + + nt->FileHeader.SizeOfOptionalHeader); + sorted = calloc(sizeof(IMAGE_SECTION_HEADER *), num_sections); + if (!sorted) { + debug("%s: Out of memory\n", __func__); + goto err; + } + + /* + * Make sure the section list is in ascending order. + */ + for (i = 0; i < num_sections; i++) + sorted[i] = §ions[i]; + qsort(sorted, num_sections, sizeof(sorted[0]), cmp_pe_section); + + for (i = 0; i < num_sections; i++) { + if (!sorted[i]->SizeOfRawData) + continue; + + size = (sorted[i]->SizeOfRawData + align - 1) & ~(align - 1); + efi_image_region_add(regs, efi + sorted[i]->PointerToRawData, + efi + sorted[i]->PointerToRawData + size, + 0); + debug("section[%d](%s): raw: 0x%x-0x%x, virt: %x-%x\n", + i, sorted[i]->Name, + sorted[i]->PointerToRawData, + sorted[i]->PointerToRawData + size, + sorted[i]->VirtualAddress, + sorted[i]->VirtualAddress + + sorted[i]->Misc.VirtualSize); + + bytes_hashed += size; + } + free(sorted); + + /* 3. Extra data excluding Certificates Table */ + if (bytes_hashed + authsz < len) { + debug("extra data for hash: %lu\n", + len - (bytes_hashed + authsz)); + efi_image_region_add(regs, efi + bytes_hashed, + efi + len - authsz, 0); + } + + /* Return Certificates Table */ + if (authsz) { + if (len < authoff + authsz) { + debug("%s: Size for auth too large: %u >= %zu\n", + __func__, authsz, len - authoff); + goto err; + } + if (authsz < sizeof(*auth)) { + debug("%s: Size for auth too small: %u < %zu\n", + __func__, authsz, sizeof(*auth)); + goto err; + } + *auth = efi + authoff; + *auth_len = authsz; + debug("WIN_CERTIFICATE: 0x%x, size: 0x%x\n", authoff, authsz); + } else { + *auth = NULL; + *auth_len = 0; + } + + *regp = regs; + + return true; + +err: + free(regs); + + return false; +} + +/** + * efi_image_unsigned_authenticate - authenticate unsigned image with + * SHA256 hash + * @regs: List of regions to be verified + * + * If an image is not signed, it doesn't have a signature. In this case, + * its message digest is calculated and it will be compared with one of + * hash values stored in signature databases. + * + * Return: true if authenticated, false if not + */ +static bool efi_image_unsigned_authenticate(struct efi_image_regions *regs) +{ + struct efi_signature_store *db = NULL, *dbx = NULL; + bool ret = false; + + dbx = efi_sigstore_parse_sigdb(L"dbx"); + if (!dbx) { + debug("Getting signature database(dbx) failed\n"); + goto out; + } + + db = efi_sigstore_parse_sigdb(L"db"); + if (!db) { + debug("Getting signature database(db) failed\n"); + goto out; + } + + /* try black-list first */ + if (efi_signature_verify_with_sigdb(regs, NULL, dbx, NULL)) { + debug("Image is not signed and rejected by \"dbx\"\n"); + goto out; + } + + /* try white-list */ + if (efi_signature_verify_with_sigdb(regs, NULL, db, NULL)) + ret = true; + else + debug("Image is not signed and not found in \"db\" or \"dbx\"\n"); + +out: + efi_sigstore_free(db); + efi_sigstore_free(dbx); + + return ret; +} + +/** + * efi_image_authenticate - verify a signature of signed image + * @efi: Pointer to image + * @efi_size: Size of @efi + * + * A signed image should have its signature stored in a table of its PE header. + * So if an image is signed and only if if its signature is verified using + * signature databases, an image is authenticated. + * If an image is not signed, its validity is checked by using + * efi_image_unsigned_authenticated(). + * TODO: + * When AuditMode==0, if the image's signature is not found in + * the authorized database, or is found in the forbidden database, + * the image will not be started and instead, information about it + * will be placed in this table. + * When AuditMode==1, an EFI_IMAGE_EXECUTION_INFO element is created + * in the EFI_IMAGE_EXECUTION_INFO_TABLE for every certificate found + * in the certificate table of every image that is validated. + * + * Return: true if authenticated, false if not + */ +static bool efi_image_authenticate(void *efi, size_t efi_size) +{ + struct efi_image_regions *regs = NULL; + WIN_CERTIFICATE *wincerts = NULL, *wincert; + size_t wincerts_len; + struct pkcs7_message *msg = NULL; + struct efi_signature_store *db = NULL, *dbx = NULL; + struct x509_certificate *cert = NULL; + void *new_efi = NULL; + size_t new_efi_size; + bool ret = false; + + if (!efi_secure_boot_enabled()) + return true; + + /* + * Size must be 8-byte aligned and the trailing bytes must be + * zero'ed. Otherwise hash value may be incorrect. + */ + if (efi_size & 0x7) { + new_efi_size = (efi_size + 0x7) & ~0x7ULL; + new_efi = calloc(new_efi_size, 1); + if (!new_efi) + return false; + memcpy(new_efi, efi, efi_size); + efi = new_efi; + efi_size = new_efi_size; + } + + if (!efi_image_parse(efi, efi_size, ®s, &wincerts, + &wincerts_len)) { + debug("Parsing PE executable image failed\n"); + goto err; + } + + if (!wincerts) { + /* The image is not signed */ + ret = efi_image_unsigned_authenticate(regs); + + goto err; + } + + /* + * verify signature using db and dbx + */ + db = efi_sigstore_parse_sigdb(L"db"); + if (!db) { + debug("Getting signature database(db) failed\n"); + goto err; + } + + dbx = efi_sigstore_parse_sigdb(L"dbx"); + if (!dbx) { + debug("Getting signature database(dbx) failed\n"); + goto err; + } + + /* go through WIN_CERTIFICATE list */ + for (wincert = wincerts; + (void *)wincert < (void *)wincerts + wincerts_len; + wincert = (void *)wincert + ALIGN(wincert->dwLength, 8)) { + if (wincert->dwLength < sizeof(*wincert)) { + debug("%s: dwLength too small: %u < %zu\n", + __func__, wincert->dwLength, sizeof(*wincert)); + goto err; + } + msg = pkcs7_parse_message((void *)wincert + sizeof(*wincert), + wincert->dwLength - sizeof(*wincert)); + if (!msg) { + debug("Parsing image's signature failed\n"); + goto err; + } + + /* try black-list first */ + if (efi_signature_verify_with_sigdb(regs, msg, dbx, NULL)) { + debug("Signature was rejected by \"dbx\"\n"); + goto err; + } + + if (!efi_signature_verify_signers(msg, dbx)) { + debug("Signer was rejected by \"dbx\"\n"); + goto err; + } else { + ret = true; + } + + /* try white-list */ + if (!efi_signature_verify_with_sigdb(regs, msg, db, &cert)) { + debug("Verifying signature with \"db\" failed\n"); + goto err; + } else { + ret = true; + } + + if (!efi_signature_verify_cert(cert, dbx)) { + debug("Certificate was rejected by \"dbx\"\n"); + goto err; + } else { + ret = true; + } + } + +err: + x509_free_certificate(cert); + efi_sigstore_free(db); + efi_sigstore_free(dbx); + pkcs7_free_message(msg); + free(regs); + free(new_efi); + + return ret; +} +#else +static bool efi_image_authenticate(void *efi, size_t efi_size) +{ + return true; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ + /** * efi_load_pe() - relocate EFI binary * @@ -214,10 +597,12 @@ static void efi_set_code_and_data_type( * * @handle: loaded image handle * @efi: pointer to the EFI binary + * @efi_size: size of @efi binary * @loaded_image_info: loaded image protocol * Return: status code */ -efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, +efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, + void *efi, size_t efi_size, struct efi_loaded_image *loaded_image_info) { IMAGE_NT_HEADERS32 *nt; @@ -232,17 +617,41 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, uint64_t image_base; unsigned long virt_size = 0; int supported = 0; + efi_status_t ret; + + /* Sanity check for a file header */ + if (efi_size < sizeof(*dos)) { + printf("%s: Truncated DOS Header\n", __func__); + ret = EFI_LOAD_ERROR; + goto err; + } dos = efi; if (dos->e_magic != IMAGE_DOS_SIGNATURE) { printf("%s: Invalid DOS Signature\n", __func__); - return EFI_LOAD_ERROR; + ret = EFI_LOAD_ERROR; + goto err; + } + + /* assume sizeof(IMAGE_NT_HEADERS32) <= sizeof(IMAGE_NT_HEADERS64) */ + if (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32)) { + printf("%s: Invalid offset for Extended Header\n", __func__); + ret = EFI_LOAD_ERROR; + goto err; } nt = (void *) ((char *)efi + dos->e_lfanew); + if ((nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) && + (efi_size < dos->e_lfanew + sizeof(IMAGE_NT_HEADERS64))) { + printf("%s: Invalid offset for Extended Header\n", __func__); + ret = EFI_LOAD_ERROR; + goto err; + } + if (nt->Signature != IMAGE_NT_SIGNATURE) { printf("%s: Invalid NT Signature\n", __func__); - return EFI_LOAD_ERROR; + ret = EFI_LOAD_ERROR; + goto err; } for (i = 0; machines[i]; i++) @@ -254,14 +663,29 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, if (!supported) { printf("%s: Machine type 0x%04x is not supported\n", __func__, nt->FileHeader.Machine); - return EFI_LOAD_ERROR; + ret = EFI_LOAD_ERROR; + goto err; } - /* Calculate upper virtual address boundary */ num_sections = nt->FileHeader.NumberOfSections; sections = (void *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader; + if (efi_size < ((void *)sections + sizeof(sections[0]) * num_sections + - efi)) { + printf("%s: Invalid number of sections: %d\n", + __func__, num_sections); + ret = EFI_LOAD_ERROR; + goto err; + } + + /* Authenticate an image */ + if (efi_image_authenticate(efi, efi_size)) + handle->auth_status = EFI_IMAGE_AUTH_PASSED; + else + handle->auth_status = EFI_IMAGE_AUTH_FAILED; + + /* Calculate upper virtual address boundary */ for (i = num_sections - 1; i >= 0; i--) { IMAGE_SECTION_HEADER *sec = §ions[i]; virt_size = max_t(unsigned long, virt_size, @@ -280,7 +704,8 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, if (!efi_reloc) { printf("%s: Could not allocate %lu bytes\n", __func__, virt_size); - return EFI_OUT_OF_RESOURCES; + ret = EFI_OUT_OF_RESOURCES; + goto err; } handle->entry = efi_reloc + opt->AddressOfEntryPoint; rel_size = opt->DataDirectory[rel_idx].Size; @@ -296,7 +721,8 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, if (!efi_reloc) { printf("%s: Could not allocate %lu bytes\n", __func__, virt_size); - return EFI_OUT_OF_RESOURCES; + ret = EFI_OUT_OF_RESOURCES; + goto err; } handle->entry = efi_reloc + opt->AddressOfEntryPoint; rel_size = opt->DataDirectory[rel_idx].Size; @@ -305,13 +731,16 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, } else { printf("%s: Invalid optional header magic %x\n", __func__, nt->OptionalHeader.Magic); - return EFI_LOAD_ERROR; + ret = EFI_LOAD_ERROR; + goto err; } /* Copy PE headers */ - memcpy(efi_reloc, efi, sizeof(*dos) + sizeof(*nt) - + nt->FileHeader.SizeOfOptionalHeader - + num_sections * sizeof(IMAGE_SECTION_HEADER)); + memcpy(efi_reloc, efi, + sizeof(*dos) + + sizeof(*nt) + + nt->FileHeader.SizeOfOptionalHeader + + num_sections * sizeof(IMAGE_SECTION_HEADER)); /* Load sections into RAM */ for (i = num_sections - 1; i >= 0; i--) { @@ -328,7 +757,8 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, (unsigned long)image_base) != EFI_SUCCESS) { efi_free_pages((uintptr_t) efi_reloc, (virt_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT); - return EFI_LOAD_ERROR; + ret = EFI_LOAD_ERROR; + goto err; } /* Flush cache */ @@ -340,5 +770,11 @@ efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi, loaded_image_info->image_base = efi_reloc; loaded_image_info->image_size = virt_size; - return EFI_SUCCESS; + if (handle->auth_status == EFI_IMAGE_AUTH_PASSED) + return EFI_SUCCESS; + else + return EFI_SECURITY_VIOLATION; + +err: + return ret; } From patchwork Tue Apr 14 02:51:45 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270036 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=A33YnlKO; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VS75NlNz9s71 for ; Tue, 14 Apr 2020 12:53:57 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 20C9381904; Tue, 14 Apr 2020 04:53:35 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="A33YnlKO"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id AFCC881834; Tue, 14 Apr 2020 04:52:58 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1041.google.com (mail-pj1-x1041.google.com [IPv6:2607:f8b0:4864:20::1041]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 67CC381718 for ; Tue, 14 Apr 2020 04:52:46 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1041.google.com with SMTP id a32so4680281pje.5 for ; Mon, 13 Apr 2020 19:52:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=S72/NRDhgAapeMJnSXbWZUJ/4F72EjjB+Ohf4ahl+eQ=; b=A33YnlKOVd6OFVPTRa5b9wrHQo7WIJ8s2sjwNAB4mOhvrn2SZFlCvE54lr7rYfgW96 1Zuop0NcYe37NhZN6kdyra5TNnJC9h4aRy/oRLB+86atmArhNJjBxxr4CZPun16EVa7o OSnRkIZboevskwRwTHZELoLMjcjy/Dv9KUuh5TiDDRFErEOkajNDZ3uqewiX7l038YL1 xt8SVW/QL2zDwwNw8JFIKzugfcthnwtkeAeYPt14U33/u3c7TZwKblxmTr4SFYI34OkR y7VjlTbiG0GKl/PGksyEAonQcO2Wf2KOvLBZ3mCcTDRyFBFrCNqFlBtCpRJncHDF28tb ZlQQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=S72/NRDhgAapeMJnSXbWZUJ/4F72EjjB+Ohf4ahl+eQ=; b=TrFWGEjoZt/Nt59GdFIxQ8yVlM8Yv792Gk4Ogo6h73MmT0e+vi+qopg5a4/HP+brjq zlK8fAbsPfOvv/2cC6qIIgarFkN3q7/T+NYylpCi2pJAsz51ceB2u0DIl0bSQp59SvF1 DIZPVadsZmu55zjqEERRAOzsKnXsOuphwpBFf73NTl+TjIQ1qvtGtQsN6k4ex39RsGNp by483nbJQCxHY9zJTzanR93wawdVbExjfdxPL93qt9QAy7524Cs1NcNG41B0tNFT+RV8 DYG0/4OGi4Ne4fb9aOF3XpUactyA3s69EnMkOQ1wAzddQ2wDxRbWmb/GDs233/1xY2m5 /dRA== X-Gm-Message-State: AGi0PubzCIegpA+JWvMGC2ULn5HXjqwKhSdjZn73h/98DKgvHs3keo+n nChUr3c+KkNwKYRe+nBahrf37A== X-Google-Smtp-Source: APiQypL+AWES85eXilRAhbdqnZJMSSio9SZysgbTQrfcqV55cFZV4n1HkBKiSFXcigsp9+ydMm01VQ== X-Received: by 2002:a17:90a:9386:: with SMTP id q6mr21919619pjo.196.1586832764941; Mon, 13 Apr 2020 19:52:44 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:44 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 08/17] efi_loader: set up secure boot Date: Tue, 14 Apr 2020 11:51:45 +0900 Message-Id: <20200414025154.27283-9-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean The following variable is exported as UEFI specification defines: SignatureSupport: array of GUIDs representing the type of signatures supported by the platform firmware Signed-off-by: AKASHI Takahiro --- lib/efi_loader/efi_setup.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/lib/efi_loader/efi_setup.c b/lib/efi_loader/efi_setup.c index b458093dfbd5..1b648c84673a 100644 --- a/lib/efi_loader/efi_setup.c +++ b/lib/efi_loader/efi_setup.c @@ -82,6 +82,39 @@ out: return ret; } +#ifdef CONFIG_EFI_SECURE_BOOT +/** + * efi_init_secure_boot - initialize secure boot state + * + * Return: EFI_SUCCESS on success, status code (negative) on error + */ +static efi_status_t efi_init_secure_boot(void) +{ + efi_guid_t signature_types[] = { + EFI_CERT_SHA256_GUID, + EFI_CERT_X509_GUID, + }; + efi_status_t ret; + + /* TODO: read-only */ + ret = EFI_CALL(efi_set_variable(L"SignatureSupport", + &efi_global_variable_guid, + EFI_VARIABLE_BOOTSERVICE_ACCESS + | EFI_VARIABLE_RUNTIME_ACCESS, + sizeof(signature_types), + &signature_types)); + if (ret != EFI_SUCCESS) + printf("EFI: cannot initialize SignatureSupport variable\n"); + + return ret; +} +#else +static efi_status_t efi_init_secure_boot(void) +{ + return EFI_SUCCESS; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ + /** * efi_init_obj_list() - Initialize and populate EFI object list * @@ -127,6 +160,11 @@ efi_status_t efi_init_obj_list(void) if (ret != EFI_SUCCESS) goto out; + /* Secure boot */ + ret = efi_init_secure_boot(); + if (ret != EFI_SUCCESS) + goto out; + /* Indicate supported runtime services */ ret = efi_init_runtime_supported(); if (ret != EFI_SUCCESS) From patchwork Tue Apr 14 02:51:46 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270040 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=gDzvnMel; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VT13FHQz9sPF for ; Tue, 14 Apr 2020 12:54:44 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 36CD2818F1; Tue, 14 Apr 2020 04:54:23 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="gDzvnMel"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 170F081718; Tue, 14 Apr 2020 04:53:09 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pl1-x643.google.com (mail-pl1-x643.google.com [IPv6:2607:f8b0:4864:20::643]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 040D780917 for ; Tue, 14 Apr 2020 04:52:49 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pl1-x643.google.com with SMTP id ay1so4151295plb.0 for ; Mon, 13 Apr 2020 19:52:49 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=BU4/taGxhiR3uGZdGcbYt58w3J2PFHjWz/G3R/bv5aI=; b=gDzvnMel3LSCM0Amag7Y2fVekTAbNZg06R8OPr3P7bnKLYjScsozhBYRbHsnYUvNDU 6F2mkyHu82XKQoQsKhMRXiZGklmn7ckI0fVX6zLU+5oCJVFdGLk7sMxN2Us8HhfThwE9 /fQUtaKsYbhQBsiRpNfnWel5oZTPM/cTsiTaHJcg+jWKHVBDosPaSvRmq3xBhnJlYR14 wfu8E1GPdbJnuMda9x6BLrfTxC8Zlh45BbNR2hnTl/41tPr1ctfB7TpqkUMLjvmZK3n6 aAN8wWZB4gVWvfhV6L/PyfMX175mTFG/BWPqwBI+x51AXt76YdnT5nURENNhhHKvwK4C yEyQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=BU4/taGxhiR3uGZdGcbYt58w3J2PFHjWz/G3R/bv5aI=; b=njqY/ZroFiJHh9rHPtRN0mVqGkrriPPTRgJ3c9HR71JCwagPuqVPFbdf5kk0UwlusL 88o7Q6Z+k1JOE0XwNNuHUekYzN5pXITQmc/CBVL171OMzhmZRwtOnDV8wNa+jP9684Mb RpkVSOaeKxA4Ip+ETMl/Zk0O/XG1TJEhzbfnCMd6vcQpgBUsoSIq6B7kDja+N3z9firY 5ycDEVDXB4BtSoZXTCVT+E5EY1GO86SUH0JgbjhUn83LYxqM1KTgp1SxH1oTyt/ZoILQ NOMM64qEtZw9r+EXFc//+FEOmexmvkGikMi0q4jSbagqnIpC29hwPgsntOe2Qx/kZdEv +jOg== X-Gm-Message-State: AGi0Pubkev0GpZSibTXy1OKXPL6c5YGCD50Fp8I8faE0iq0xl9cPZm3j IUMGTxz9z+CFY28NcRNz9woJwA== X-Google-Smtp-Source: APiQypJJIRuyOUlElWozOtPb9q2q/UWprq3/Zvoq0OpNwNc5Bry6Tf9j3L1WdEc6+9kVurEZioxohw== X-Received: by 2002:a17:90a:e28e:: with SMTP id d14mr7214546pjz.29.1586832768310; Mon, 13 Apr 2020 19:52:48 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:47 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 09/17] cmd: env: use appropriate guid for authenticated UEFI variable Date: Tue, 14 Apr 2020 11:51:46 +0900 Message-Id: <20200414025154.27283-10-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean A signature database variable is associated with a specific guid. For convenience, if user doesn't supply any guid info, "env set|print -e" should complement it. Signed-off-by: AKASHI Takahiro --- cmd/nvedit_efi.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/cmd/nvedit_efi.c b/cmd/nvedit_efi.c index 8ea0da01283f..579cf430593c 100644 --- a/cmd/nvedit_efi.c +++ b/cmd/nvedit_efi.c @@ -41,6 +41,11 @@ static const struct { } efi_guid_text[] = { /* signature database */ {EFI_GLOBAL_VARIABLE_GUID, "EFI_GLOBAL_VARIABLE_GUID"}, + {EFI_IMAGE_SECURITY_DATABASE_GUID, "EFI_IMAGE_SECURITY_DATABASE_GUID"}, + /* certificate type */ + {EFI_CERT_SHA256_GUID, "EFI_CERT_SHA256_GUID"}, + {EFI_CERT_X509_GUID, "EFI_CERT_X509_GUID"}, + {EFI_CERT_TYPE_PKCS7_GUID, "EFI_CERT_TYPE_PKCS7_GUID"}, }; /* "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" */ @@ -525,9 +530,9 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) if (*ep != ',') return CMD_RET_USAGE; + /* 0 should be allowed for delete */ size = simple_strtoul(++ep, NULL, 16); - if (!size) - return CMD_RET_FAILURE; + value_on_memory = true; } else if (!strcmp(argv[0], "-v")) { verbose = true; @@ -539,8 +544,13 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) return CMD_RET_USAGE; var_name = argv[0]; - if (default_guid) - guid = efi_global_variable_guid; + if (default_guid) { + if (!strcmp(var_name, "db") || !strcmp(var_name, "dbx") || + !strcmp(var_name, "dbt")) + guid = efi_guid_image_security_database; + else + guid = efi_global_variable_guid; + } if (verbose) { printf("GUID: %s\n", efi_guid_to_str((const efi_guid_t *) From patchwork Tue Apr 14 02:51:47 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270038 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=w/59yA/K; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VSW3fnyz9sPF for ; Tue, 14 Apr 2020 12:54:19 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 0F6C5818C7; Tue, 14 Apr 2020 04:53:45 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="w/59yA/K"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 913D18181D; Tue, 14 Apr 2020 04:53:06 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pg1-x543.google.com (mail-pg1-x543.google.com [IPv6:2607:f8b0:4864:20::543]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 1F56E815F4 for ; Tue, 14 Apr 2020 04:52:53 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pg1-x543.google.com with SMTP id i3so1355625pgk.1 for ; Mon, 13 Apr 2020 19:52:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=z9WKq7An79xVtH0pjdUXYx2kh/5nRcMJ92S5nAdyH9E=; b=w/59yA/KeI+ctg+mzha+iPnmpGe3uJvsX+KJD+jBe1ZbI3mhkGdG7fjWfTuZeHZEFE VYMEI4xAgsZv3FiacT8cGyUylBJlXEBe4+6JLq9f5eyc73MVuiSY47wXGy7FwPmE/8np EQORc5QQnq71ZEdb+p3hiCDINzS4ZUFjnRtTtsRqyqz4OVlxWuK2nlvjshlW1oK4ovLd mLAQUXniC9R2HCpfrj8uv0JHCgE/dTxRs888hFaBhDlU3gL3xuCtT0oJE+avXl6ikRtI QjMngrbFhkH2tOQQVNlxql1KQVVGhdrCI7rHalS/snmd2dAPxOkqU3wyCGGP9QQthzYe UfUA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=z9WKq7An79xVtH0pjdUXYx2kh/5nRcMJ92S5nAdyH9E=; b=c351L3uH5C2rOc5tyqnSzQmSu5O2P5crf4qEGvCzNln1TIBWGW00odBlnJM8jnpKfh 7pdp4RV+hUgi+H1EQBHMG8cgMRKZTDt5PLqS8c4z8NjLY3EUUjhd7y6/IVRvuUc4M++y 8shGKz+6If7e30dma63Lq2q+1Fr9sUPpLxEN4gV5Ti2mbvk1rPxGYvEhAvfdFteA550r z3oDjHjCMoY99ZM2ZoH4e/cGxp3YbEnCAyFULgAZjQeyDWx0au/20XrnCUcLu8rt/g5P S/eEwi8OD6bLjTXgqiP+2NsqJM5BZUdglnWPiQC+vaMLYGSGtpsOyLOK2ZeqLFJOvJAb YAOg== X-Gm-Message-State: AGi0PuY9hlS9Eraxx7tZsntFje5btfjENxS7RojD2/HG4E+E+UtxDwAp BrWrJ/ceLpNrdwUZDTRZRZ7vkA== X-Google-Smtp-Source: APiQypJkuE4W0mHCyXV4/uKb8x7kfcpODowjI8LRSaA50OcllsRqC3aCkNZTQsgcNWoQGkgrXSapsg== X-Received: by 2002:a63:1806:: with SMTP id y6mr12922555pgl.407.1586832771441; Mon, 13 Apr 2020 19:52:51 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.48 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:50 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 10/17] cmd: env: add "-at" option to "env set -e" command Date: Tue, 14 Apr 2020 11:51:47 +0900 Message-Id: <20200414025154.27283-11-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean With "-at" option, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS will be passed to SetVariable() to authenticate the variable. Signed-off-by: AKASHI Takahiro --- cmd/nvedit.c | 5 +++-- cmd/nvedit_efi.c | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd/nvedit.c b/cmd/nvedit.c index 81d94cd193c6..966c13405956 100644 --- a/cmd/nvedit.c +++ b/cmd/nvedit.c @@ -1417,7 +1417,7 @@ static char env_help_text[] = #endif #endif #if defined(CONFIG_CMD_NVEDIT_EFI) - "env set -e [-nv][-bs][-rt][-a][-i addr,size][-v] name [arg ...]\n" + "env set -e [-nv][-bs][-rt][-at][-a][-i addr,size][-v] name [arg ...]\n" " - set UEFI variable; unset if '-i' or 'arg' not specified\n" #endif "env set [-f] name [arg ...]\n"; @@ -1479,13 +1479,14 @@ U_BOOT_CMD_COMPLETE( setenv, CONFIG_SYS_MAXARGS, 0, do_env_set, "set environment variables", #if defined(CONFIG_CMD_NVEDIT_EFI) - "-e [-guid guid][-nv][-bs][-rt][-a][-v]\n" + "-e [-guid guid][-nv][-bs][-rt][-at][-a][-v]\n" " [-i addr,size name], or [name [value ...]]\n" " - set UEFI variable 'name' to 'value' ...'\n" " \"-guid\": set vendor guid\n" " \"-nv\": set non-volatile attribute\n" " \"-bs\": set boot-service attribute\n" " \"-rt\": set runtime attribute\n" + " \"-at\": set time-based authentication attribute\n" " \"-a\": append-write\n" " \"-i addr,size\": use as variable's value\n" " \"-v\": verbose message\n" diff --git a/cmd/nvedit_efi.c b/cmd/nvedit_efi.c index 579cf430593c..837e39e02179 100644 --- a/cmd/nvedit_efi.c +++ b/cmd/nvedit_efi.c @@ -458,7 +458,7 @@ out: * Return: CMD_RET_SUCCESS on success, or CMD_RET_RET_FAILURE * * This function is for "env set -e" or "setenv -e" command: - * => env set -e [-guid guid][-nv][-bs][-rt][-a][-v] + * => env set -e [-guid guid][-nv][-bs][-rt][-at][-a][-v] * [-i address,size] var, or * var [value ...] * Encode values specified and set given UEFI variable. @@ -517,6 +517,9 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) attributes |= EFI_VARIABLE_RUNTIME_ACCESS; } else if (!strcmp(argv[0], "-nv")) { attributes |= EFI_VARIABLE_NON_VOLATILE; + } else if (!strcmp(argv[0], "-at")) { + attributes |= + EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS; } else if (!strcmp(argv[0], "-a")) { attributes |= EFI_VARIABLE_APPEND_WRITE; } else if (!strcmp(argv[0], "-i")) { From patchwork Tue Apr 14 02:51:48 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270041 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=x0TqhAYI; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VTF45kCz9s71 for ; Tue, 14 Apr 2020 12:54:56 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 8FB0181469; Tue, 14 Apr 2020 04:54:26 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="x0TqhAYI"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 1BDDD8160C; Tue, 14 Apr 2020 04:53:16 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1041.google.com (mail-pj1-x1041.google.com [IPv6:2607:f8b0:4864:20::1041]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 1983C81864 for ; Tue, 14 Apr 2020 04:52:56 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1041.google.com with SMTP id mn19so4629514pjb.0 for ; Mon, 13 Apr 2020 19:52:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=3ykp2npn2MmGaWN++2ZU/TvGjn0jEytwBNATHBV25go=; b=x0TqhAYIGZ6k9MbFIScPZXPdlPwcwH0++FSxwOva9aiwCpxA7xgi4hfK/QeLidhkGV KyZSlnFWZbqHzuU3o1tYHfZR4ve5QuKjOkANf0mUv8jWfBjdqPzryGV6S+aDzuMo3YQt N8KIXyj64cbaGgnm/7sRcPSZj4IAzrhGg8/VG4I9tx+u7l2rVyiaNjaIaL6BFlSxI8gl 9zkkJYGiKv7RGOeiDmZ7pfN482dcauGyRiXjcVST/L+jpKrWmLLryqAnAArmSnjrZEGk v5th8NaF9Kd8gM39LgzjcSGAc6WigZxtA/HHImuC48CHsi2x/6N8luw0YYmjoBiUYXaf vlwg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=3ykp2npn2MmGaWN++2ZU/TvGjn0jEytwBNATHBV25go=; b=OPhaVPd5EUZL2P8foF/SeJMIiH1uQYcosXEtPsD23dG6jXQ1ty1ptA+fHFdhE8hx3p 8P8egf1p8VMfZ79X9n4s8vCraICqSdrsOSeKsYD5cTf23yoqaJzNV58lhoKHCFDsC/NB qOFIrpU+LqgoOBEdG5ajh58jlsI3g1FJx+H/7UuZ/0cnDQZllXr7q9lrr/Jzt/dUbXqm QrKkSr5xB27Wrj/ssyVJCH12yeJ0amtYagoc93QnhK87g2Joz9JE7QmRjpCdjH2FWTPy vECSrikOGjUxIHs60H8nvjP9thxhN5JyCyHurGPY/9iFpE6db2fRfVnhjMamVW9aJvPD zFyw== X-Gm-Message-State: AGi0PubJWUYKd6QpyoJnxNt+KxZRN9t9DiChoqOrACg8IBwwGkI/zCNy lrLq6RsPrAUHrm4ah5Erhmx1lzCHR6Q= X-Google-Smtp-Source: APiQypIAKCg5pHYWMtVfulBk1nS6mrMN3UrrM8dDIkgWgkm5ckILQH+QkYmgqh1ymwqod5qqoCEpoA== X-Received: by 2002:a17:902:b489:: with SMTP id y9mr18317658plr.67.1586832774570; Mon, 13 Apr 2020 19:52:54 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.51 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:54 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 11/17] cmd: efidebug: add "test bootmgr" sub-command Date: Tue, 14 Apr 2020 11:51:48 +0900 Message-Id: <20200414025154.27283-12-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean This sub-command will be used to test image authentication, in particular, a case where efi_load_image() failed with EFI_SECURITY_VIOLATION but we still want to try efi_start_image(). We won't run such a case under normal bootmgr because it simply refuses to call efi_start_image() if anything but EFI_SUCCESS is returned when loading an image. Signed-off-by: AKASHI Takahiro --- cmd/efidebug.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/cmd/efidebug.c b/cmd/efidebug.c index bb7c13d6a1ce..9769aeeac58b 100644 --- a/cmd/efidebug.c +++ b/cmd/efidebug.c @@ -1087,6 +1087,78 @@ static int do_efi_boot_opt(cmd_tbl_t *cmdtp, int flag, return cp->cmd(cmdtp, flag, argc, argv); } +/** + * do_efi_test_bootmgr() - run simple bootmgr for test + * + * @cmdtp: Command table + * @flag: Command flag + * @argc: Number of arguments + * @argv: Argument array + * Return: CMD_RET_SUCCESS on success, + * CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure + * + * Implement efidebug "test bootmgr" sub-command. + * Run simple bootmgr for test. + * + * efidebug test bootmgr + */ +static int do_efi_test_bootmgr(cmd_tbl_t *cmdtp, int flag, + int argc, char * const argv[]) +{ + efi_handle_t image; + efi_uintn_t exit_data_size = 0; + u16 *exit_data = NULL; + efi_status_t ret; + + ret = efi_bootmgr_load(&image); + printf("efi_bootmgr_load() returned: %ld\n", ret & ~EFI_ERROR_MASK); + + /* We call efi_start_image() even if error for test purpose. */ + ret = EFI_CALL(efi_start_image(image, &exit_data_size, &exit_data)); + printf("efi_start_image() returned: %ld\n", ret & ~EFI_ERROR_MASK); + if (ret && exit_data) + efi_free_pool(exit_data); + + efi_restore_gd(); + + return CMD_RET_SUCCESS; +} + +static cmd_tbl_t cmd_efidebug_test_sub[] = { + U_BOOT_CMD_MKENT(bootmgr, CONFIG_SYS_MAXARGS, 1, do_efi_test_bootmgr, + "", ""), +}; + +/** + * do_efi_test() - manage UEFI load options + * + * @cmdtp: Command table + * @flag: Command flag + * @argc: Number of arguments + * @argv: Argument array + * Return: CMD_RET_SUCCESS on success, + * CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure + * + * Implement efidebug "test" sub-command. + */ +static int do_efi_test(cmd_tbl_t *cmdtp, int flag, + int argc, char * const argv[]) +{ + cmd_tbl_t *cp; + + if (argc < 2) + return CMD_RET_USAGE; + + argc--; argv++; + + cp = find_cmd_tbl(argv[0], cmd_efidebug_test_sub, + ARRAY_SIZE(cmd_efidebug_test_sub)); + if (!cp) + return CMD_RET_USAGE; + + return cp->cmd(cmdtp, flag, argc, argv); +} + static cmd_tbl_t cmd_efidebug_sub[] = { U_BOOT_CMD_MKENT(boot, CONFIG_SYS_MAXARGS, 1, do_efi_boot_opt, "", ""), U_BOOT_CMD_MKENT(devices, CONFIG_SYS_MAXARGS, 1, do_efi_show_devices, @@ -1101,6 +1173,8 @@ static cmd_tbl_t cmd_efidebug_sub[] = { "", ""), U_BOOT_CMD_MKENT(tables, CONFIG_SYS_MAXARGS, 1, do_efi_show_tables, "", ""), + U_BOOT_CMD_MKENT(test, CONFIG_SYS_MAXARGS, 1, do_efi_test, + "", ""), }; /** @@ -1170,7 +1244,9 @@ static char efidebug_help_text[] = "efidebug memmap\n" " - show UEFI memory map\n" "efidebug tables\n" - " - show UEFI configuration tables\n"; + " - show UEFI configuration tables\n" + "efidebug test bootmgr\n" + " - run simple bootmgr for test\n"; #endif U_BOOT_CMD( From patchwork Tue Apr 14 02:51:49 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270039 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=unJe0hgN; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VSm4dD8z9sPF for ; Tue, 14 Apr 2020 12:54:31 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 45FEF817EA; Tue, 14 Apr 2020 04:54:20 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="unJe0hgN"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 800BE81834; Tue, 14 Apr 2020 04:53:17 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pl1-x62b.google.com (mail-pl1-x62b.google.com [IPv6:2607:f8b0:4864:20::62b]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 75DB88180B for ; Tue, 14 Apr 2020 04:52:59 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pl1-x62b.google.com with SMTP id g2so4145438plo.3 for ; Mon, 13 Apr 2020 19:52:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=l0bYsofpB3kS/MbDSssZQu6CdYk5/RkMnuCar6OaxRg=; b=unJe0hgNlw7Whxm0BnFmzMDrotmdbJKxnaJHTlNcxiA1oXZqtgvfDGVB0uf6E+G/jQ SwnGEzj0iyb2LcE5JNJiqfA1+tRu8gF50uL8kWAVKaPWPJi0s/mSxYkaL0zgQWeAr9/F spDkwxQE9PPiXbwFipDzmWiKd+P1bgqkBk6zpaewWUwpJtqrIahBRE2KbhoejyWPsTCp W6MM56tTFdgmxIq+xPqAldD5szh4BtSgd3y+M/0iLr8Bnutx7oigoFg7rbT2BNU+dqjG oD7kTxvsLp/Ri7KXstMBkU5Rneo2EkkHZW8ORrxlteHPDNJtL6jzfqSYeKGK/fdraeXK q02w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=l0bYsofpB3kS/MbDSssZQu6CdYk5/RkMnuCar6OaxRg=; b=E+drkXxNIHAoiXVL3V646+x2ItqKh5zgVMNy//52ItZ2Ir5ah4VrZFrZBvv4J3bZAE lOQX1SkCs+emS2tKVL7kB8Z7/hiO06jpKFbiW1NtCwYeTIJGgnjXMEU3P/e5y/WMlzV9 RE1Gdh/CVcabV+lZDQVua9qENRaamnmwqxqSBfyDhNfYwS2vscVSizxxkDahpLxbr6JM 4sgvkKXv5R8gwgHlEygJeuN30W3MCh1c6eaHmpWM2CYoowZzH2Q2U9sfTotS3KrEKa/a DHcEkWxLDbKxrc/1eVI7ZrJL0qSQNVUvSjXYzVb0HapEI4tGTGX1crmf/M8htKf9uclQ FfDg== X-Gm-Message-State: AGi0PubuCnMmpqpboKgk95aB/daJ28qqskf2RTNO0aMv2gJf87bFbJGp c9zvC24+97w2O/xn5c2ZimMkxA== X-Google-Smtp-Source: APiQypLgmbWHbr1OUumQOHv51n1lK9PzJgJRq3xah9Eh6WLCBPEGQuTUkTqg8I9Yh99dV1lXRuaNAg== X-Received: by 2002:a17:902:ba14:: with SMTP id j20mr19330374pls.69.1586832777909; Mon, 13 Apr 2020 19:52:57 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:52:57 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 12/17] efi_loader, pytest: set up secure boot environment Date: Tue, 14 Apr 2020 11:51:49 +0900 Message-Id: <20200414025154.27283-13-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean A fixture for UEFI secure boot tests (image authentication and variable authentication) is defined. A small file system with test data in a single partition formatted in fat is created. This test requires efitools v1.5.2 or later. If the system's efitools is older, you have to build it on your own and define EFITOOLS_PATH. Signed-off-by: AKASHI Takahiro --- test/py/README.md | 8 ++ test/py/tests/test_efi_secboot/conftest.py | 151 +++++++++++++++++++++ test/py/tests/test_efi_secboot/defs.py | 21 +++ 3 files changed, 180 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/conftest.py create mode 100644 test/py/tests/test_efi_secboot/defs.py diff --git a/test/py/README.md b/test/py/README.md index 3cbe01b73e28..aa8a5607b064 100644 --- a/test/py/README.md +++ b/test/py/README.md @@ -37,7 +37,15 @@ will be required. The following is an incomplete list: | openssl | | sudo OR guestmount | | e2fsprogs | +| util-linux | +| coreutils | | dosfstools | +| efitools | +| mount | +| mtools | +| sbsigntool | +| udisks2 | + Please use the apporirate commands for your distribution to match these tools up with the package that provides them. diff --git a/test/py/tests/test_efi_secboot/conftest.py b/test/py/tests/test_efi_secboot/conftest.py new file mode 100644 index 000000000000..e542fef6e819 --- /dev/null +++ b/test/py/tests/test_efi_secboot/conftest.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro + +import os +import os.path +import pytest +import re +from subprocess import call, check_call, check_output, CalledProcessError +from defs import * + +# from test/py/conftest.py +def tool_is_in_path(tool): + for path in os.environ["PATH"].split(os.pathsep): + fn = os.path.join(path, tool) + if os.path.isfile(fn) and os.access(fn, os.X_OK): + return True + return False + +# +# Fixture for UEFI secure boot test +# +@pytest.fixture(scope='session') +def efi_boot_env(request, u_boot_config): + """Set up a file system to be used in UEFI secure boot test. + + Args: + request: Pytest request object. + u_boot_config: U-boot configuration. + + Return: + A path to disk image to be used for testing + """ + global HELLO_PATH + + image_path = u_boot_config.persistent_data_dir + image_path = image_path + '/' + EFI_SECBOOT_IMAGE_NAME + image_size = EFI_SECBOOT_IMAGE_SIZE + part_size = EFI_SECBOOT_PART_SIZE + fs_type = EFI_SECBOOT_FS_TYPE + + if HELLO_PATH == '': + HELLO_PATH = u_boot_config.build_dir + '/lib/efi_loader/helloworld.efi' + + try: + non_root = tool_is_in_path('udisksctl') + + # create a disk/partition + check_call('dd if=/dev/zero of=%s bs=1MiB count=%d' + % (image_path, image_size), shell=True) + check_call('sgdisk %s -n 1:0:+%dMiB' + % (image_path, part_size), shell=True) + # create a file system + check_call('dd if=/dev/zero of=%s.tmp bs=1MiB count=%d' + % (image_path, part_size), shell=True) + check_call('mkfs -t %s %s.tmp' % (fs_type, image_path), shell=True) + check_call('dd if=%s.tmp of=%s bs=1MiB seek=1 count=%d conv=notrunc' + % (image_path, image_path, 1), shell=True) + check_call('rm %s.tmp' % image_path, shell=True) + if non_root: + out_data = check_output('udisksctl loop-setup -f %s -o %d' + % (image_path, 1048576), shell=True).decode() + m = re.search('(?<= as )(.*)\.', out_data) + loop_dev = m.group(1) + # print 'loop device is: %s' % loop_dev + out_data = check_output('udisksctl info -b %s' + % loop_dev, shell=True).decode() + m = re.search('MountPoints:[ \t]+(.*)', out_data) + mnt_point = m.group(1) + else: + loop_dev = check_output('sudo losetup -o 1MiB --sizelimit %dMiB --show -f %s | tr -d "\n"' + % (part_size, image_path), shell=True).decode() + mnt_point = '/mnt' + check_output('sudo mount -t %s -o umask=000 %s %s' + % (fs_type, loop_dev, mnt_point), shell=True) + + # print 'mount point is: %s' % mnt_point + + # suffix + # *.key: RSA private key in PEM + # *.crt: X509 certificate (self-signed) in PEM + # *.esl: signature list + # *.hash: message digest of image as signature list + # *.auth: signed signature list in signature database format + # *.efi: UEFI image + # *.efi.signed: signed UEFI image + + # Create signature database + ## PK + check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_PK/ -keyout PK.key -out PK.crt -nodes -days 365' + % mnt_point, shell=True) + check_call('cd %s; %scert-to-efi-sig-list -g %s PK.crt PK.esl; %ssign-efi-sig-list -c PK.crt -k PK.key PK PK.esl PK.auth' + % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH), + shell=True) + ## PK_null for deletion + check_call('cd %s; sleep 2; touch PK_null.esl; %ssign-efi-sig-list -c PK.crt -k PK.key PK PK_null.esl PK_null.auth' + % (mnt_point, EFITOOLS_PATH), shell=True) + ## KEK + check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_KEK/ -keyout KEK.key -out KEK.crt -nodes -days 365' + % mnt_point, shell=True) + check_call('cd %s; %scert-to-efi-sig-list -g %s KEK.crt KEK.esl; %ssign-efi-sig-list -c PK.crt -k PK.key KEK KEK.esl KEK.auth' + % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH), + shell=True) + ## db + check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db/ -keyout db.key -out db.crt -nodes -days 365' + % mnt_point, shell=True) + check_call('cd %s; %scert-to-efi-sig-list -g %s db.crt db.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db.esl db.auth' + % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH), + shell=True) + ## db1 + check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db1/ -keyout db1.key -out db1.crt -nodes -days 365' + % mnt_point, shell=True) + check_call('cd %s; %scert-to-efi-sig-list -g %s db1.crt db1.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db1.esl db1.auth' + % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH), + shell=True) + ## db1-update + check_call('cd %s; %ssign-efi-sig-list -a -c KEK.crt -k KEK.key db db1.esl db1-update.auth' + % (mnt_point, EFITOOLS_PATH), shell=True) + ## dbx + check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_dbx/ -keyout dbx.key -out dbx.crt -nodes -days 365' + % mnt_point, shell=True) + check_call('cd %s; %scert-to-efi-sig-list -g %s dbx.crt dbx.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key dbx dbx.esl dbx.auth' + % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH), + shell=True) + + # Copy image + check_call('cp %s %s' % (HELLO_PATH, mnt_point), shell=True) + + ## Sign image + check_call('cd %s; sbsign --key db.key --cert db.crt helloworld.efi' + % mnt_point, shell=True) + ## Digest image + check_call('cd %s; %shash-to-efi-sig-list helloworld.efi db_hello.hash; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db_hello.hash db_hello.auth' + % (mnt_point, EFITOOLS_PATH, EFITOOLS_PATH), + shell=True) + + if non_root: + check_call('udisksctl unmount -b %s' % loop_dev, shell=True) + # not needed + # check_call('udisksctl loop-delete -b %s' % loop_dev, shell=True) + else: + check_call('sudo umount %s' % loop_dev, shell=True) + check_call('sudo losetup -d %s' % loop_dev, shell=True) + + except CalledProcessError as e: + pytest.skip('Setup failed: %s' % e.cmd) + return + else: + yield image_path + finally: + call('rm -f %s' % image_path, shell=True) diff --git a/test/py/tests/test_efi_secboot/defs.py b/test/py/tests/test_efi_secboot/defs.py new file mode 100644 index 000000000000..d6222809c547 --- /dev/null +++ b/test/py/tests/test_efi_secboot/defs.py @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: GPL-2.0+ + +# Disk image name +EFI_SECBOOT_IMAGE_NAME='test_efi_secboot.img' + +# Size in MiB +EFI_SECBOOT_IMAGE_SIZE=16 +EFI_SECBOOT_PART_SIZE=8 + +# Partition file system type +EFI_SECBOOT_FS_TYPE='vfat' + +# Owner guid +GUID='11111111-2222-3333-4444-123456789abc' + +# v1.5.1 or earlier of efitools has a bug in sha256 calculation, and +# you need build a newer version on your own. +EFITOOLS_PATH='' + +# Hello World application for sandbox +HELLO_PATH='' From patchwork Tue Apr 14 02:51:50 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270042 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=HihMcUeP; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VTW6Mg8z9s71 for ; Tue, 14 Apr 2020 12:55:11 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id BC43C81888; Tue, 14 Apr 2020 04:54:29 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="HihMcUeP"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 88DF88180B; Tue, 14 Apr 2020 04:53:21 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x1042.google.com (mail-pj1-x1042.google.com [IPv6:2607:f8b0:4864:20::1042]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id C3D6081902 for ; Tue, 14 Apr 2020 04:53:02 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x1042.google.com with SMTP id z9so4622371pjd.2 for ; Mon, 13 Apr 2020 19:53:02 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=4NtT1qa2wUvKO8sp0UYIY6mno1qiDQphdo3wMaq2dHw=; b=HihMcUePgSrFMfLbEFKneZkznPDtcbex5ROvfYe1MWPrwlPeg4FALy2JD22EQMm+My Fbxvo7yq4m9ZWbZy7/ZfBh+USAjuJXKAS24xiZt+xYxXxOIsCcuvhfKv3TuNWqhX23E9 yM6/IuBisvTsyyFA5KjU07aQkBU1iLskHMtttWZhXsUnVoRgtN2AP20dKEiY9XeiKc/0 GWVOm+E28GGTh1XtoUgUDuHeAX+xk5JGdUNjGF0pHZi98hlCR2y7K5Eo9t7cO+kh0JmH 0fix96sahR4aBNVTDvMdkaLigweM8xK2OJ/T8HehlcNxvgZ3NYfIpzQYj28JereIS2rg Felw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=4NtT1qa2wUvKO8sp0UYIY6mno1qiDQphdo3wMaq2dHw=; b=SXCZF87HjYlw796hYMEnXl2mZxZ8jRnPEV+popIt529Vs+lRSOHPBaRGwtd+XtbOwD /uQExYAU4MCQKQFnOlJQ3wmEM0CLBi/G6z38OqBuF46RLlv0Pq7uZImX3FMBPkA5aMYB XI3AWE+hHRu9gntAkXzQMwPosB2VIp9ddr1RsNGVuS7ZVlvIxCn8oF+yS5g8CtCjwPpM OnJe2L9X0WCB/dsuUDqUp4wFn2DniTwTW5SVH4lemtff9dpk+oxmxyYXEsEQbJJByk4v xl26sH/+YFkW6KhgajMcelCUfYXDM1pZqO1JiEuNQnUORkAp0LKJF1Ylh0lEx28C9UTO 8OzA== X-Gm-Message-State: AGi0PuZp5gtt+lVnL7BP+kBpE66OXaIZvqRRig4GOQNHQf3o68B/ka0H mWJtdKGN8MpTEPCTSKatC/woKg== X-Google-Smtp-Source: APiQypJxJfai+2F1y+nUC6BKkfsHJ2ibMa7my8BvSNey5nx/saJXSpULetXYB0x5fYYSi8oJ3CXopg== X-Received: by 2002:a17:902:9f81:: with SMTP id g1mr20290079plq.269.1586832781151; Mon, 13 Apr 2020 19:53:01 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.52.58 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:53:00 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 13/17] efi_loader, pytest: add UEFI secure boot tests (authenticated variables) Date: Tue, 14 Apr 2020 11:51:50 +0900 Message-Id: <20200414025154.27283-14-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean Provide a couple of test cases for variable authentication. Signed-off-by: AKASHI Takahiro --- .../py/tests/test_efi_secboot/test_authvar.py | 282 ++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py diff --git a/test/py/tests/test_efi_secboot/test_authvar.py b/test/py/tests/test_efi_secboot/test_authvar.py new file mode 100644 index 000000000000..55dcaa95f1ea --- /dev/null +++ b/test/py/tests/test_efi_secboot/test_authvar.py @@ -0,0 +1,282 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro +# +# U-Boot UEFI: Variable Authentication Test + +""" +This test verifies variable authentication +""" + +import pytest +import re +from defs import * + +@pytest.mark.boardspec('sandbox') +@pytest.mark.buildconfigspec('efi_secure_boot') +@pytest.mark.buildconfigspec('cmd_fat') +@pytest.mark.buildconfigspec('cmd_nvedit_efi') +@pytest.mark.slow +class TestEfiAuthVar(object): + def test_efi_var_auth1(self, u_boot_console, efi_boot_env): + """ + Test Case 1 - Install signature database + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 1a'): + # Test Case 1a, Initial secure state + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'printenv -e SecureBoot']) + assert('00000000: 00' in ''.join(output)) + + output = u_boot_console.run_command( + 'printenv -e SetupMode') + assert('00000000: 01' in output) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, PK without AUTHENTICATED_WRITE_ACCESS + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -i 4000000,$filesize PK']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 1c'): + # Test Case 1c, install PK + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'printenv -e -n PK']) + assert(re.search('PK:', ''.join(output))) + + output = u_boot_console.run_command( + 'printenv -e SecureBoot') + assert('00000000: 01' in output) + output = u_boot_console.run_command( + 'printenv -e SetupMode') + assert('00000000: 00' in output) + + with u_boot_console.log.section('Test Case 1d'): + # Test Case 1d, db/dbx without KEK + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize dbx']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 1e'): + # Test Case 1e, install KEK + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -i 4000000,$filesize KEK']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'printenv -e -n KEK']) + assert(re.search('KEK:', ''.join(output))) + + output = u_boot_console.run_command( + 'printenv -e SecureBoot') + assert('00000000: 01' in output) + + with u_boot_console.log.section('Test Case 1f'): + # Test Case 1f, install db + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + output = u_boot_console.run_command( + 'printenv -e SecureBoot') + assert('00000000: 01' in output) + + with u_boot_console.log.section('Test Case 1g'): + # Test Case 1g, install dbx + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + output = u_boot_console.run_command( + 'printenv -e SecureBoot') + assert('00000000: 01' in output) + + def test_efi_var_auth2(self, u_boot_console, efi_boot_env): + """ + Test Case 2 - Update database by overwriting + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 2a'): + # Test Case 2a, update without AUTHENTICATED_WRITE_ACCESS + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db1.auth', + 'setenv -e -nv -bs -rt -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 2b'): + # Test Case 2b, update without correct signature + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.esl', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 2c'): + # Test Case 2c, update with correct signature + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db1.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + def test_efi_var_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - Append database + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 3a'): + # Test Case 3a, update without AUTHENTICATED_WRITE_ACCESS + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db1.auth', + 'setenv -e -nv -bs -rt -a -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 3b'): + # Test Case 3b, update without correct signature + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.esl', + 'setenv -e -nv -bs -rt -at -a -i 4000000,$filesize db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + + with u_boot_console.log.section('Test Case 3c'): + # Test Case 3c, update with correct signature + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db1.auth', + 'setenv -e -nv -bs -rt -at -a -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + def test_efi_var_auth4(self, u_boot_console, efi_boot_env): + """ + Test Case 4 - Delete database without authentication + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 4a'): + # Test Case 4a, update without AUTHENTICATED_WRITE_ACCESS + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + with u_boot_console.log.section('Test Case 4b'): + # Test Case 4b, update without correct signature/data + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt -at db', + 'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + + def test_efi_var_auth5(self, u_boot_console, efi_boot_env): + """ + Test Case 5 - Uninstall(delete) PK + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 5a'): + # Test Case 5a, Uninstall PK without correct signature + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'printenv -e -n PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 PK_null.esl', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'printenv -e -n PK']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) + + with u_boot_console.log.section('Test Case 5b'): + # Test Case 5b, Uninstall PK with correct signature + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 PK_null.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK', + 'printenv -e -n PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('\"PK\" not defined', ''.join(output))) + + output = u_boot_console.run_command( + 'printenv -e SecureBoot') + assert('00000000: 00' in output) + output = u_boot_console.run_command( + 'printenv -e SetupMode') + assert('00000000: 01' in output) From patchwork Tue Apr 14 02:51:51 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270043 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=bV3Jbwry; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VTl61Ftz9s71 for ; Tue, 14 Apr 2020 12:55:22 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 54D4F8180B; Tue, 14 Apr 2020 04:54:33 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="bV3Jbwry"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 38C768128F; Tue, 14 Apr 2020 04:53:20 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pj1-x102f.google.com (mail-pj1-x102f.google.com [IPv6:2607:f8b0:4864:20::102f]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id E6A3F81824 for ; Tue, 14 Apr 2020 04:53:05 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pj1-x102f.google.com with SMTP id b7so4694681pju.0 for ; Mon, 13 Apr 2020 19:53:05 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=gihscCGb4kIN8BlCIHBH83wfX9PjttsTwL1Ap2CHOMc=; b=bV3Jbwry0nx85mD+YP7qR3SzSLVgZ9G2qA0nmD8GZDGxeSGvDmCmEewLFfXcqFR5ot DWTpEzi7upBRg+tqmDbpS0+qaQS2xj+RUV8UFvtReIKgQj9Bybb1EaAmxv6GlQQdJH83 H38Fs8oloM9HjTSc776pF9szTlTEf+uPKECAfmqFvpF3TE15jPdu4rcvXGdHldS+fr5F DEgGa1va/C2PzoWkp4tustKxZgF0FCCSRK3FV+aFOrOrp1e7pf0DTuN1cCU0At6Tofsh GI/k2YViGjM6Ukt5zrZ76ZbXTV+KHJLtSeoF+UprPvd6jTIY4c8tcv2g31kH4DxkqwbJ W2Ig== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=gihscCGb4kIN8BlCIHBH83wfX9PjttsTwL1Ap2CHOMc=; b=T63bmtqlFUj8kC1eb9BHxdTuBoPDxwM4ZRLWY1e4Hx8odnCSMYXxOW+Y8R7J8BFuit YJw+7xFpO0S+viA6ybxUP29YgDbQsUkSAsb9w8k9XyMOf17Ucrr+Wj7Fh24lMNSZuRbU hGrPbtgwMTqcNYId+gJfT6HUjghwgIS3VJFS3eIBTgBKt3JAIcFYVYQKgNS0x2btR0/M wcYIRwAmj6QBH+3Z2Gia1Q8tuoytp2PSzLffNEAmpWnQpxFCXIAL0FARwt8gmipxyXCA up8mVuC1+9lLEUtT4+i1V1AOSS0tD6t6TrpYUjZPaUSqmKI1eKFjqvUuhAINAIdVPsgk +E8Q== X-Gm-Message-State: AGi0PuYln3RP/VB/YFbLH56DEkvbME6TMey+jZ6S65prbN7yqdQ7U4av /t2P5mU9sDta6a0KeluS9D7snw== X-Google-Smtp-Source: APiQypLMV7rkDrk8yRstgidmR+2//zFL0UcawtyH2BdmtdETFFrOp8Onemr+x9ke+E5Y3C3OZjehyA== X-Received: by 2002:a17:90a:35f0:: with SMTP id r103mr22735232pjb.167.1586832784326; Mon, 13 Apr 2020 19:53:04 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.53.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:53:03 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 14/17] efi_loader, pytest: add UEFI secure boot tests (image) Date: Tue, 14 Apr 2020 11:51:51 +0900 Message-Id: <20200414025154.27283-15-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean Provide test cases for * image authentication for signed images (test_efi_secboot/test_signed.py) * image authentication for unsigned images (test_efi_secboot/test_unsigned.py) Signed-off-by: AKASHI Takahiro --- test/py/tests/test_efi_secboot/test_signed.py | 117 +++++++++++++++++ .../tests/test_efi_secboot/test_unsigned.py | 121 ++++++++++++++++++ 2 files changed, 238 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_signed.py create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.py diff --git a/test/py/tests/test_efi_secboot/test_signed.py b/test/py/tests/test_efi_secboot/test_signed.py new file mode 100644 index 000000000000..584282b338bc --- /dev/null +++ b/test/py/tests/test_efi_secboot/test_signed.py @@ -0,0 +1,117 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro +# +# U-Boot UEFI: Signed Image Authentication Test + +""" +This test verifies image authentication for signed images. +""" + +import pytest +import re +from defs import * + +@pytest.mark.boardspec('sandbox') +@pytest.mark.buildconfigspec('efi_secure_boot') +@pytest.mark.buildconfigspec('cmd_efidebug') +@pytest.mark.buildconfigspec('cmd_fat') +@pytest.mark.buildconfigspec('cmd_nvedit_efi') +@pytest.mark.slow +class TestEfiSignedImage(object): + def test_efi_signed_image_auth1(self, u_boot_console, efi_boot_env): + """ + Test Case 1 - authenticated by db + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 1a'): + # Test Case 1a, run signed image if no db/dbx + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'efidebug boot add 1 HELLO1 host 0:1 /helloworld.efi.signed ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, run unsigned image if no db/dbx + output = u_boot_console.run_command_list([ + 'efidebug boot add 2 HELLO2 host 0:1 /helloworld.efi ""', + 'efidebug boot next 2', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + with u_boot_console.log.section('Test Case 1c'): + # Test Case 1c, not authenticated by db + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 2', + 'bootefi bootmgr']) + assert(re.search('\'HELLO2\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 2', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) + + with u_boot_console.log.section('Test Case 1d'): + # Test Case 1d, authenticated by db + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + def test_efi_signed_image_auth2(self, u_boot_console, efi_boot_env): + """ + Test Case 2 - rejected by dbx + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 2a'): + # Test Case 2a, rejected by dbx + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize dbx', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot add 1 HELLO host 0:1 /helloworld.efi.signed ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) + + with u_boot_console.log.section('Test Case 2b'): + # Test Case 2b, rejected by dbx even if db allows + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) diff --git a/test/py/tests/test_efi_secboot/test_unsigned.py b/test/py/tests/test_efi_secboot/test_unsigned.py new file mode 100644 index 000000000000..22d849afb89b --- /dev/null +++ b/test/py/tests/test_efi_secboot/test_unsigned.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro +# +# U-Boot UEFI: Signed Image Authentication Test + +""" +This test verifies image authentication for unsigned images. +""" + +import pytest +import re +from defs import * + +@pytest.mark.boardspec('sandbox') +@pytest.mark.buildconfigspec('efi_secure_boot') +@pytest.mark.buildconfigspec('cmd_efidebug') +@pytest.mark.buildconfigspec('cmd_fat') +@pytest.mark.buildconfigspec('cmd_nvedit_efi') +@pytest.mark.slow +class TestEfiUnsignedImage(object): + def test_efi_unsigned_image_auth1(self, u_boot_console, efi_boot_env): + """ + Test Case 1 - rejected when not digest in db or dbx + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 1'): + # Test Case 1 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'efidebug boot add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) + + def test_efi_unsigned_image_auth2(self, u_boot_console, efi_boot_env): + """ + Test Case 2 - authenticated by digest in db + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 2'): + # Test Case 2 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db_hello.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'efidebug boot add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + def test_efi_unsigned_image_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - rejected by digest in dbx + """ + u_boot_console.restart_uboot() + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 3a'): + # Test Case 3a, rejected by dbx + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db_hello.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize dbx', + 'fatload host 0:1 4000000 KEK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK', + 'fatload host 0:1 4000000 PK.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'efidebug boot add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) + + with u_boot_console.log.section('Test Case 3b'): + # Test Case 3b, rejected by dbx even if db allows + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db_hello.auth', + 'setenv -e -nv -bs -rt -at -i 4000000,$filesize db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'efidebug boot add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + output = u_boot_console.run_command_list([ + 'efidebug boot next 1', + 'efidebug test bootmgr']) + assert(re.search('efi_start_image[(][)] returned: 26', + ''.join(output))) + assert(not re.search('Hello, world!', ''.join(output))) From patchwork Tue Apr 14 02:51:52 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270044 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=zTqAa8dY; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VTw6f0bz9s71 for ; Tue, 14 Apr 2020 12:55:32 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id 493F48196B; Tue, 14 Apr 2020 04:54:38 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="zTqAa8dY"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 9056A81834; Tue, 14 Apr 2020 04:53:22 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,UPPERCASE_50_75,URIBL_BLOCKED autolearn=no autolearn_force=no version=3.4.2 Received: from mail-pl1-x636.google.com (mail-pl1-x636.google.com [IPv6:2607:f8b0:4864:20::636]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 0193C8058D for ; Tue, 14 Apr 2020 04:53:08 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pl1-x636.google.com with SMTP id w3so4141374plz.5 for ; Mon, 13 Apr 2020 19:53:08 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=f/6kKNbNVm5Et1k6ciDE3DfNfzIyp+S7daDWO5DrKBo=; b=zTqAa8dYqoplAQXCUrS5t6Zlm3Ut23bSeIO9K4hY5sWd9ADWtSa6DKFNVCZXrt4wQt xlLzT/r3FipWQKhZ6V1eu+Y5sMemV5l6s+LRyiq9AyiNy38zavmHn2l8CqxYTodJghhW 0n6rc3AkTnjvdjzU6Ko11vDlfOWW7q/+DBsCujigygT8r9NfvGO6dK+OSuPfqx83tBps TYTs9N5yZqHokU55F+idJdUNf5HO1UnUXLCYVrmRjCV0g4Nj7nZqFMMXahXyo8PdNRBc hNrc3onbnoA95bbn9MuV5m0VrLl9D7JAmB0+EpoedP9R25RSGZFIBQ7G8K1jqfTf2lEJ oIag== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=f/6kKNbNVm5Et1k6ciDE3DfNfzIyp+S7daDWO5DrKBo=; b=AREPkoPcKxJtYi3Y1eAwmvDnCUinE5O+VyqSMbNnGEm9mMBLAbxpc5N3x1IKIstNct f+D2XqqYLTS9cK8/QjokwZ35zFvi7iQU3ldtJVxDpNHyctjwrzn9T3hCu8ATdpaWXq16 m5yS3t+w99wjQS2ZyW0qu4gXmRdeSIIXLc+/AjrNoJnvYQu9mAZEFNWeS5eW12knhf6y Y5sKzFbXWGf2KC6ipfe+jifh5EyAqJ7TCHFGatFOlLZSVMLkpXiYT3SFoXG9egtnq+us YaAlOcLsieeVFyi3UBveo5BCk4VuSWx4QI5o2F+zeo5cO3JY7xK2Q0aGJRNWYZJmoWiA tIkA== X-Gm-Message-State: AGi0PuYk6YtMzNT7F7XA50A8CvDq8J1DhVX68x9mgMP9uCvHGW0FH07+ 8iEJdBg8kWOYEpaBnN2mKB0Zjg== X-Google-Smtp-Source: APiQypKfBTo8YIN+vbLTMic9ioy/Q4zazaybH6cLKi+Rjmc9OwxAKgUFUknFRslBrT3JgyfWauCgGA== X-Received: by 2002:a17:902:7b96:: with SMTP id w22mr20609247pll.10.1586832787507; Mon, 13 Apr 2020 19:53:07 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.53.04 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:53:06 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 15/17] sandbox: add extra configurations for UEFI and related tests Date: Tue, 14 Apr 2020 11:51:52 +0900 Message-Id: <20200414025154.27283-16-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean Adding those extra configurations allows us to successfully run UEFI secure boot pytest on Travis CI. Signed-off-by: AKASHI Takahiro --- configs/sandbox64_defconfig | 3 +++ configs/sandbox_defconfig | 3 +++ 2 files changed, 6 insertions(+) diff --git a/configs/sandbox64_defconfig b/configs/sandbox64_defconfig index 8ca17d621bbf..60fbc9a89cc7 100644 --- a/configs/sandbox64_defconfig +++ b/configs/sandbox64_defconfig @@ -27,6 +27,7 @@ CONFIG_CMD_ASKENV=y CONFIG_CMD_GREPENV=y CONFIG_CMD_ENV_CALLBACK=y CONFIG_CMD_ENV_FLAGS=y +CONFIG_CMD_NVEDIT_EFI=y CONFIG_LOOPW=y CONFIG_CMD_MD5SUM=y CONFIG_CMD_MEMINFO=y @@ -53,6 +54,7 @@ CONFIG_CMD_DNS=y CONFIG_CMD_LINK_LOCAL=y CONFIG_CMD_ETHSW=y CONFIG_CMD_BMP=y +CONFIG_CMD_EFIDEBUG=y CONFIG_CMD_TIME=y CONFIG_CMD_TIMER=y CONFIG_CMD_SOUND=y @@ -203,6 +205,7 @@ CONFIG_RSA_VERIFY_WITH_PKEY=y CONFIG_TPM=y CONFIG_LZ4=y CONFIG_ERRNO_STR=y +CONFIG_EFI_SECURE_BOOT=y CONFIG_TEST_FDTDEC=y CONFIG_UNIT_TEST=y CONFIG_UT_TIME=y diff --git a/configs/sandbox_defconfig b/configs/sandbox_defconfig index cc90f0006e24..72e1de3086ee 100644 --- a/configs/sandbox_defconfig +++ b/configs/sandbox_defconfig @@ -31,6 +31,7 @@ CONFIG_CMD_ASKENV=y CONFIG_CMD_GREPENV=y CONFIG_CMD_ENV_CALLBACK=y CONFIG_CMD_ENV_FLAGS=y +CONFIG_CMD_NVEDIT_EFI=y CONFIG_LOOPW=y CONFIG_CMD_MD5SUM=y CONFIG_CMD_MEMINFO=y @@ -62,6 +63,7 @@ CONFIG_CMD_LINK_LOCAL=y CONFIG_CMD_ETHSW=y CONFIG_CMD_BMP=y CONFIG_CMD_BOOTCOUNT=y +CONFIG_CMD_EFIDEBUG=y CONFIG_CMD_TIME=y CONFIG_CMD_TIMER=y CONFIG_CMD_SOUND=y @@ -229,6 +231,7 @@ CONFIG_RSA_VERIFY_WITH_PKEY=y CONFIG_TPM=y CONFIG_LZ4=y CONFIG_ERRNO_STR=y +CONFIG_EFI_SECURE_BOOT=y CONFIG_TEST_FDTDEC=y CONFIG_UNIT_TEST=y CONFIG_UT_TIME=y From patchwork Tue Apr 14 02:51:53 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270047 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=85.214.62.61; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=TTRc2J0p; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [85.214.62.61]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VV62Z4tz9s71 for ; Tue, 14 Apr 2020 12:55:41 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id CE28281940; Tue, 14 Apr 2020 04:54:41 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="TTRc2J0p"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id CF998818F1; Tue, 14 Apr 2020 04:53:25 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pl1-x643.google.com (mail-pl1-x643.google.com [IPv6:2607:f8b0:4864:20::643]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 2F99481656 for ; Tue, 14 Apr 2020 04:53:12 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pl1-x643.google.com with SMTP id g2so4145611plo.3 for ; Mon, 13 Apr 2020 19:53:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=2S5DuX5Pyutc6HBsTFa8FiycntF24F3fXwKlwCP+2js=; b=TTRc2J0pfRQy91IehwPykV0tsgswbjdoLjHJiM6B1Ni6qJIP7DtPSUjvMb1sR2blHF QcjxdgupHjQreVSkb3phoE7qy9PbbDh82RwgtjDwzJOoGJZ/5xL0R0ZqCK/YcCWEEhGi nV2mxgrlFNjBcC9Tx16JxS77ubcuFuhEZisU+lIbZwk8MFD7YhLpzVhG+Nkf93M7tNLn OpTwm7Oy7Z38JFyo0GkZVw+Og4thhPpMg+salaF6scne4eyZh5vvug5DKDGizAOnygRz 24DgsSBXj1iDLuD+BUNldjCM9/WDNapywe/S4MIHjyZ6vDPatyqMA5uV8JZc430VjkNd XSJQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=2S5DuX5Pyutc6HBsTFa8FiycntF24F3fXwKlwCP+2js=; b=T8Bdfdw/9xWUAmM1hk+rGTdq4AlVmxPft05FjtoAYN2MePftJaUUxQiflVnqa7gKQY zT4ONL6HUJzRdxv80axq9PphJS4gv6GHcWV4DQ4eNnqb3tBZYSODuVkvSkX/jSSQpuFi 5siCA9uk3H4t5urV6vPWIJmmfrAqdEn0XNmnZC091tSguRqlMVp/D9/aF+F3ONaUo+Xy cltUgoP0BLSCvoMfIKhG0XQEwfKuhYGe0F1h7DgQERTDVhYp5CbCNsvvp/tRNX1gTKVe VQqbRIiWjJ9ddc/Fds+6bH62GZLYzY+VoIq9paRfu7z03uLAnW0NQmWLEE0l7Mx1Gw1D MruQ== X-Gm-Message-State: AGi0PuaQQuh05KXsxrHgkUTEqIzjRC3/Xg/HcOPtrQ88oE9C8UAFP5C0 3dTWalQ9Xdzs1vlMC3jstHwLZw== X-Google-Smtp-Source: APiQypIF/n5dTSQIGpNMT8K98Bo6GcgBl93dXZL3hp+9RVxSoTI1X8llw7Sgzm/fsaagzvh4q5qT9g== X-Received: by 2002:a17:902:8d8e:: with SMTP id v14mr19345993plo.186.1586832790733; Mon, 13 Apr 2020 19:53:10 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.53.07 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:53:10 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 16/17] travis: add packages for UEFI secure boot test Date: Tue, 14 Apr 2020 11:51:53 +0900 Message-Id: <20200414025154.27283-17-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean Pytest for UEFI secure boot will use several host commands. In particular, Test setup relies on efitools, whose version must be v1.5.2 or later. So fetch a new version of deb package directly. Please note it has a dependency on mtools, which must also be installed along wih efitools. In addition, the path, '/sbin', is added to PATH for use of sgdisk and mkfs. Signed-off-by: AKASHI Takahiro Reviewed-by: Tom Rini --- .travis.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c59bd7790b66..b08dd030ef02 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,6 +40,14 @@ addons: - clang-7 - srecord - graphviz + - coreutils + - util-linux + - dosfstools + - gdisk + - mount + - mtools + - openssl + - sbsigntool install: # Clone uboot-test-hooks @@ -60,10 +68,11 @@ install: - mkdir ~/grub2-arm64 - ( cd ~/grub2-arm64; wget -O - http://download.opensuse.org/ports/aarch64/distribution/leap/42.2/repo/oss/suse/aarch64/grub2-arm64-efi-2.02~beta2-87.1.aarch64.rpm | rpm2cpio | cpio -di ) - wget http://mirrors.kernel.org/ubuntu/pool/main/m/mpfr4/libmpfr4_3.1.4-1_amd64.deb && sudo dpkg -i libmpfr4_3.1.4-1_amd64.deb && rm libmpfr4_3.1.4-1_amd64.deb + - wget http://mirrors.kernel.org/ubuntu/pool/universe/e/efitools/efitools_1.8.1-0ubuntu2_amd64.deb && sudo dpkg -i efitools_1.8.1-0ubuntu2_amd64.deb && rm efitools_1.8.1-0ubuntu2_amd64.deb env: global: - - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/usr/bin:/bin:/usr/local/bin + - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/sbin:/usr/bin:/bin:/usr/local/bin - PYTHONPATH=/tmp/uboot-test-hooks/py/travis-ci - BUILD_DIR=build - HOSTCC="cc" From patchwork Tue Apr 14 02:51:54 2020 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: AKASHI Takahiro X-Patchwork-Id: 1270049 X-Patchwork-Delegate: xypron.glpk@gmx.de Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=lists.denx.de (client-ip=2a01:238:438b:c500:173d:9f52:ddab:ee01; helo=phobos.denx.de; envelope-from=u-boot-bounces@lists.denx.de; receiver=) Authentication-Results: ozlabs.org; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: ozlabs.org; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.a=rsa-sha256 header.s=google header.b=rtdGAxON; dkim-atps=neutral Received: from phobos.denx.de (phobos.denx.de [IPv6:2a01:238:438b:c500:173d:9f52:ddab:ee01]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 491VVJ0H44z9sSt for ; Tue, 14 Apr 2020 12:55:51 +1000 (AEST) Received: from h2850616.stratoserver.net (localhost [IPv6:::1]) by phobos.denx.de (Postfix) with ESMTP id D077581986; Tue, 14 Apr 2020 04:54:46 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=u-boot-bounces@lists.denx.de Authentication-Results: phobos.denx.de; dkim=pass (2048-bit key; unprotected) header.d=linaro.org header.i=@linaro.org header.b="rtdGAxON"; dkim-atps=neutral Received: by phobos.denx.de (Postfix, from userid 109) id 629AE818F1; Tue, 14 Apr 2020 04:53:30 +0200 (CEST) X-Spam-Checker-Version: SpamAssassin 3.4.2 (2018-09-13) on phobos.denx.de X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,SPF_HELO_NONE,URIBL_BLOCKED autolearn=ham autolearn_force=no version=3.4.2 Received: from mail-pg1-x542.google.com (mail-pg1-x542.google.com [IPv6:2607:f8b0:4864:20::542]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits)) (No client certificate requested) by phobos.denx.de (Postfix) with ESMTPS id 94A5E81718 for ; Tue, 14 Apr 2020 04:53:15 +0200 (CEST) Authentication-Results: phobos.denx.de; dmarc=pass (p=none dis=none) header.from=linaro.org Authentication-Results: phobos.denx.de; spf=pass smtp.mailfrom=takahiro.akashi@linaro.org Received: by mail-pg1-x542.google.com with SMTP id w11so5362107pga.12 for ; Mon, 13 Apr 2020 19:53:15 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linaro.org; s=google; h=from:to:cc:subject:date:message-id:in-reply-to:references :mime-version:content-transfer-encoding; bh=WerUd5Hu1d9RwK+/jXm825bQJGyFMUaEiwpUWXrpAaU=; b=rtdGAxONtPGvu315Ei9BAAWyiG06OCC5fjBjR68OgL2WAmI85/AcXazBepiggpNghH 9DwNoPA7Zol6vxQNNx0a7Gt70Kjt35BNRHkm+keiBz6Gq76j5OiRICQ0cptwQL4jRTwA QflNhqb7w1dfF4ma/d17RqEJWZw3sbdOJ8FRy4GuN+H3YGJ+1OsAPe0UyZwVlA2p4k3Z fpIbxpGmuRpKAPLLUMDRYfGe4LCjDOTbLnh7oFpVejlZr2lVDpa9NRLSjkY/OJGwfSu3 KC7o5RgFyxb0qp/Ul8bXNsRa6Ld5/mSFwZORH3XaVZrjHH6Enavz89dGfnjwlwDwIsrM gUVQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references:mime-version:content-transfer-encoding; bh=WerUd5Hu1d9RwK+/jXm825bQJGyFMUaEiwpUWXrpAaU=; b=TY54m8aR+VbltiJaFac+XjOU20++heE8nC4aHAs823AfvlyEUWhako6eV/hLEOY+QP gLu3mgWbIrYbFRMe00o31eNO/VvoCDwQUigYFzf6Kosv9FCb2axBrtjJjoxHMl9CFEp9 sHB3PmLU6h6ztah/+j1N4skh1mALPzgdw6YyU+w9x11PBM5fQov/OkKYCHE5ijy2RZ2d uvRfyufmDk0Be9zarfA2t/9fmf/v85A62IUguSfcAcfbzFsjd4avOi8udORHpaDMG0wI iPGWAVY78eIu9FaRPyeh7+QQ1ZQgCl7QNtKlZfhQl3N+gBkexxfa7Rd/2hOC3+/6VVYJ q7KA== X-Gm-Message-State: AGi0Puai/YFnLFfVfMMkCMrttNm5Ihmbm+B6v5bcmOGlkcEP8agACiP4 O6CLYDDNwBnJDjTtl3Fq3fsYpltsIuI= X-Google-Smtp-Source: APiQypL6gyrRYr7cD0JkjvB9RaqmVxWb0McOCX66rk41krlBoKGBywBxcboNXwQeqfozbf42iPQI3g== X-Received: by 2002:a63:cf50:: with SMTP id b16mr19557462pgj.189.1586832794054; Mon, 13 Apr 2020 19:53:14 -0700 (PDT) Received: from localhost.localdomain (p73a21dd7.tkyea130.ap.so-net.ne.jp. [115.162.29.215]) by smtp.gmail.com with ESMTPSA id mq6sm10686103pjb.38.2020.04.13.19.53.11 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 13 Apr 2020 19:53:13 -0700 (PDT) From: AKASHI Takahiro To: xypron.glpk@gmx.de, agraf@csgraf.de, trini@konsulko.com Cc: sjg@chromium.org, ilias.apalodimas@linaro.org, mail@patrick-wildt.de, u-boot@lists.denx.de, AKASHI Takahiro Subject: [PATCH v7 17/17] efi_loader: add some description about UEFI secure boot Date: Tue, 14 Apr 2020 11:51:54 +0900 Message-Id: <20200414025154.27283-18-takahiro.akashi@linaro.org> X-Mailer: git-send-email 2.25.2 In-Reply-To: <20200414025154.27283-1-takahiro.akashi@linaro.org> References: <20200414025154.27283-1-takahiro.akashi@linaro.org> MIME-Version: 1.0 X-BeenThere: u-boot@lists.denx.de X-Mailman-Version: 2.1.30rc1 Precedence: list List-Id: U-Boot discussion List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: u-boot-bounces@lists.denx.de Sender: "U-Boot" X-Virus-Scanned: clamav-milter 0.102.2 at phobos.denx.de X-Virus-Status: Clean A small text in docs/uefi/uefi.rst was added to explain how we can configure and utilise UEFI secure boot feature on U-Boot. Signed-off-by: AKASHI Takahiro Acked-by: Ilias Apalodimas --- doc/uefi/uefi.rst | 77 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/doc/uefi/uefi.rst b/doc/uefi/uefi.rst index cfe2d84a4c64..a35fbd331c1f 100644 --- a/doc/uefi/uefi.rst +++ b/doc/uefi/uefi.rst @@ -97,6 +97,83 @@ Below you find the output of an example session starting GRUB:: See doc/uImage.FIT/howto.txt for an introduction to FIT images. +Configuring UEFI secure boot +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +UEFI specification[1] defines a secure way of executing UEFI images +by verifying a signature (or message digest) of image with certificates. +This feature on U-Boot is enabled with:: + + CONFIG_UEFI_SECURE_BOOT=y + +To make the boot sequence safe, you need to establish a chain of trust; +In UEFI secure boot, you can make it with the UEFI variables, "PK" +(Platform Key), "KEK" (Key Exchange Keys), "db" (white list database) +and "dbx" (black list database). + +There are many online documents that describe what UEFI secure boot is +and how it works. Please consult some of them for details. + +Here is a simple example that you can follow for your initial attempt +(Please note that the actual steps would absolutely depend on your system +and environment.): + +1. Install utility commands on your host + * openssl + * efitools + * sbsigntool + +2. Create signing keys and key database files on your host + for PK:: + + $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_PK/ \ + -keyout PK.key -out PK.crt -nodes -days 365 + $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \ + PK.crt PK.esl; + $ sign-efi-sig-list -c PK.crt -k PK.key PK PK.esl PK.auth + + for KEK:: + + $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_KEK/ \ + -keyout KEK.key -out KEK.crt -nodes -days 365 + $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \ + KEK.crt KEK.esl + $ sign-efi-sig-list -c PK.crt -k PK.key KEK KEK.esl KEK.auth + + for db:: + + $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db/ \ + -keyout db.key -out db.crt -nodes -days 365 + $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \ + db.crt db.esl + $ sign-efi-sig-list -c KEK.crt -k KEK.key db db.esl db.auth + + Copy \*.auth to media, say mmc, that is accessible from U-Boot. + +3. Sign an image with one key in "db" on your host:: + + $ sbsign --key db.key --cert db.crt helloworld.efi + +4. Install keys on your board:: + + ==> fatload mmc 0:1 PK.auth + ==> setenv -e -nv -bs -rt -at -i ,$filesize PK + ==> fatload mmc 0:1 KEK.auth + ==> setenv -e -nv -bs -rt -at -i ,$filesize KEK + ==> fatload mmc 0:1 db.auth + ==> setenv -e -nv -bs -rt -at -i ,$filesize db + +5. Set up boot parameters on your board:: + + ==> efidebug boot add 1 HELLO mmc 0:1 /helloworld.efi.signed "" + +Then your board runs that image from Boot manager (See below). +You can also try this sequence by running Pytest, test_efi_secboot, +on sandbox:: + + $ cd + $ pytest.py test/py/tests/test_efi_secboot/test_signed.py --bd sandbox + Executing the boot manager ~~~~~~~~~~~~~~~~~~~~~~~~~~