From 65ce860e494eb6d2b84eebf90b0774353f1f755a Mon Sep 17 00:00:00 2001 From: Michael Kinney Date: Thu, 14 Aug 2014 06:30:10 +0000 Subject: [PATCH] Contributed-under: TianoCore Contribution Agreement 1.0 Signed-off-by: Michael Kinney Reviewed-by: Yingke Liu Add support for RSA 2048 SHA 256 signing and verification encoded in a PI FFS GUIDED Encapsulation Section. The primary use case of this feature is in support of signing and verification of encapsulated FVs for Recovery and Capsule Update, but can potentially be used for signing and verification of any content that can be stored in a PI conformant FFS file. Signing operations are performed from python scripts that wrap OpenSsl command line utilities. Verification operations are performed using the OpenSsl libraries in the CryptoPkg. The guided encapsulation sections uses the UEFI 2.4 Specification defined GUID called EFI_CERT_TYPE_RSA2048_SHA256_GUID. The data layout for the encapsulation section starts with the UEFI 2.4 Specification defined structure called EFI_CERT_BLOCK_RSA_2048_SHA256 followed immediately by the data. The signing tool included in these patches performs encode/decode operations using this data layout. HashType is set to the UEFI 2.4 Specification defined GUID called EFI_HASH_ALGORITHM_SHA256_GUID. MdePkg/Include/Guid/WinCertificate.h ================================= // // WIN_CERTIFICATE_UEFI_GUID.CertType // #define EFI_CERT_TYPE_RSA2048_SHA256_GUID \ {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf } } /// /// WIN_CERTIFICATE_UEFI_GUID.CertData /// typedef struct { EFI_GUID HashType; UINT8 PublicKey[256]; UINT8 Signature[256]; } EFI_CERT_BLOCK_RSA_2048_SHA256; MdePkg/Include/Protocol/Hash.h ================================= #define EFI_HASH_ALGORITHM_SHA256_GUID \ { \ 0x51aa59de, 0xfdf2, 0x4ea3, {0xbc, 0x63, 0x87, 0x5f, 0xb7, 0x84, 0x2e, 0xe9 } \ } The verification operations require the use of public key(s). A new PCD called gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer is added to the SecurityPkg that supports one or more SHA 256 hashes of the public keys. A SHA 256 hash is performed to minimize the FLASH overhead of storing the public keys. When a verification operation is performed, a SHA 256 hash is performed on EFI_CERT_BLOCK_RSA_2048_SHA256.PublicKey and a check is made to see if that hash matches any of the hashes in the new PCD. It is recommended that this PCD always be configured in the DSC file as storage type of [PcdsDynamixExVpd], so the public keys are stored in a protected read-only region. While working on this feature, I noticed that the CRC32 signing and verification feature was incomplete. It only supported CRC32 based verification in the DXE Phase, so the attached patches also provide support for CRC32 based verification in the PEI Phase. I also noticed that the most common method for incorporating guided section extraction libraries was to directly link them to the DXE Core, which is not very flexible. The attached patches also add a generic section extraction PEIM and a generic section extraction DXE driver that can each be linked against one or more section extraction libraries. This provides a platform developer with the option of providing section extraction services with the DXE Core or providing section extraction services with these generic PEIM/DXE Drivers. Patch Summary ============== 1) BaseTools - Rsa2049Sha256Sign python script that can perform test signing or custom signing of PI FFS file GUIDed sections a. Wrapper for a set of OpenSsl command line utility operations b. OpenSsl command line tool must be installed in location that is in standard OS path or in path specified by OS environment variable called OPENSSL_PATH c. Provides standard EDK II command line arguments for a tool that encodes/decodes guided encapsulation section Rsa2048Sha256Sign - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved. usage: Rsa2048Sha256Sign -e|-d [options] positional arguments: input_file specify the input filename optional arguments: -e encode file -d decode file -o filename, --output filename specify the output filename --private-key PRIVATEKEYFILE specify the private key filename. If not specified, a test signing key is used. -v, --verbose increase output messages -q, --quiet reduce output messages --debug [0-9] set debug level --version display the program version and exit -h, --help display this help text 2) BaseTools - Rsa2049Sha256GenerateKeys python script that can generate new private/public key and PCD value that is SHA 256 hash of public key using OpenSsl command line utilities. a. Wrapper for a set of OpenSsl command line utility operations b. OpenSsl command line tool must be installed in location that is in standard path or in path specified by OS environment variable called OPENSSL_PATH Rsa2048Sha256GenerateKeys - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved. usage: Rsa2048Sha256GenerateKeys [options] optional arguments: -o [filename [filename ...]], --output [filename [filename ...]] specify the output private key filename in PEM format -i [filename [filename ...]], --input [filename [filename ...]] specify the input private key filename in PEM format --public-key-hash PUBLICKEYHASHFILE specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in binary format --public-key-hash-c PUBLICKEYHASHCFILE specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in C structure format -v, --verbose increase output messages -q, --quiet reduce output messages --debug [0-9] set debug level --version display the program version and exit -h, --help display this help text 3) BaseTools\Conf\tools_def.template a. Define GUID/Tool to perform RSA 2048 SHA 256 test signing and instructions on how to use alternate private/public key b. GUID is EFI_CERT_TYPE_RSA2048_SHA256_GUID c. Tool is Rsa2049Sha256Sign 4) MdeModulePkg\Library\PeiCrc32GuidedSectionExtractionLib a. Add peer for DxeCrc32GuidedSectionExtractionLib so both PEI and DXE phases can perform basic integrity checks of PEI and DXE components 5) MdeModulePkg\Universal\SectionExtractionPei a. Generic PEIM that can link against one or more NULL section extraction library instances to provided one or more GUIDED Section Extraction PPIs 6) MdeModulePkg\Universal\SectionExtractionDxe a. Generic DXE Driver that can link against one or more NULL section extraction library instances to provide one or more GUIDED Section Extraction Protocols. 7) SecurityPkg\Library\PeiRsa2048Sha256GuidedSectionExtractLib a. NULL library instances that performs PEI phase RSA 2048 SHA 256 signature verification using OpenSsl libraries from CryptoPkg. b. Based on algorithms from SecurityPkg Authenticated Variable services c. Uses public key from gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer. 8) SecurityPkg\Library\DxeRsa2048Sha256GuidedSectionExtractLib a. NULL library instances that performs DXE phase RSA 2048 SHA 256 signature verification using OpenSsl libraries from CryptoPkg. b. Based on algorithms from SecurityPkg Authenticated Variable services c. Uses public key from gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer. git-svn-id: https://svn.code.sf.net/p/edk2/code/trunk/edk2@15800 6f19259b-4bc3-4df7-8a09-765794883524 --- BaseTools/Conf/tools_def.template | 27 +++ BaseTools/Source/Python/Makefile | 11 +- .../Rsa2048Sha256GenerateKeys.py | 174 ++++++++++++++ .../Rsa2048Sha256Sign/Rsa2048Sha256Sign.py | 217 ++++++++++++++++++ .../TestSigningPrivateKey.pem | 27 +++ .../TestSigningPublicKey.bin | 1 + .../TestSigningPublicKey.txt | 1 + 7 files changed, 456 insertions(+), 2 deletions(-) create mode 100644 BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py create mode 100644 BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py create mode 100644 BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPrivateKey.pem create mode 100644 BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.bin create mode 100644 BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.txt diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 897d13799e..1dae59a51a 100644 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -6519,6 +6519,32 @@ RELEASE_ARMLINUXGCC_AARCH64_CC_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC *_*_*_CRC32_PATH = GenCrc32 *_*_*_CRC32_GUID = FC1BCDB0-7D31-49AA-936A-A4600D9DD083 +################## +# Rsa2048Sha256Sign tool definitions +# +# Notes: This tool defintion uses a test signing key for development purposes only. +# The tool Rsa2048Sha256GenerateKeys can be used to generate a new private/public key +# and the gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer PCD value. +# A custom tool/script can be implemented using the new private/public key with +# the Rsa2048Sha256Sign tool and this tool defintiion can be updated to use a +# custom tool/script. +# +# Generate new private/public key and gEfiSecurityPkgTokenSpaceGuid.PcdRsa2048Sha256PublicKeyBuffer PCD value +# +# Rsa2048Sha256GenerateKeys.py -o MyKey.pem --public-key-hash-c MyKey.pcd +# +# Custom script example (MyRsa2048Sha256Sign.cmd): +# +# Rsa2048Sha256Sign --private-key MyKey.pem %1 %2 %3 %4 %5 %6 %7 %8 %9 +# +# WARNING: Vendors that uses private keys are responsible for proper management and protection +# of private keys. Vendors may choose to use infrastructure such as signing servers +# or signing portals to support the management and protection of private keys. +# +################## +*_*_*_RSA2048SHA256SIGN_PATH = Rsa2048Sha256Sign +*_*_*_RSA2048SHA256SIGN_GUID = A7717414-C616-4977-9420-844712A735BF + ################## # LzmaCompress tool definitions ################## @@ -6544,3 +6570,4 @@ RELEASE_ARMLINUXGCC_AARCH64_CC_FLAGS = $(ARCHCC_FLAGS) $(PLATFORM_FLAGS) DEF(GCC ################## *_*_*_VPDTOOL_PATH = BPDG *_*_*_VPDTOOL_GUID = 8C3D856A-9BE6-468E-850A-24F7A8D38E08 + diff --git a/BaseTools/Source/Python/Makefile b/BaseTools/Source/Python/Makefile index a3a537c352..0c332afbed 100644 --- a/BaseTools/Source/Python/Makefile +++ b/BaseTools/Source/Python/Makefile @@ -1,7 +1,7 @@ ## @file # Windows makefile for Python tools build. # -# Copyright (c) 2010, Intel Corporation. All rights reserved.
+# Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at @@ -27,7 +27,7 @@ MODULES=encodings.cp437,encodings.gbk,encodings.utf_16,encodings.utf_8,encodings BIN_DIR=$(EDK_TOOLS_PATH)\Bin\Win32 -APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe +APPLICATIONS=$(BIN_DIR)\build.exe $(BIN_DIR)\GenFds.exe $(BIN_DIR)\Trim.exe $(BIN_DIR)\TargetTool.exe $(BIN_DIR)\GenDepex.exe $(BIN_DIR)\GenPatchPcdTable.exe $(BIN_DIR)\PatchPcdValue.exe $(BIN_DIR)\BPDG.exe $(BIN_DIR)\UPT.exe $(BIN_DIR)\Rsa2048Sha256Sign.exe $(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe COMMON_PYTHON=$(BASE_TOOLS_PATH)\Source\Python\Common\BuildToolError.py \ $(BASE_TOOLS_PATH)\Source\Python\Common\Database.py \ @@ -101,6 +101,13 @@ $(BIN_DIR)\BPDG.exe: $(BASE_TOOLS_PATH)\Source\Python\BPDG\BPDG.py $(COMMON_PYTH $(BIN_DIR)\UPT.exe: $(BASE_TOOLS_PATH)\Source\Python\UPT\UPT.py $(UPT_BUILDVERSION_PYTHON) @pushd . & @cd UPT & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) UPT.py & @popd +$(BIN_DIR)\Rsa2048Sha256Sign.exe: $(BASE_TOOLS_PATH)\Source\Python\Rsa2048Sha256Sign\Rsa2048Sha256Sign.py + @pushd . & @cd Rsa2048Sha256Sign & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Rsa2048Sha256Sign.py & @popd + @pushd . & @copy /Y /B $(BASE_TOOLS_PATH)\Source\Python\Rsa2048Sha256Sign\TestSigningPrivateKey.pem $(BIN_DIR)\TestSigningPrivateKey.pem & @popd + +$(BIN_DIR)\Rsa2048Sha256GenerateKeys.exe: $(BASE_TOOLS_PATH)\Source\Python\Rsa2048Sha256Sign\Rsa2048Sha256GenerateKeys.py + @pushd . & @cd Rsa2048Sha256Sign & @$(FREEZE) --include-modules=$(MODULES) --install-dir=$(BIN_DIR) Rsa2048Sha256GenerateKeys.py & @popd + clean: cleanall: @del /f /q $(BIN_DIR)\*.pyd $(BIN_DIR)\*.dll diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py new file mode 100644 index 0000000000..630670ef6d --- /dev/null +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256GenerateKeys.py @@ -0,0 +1,174 @@ +## @file +# This tool can be used to generate new RSA 2048 bit private/public key pairs +# in a PEM file format using OpenSSL command line utilities that are installed +# on the path specified by the system environment variable OPENSSL_PATH. +# This tool can also optionally write one or more SHA 256 hashes of 2048 bit +# public keys to a binary file, write one or more SHA 256 hashes of 2048 bit +# public keys to a file in a C structure format, and in verbose mode display +# one or more SHA 256 hashes of 2048 bit public keys in a C structure format +# on STDOUT. +# This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013 +# +# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# + +''' +Rsa2048Sha256GenerateKeys +''' + +import os +import sys +import argparse +import subprocess + +if __name__ == '__main__': + # + # Save name of the program + # + ProgramName = sys.argv[0] + + # + # Print copyright + # + print '%s - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.' % (ProgramName) + + # + # Create command line argument parser object + # + parser = argparse.ArgumentParser(prog=ProgramName, usage='%(prog)s [options]', add_help=False) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("-o", "--output", dest='OutputFile', type=argparse.FileType('wb'), metavar='filename', nargs='*', help="specify the output private key filename in PEM format") + group.add_argument("-i", "--input", dest='InputFile', type=argparse.FileType('rb'), metavar='filename', nargs='*', help="specify the input private key filename in PEM format") + parser.add_argument("--public-key-hash", dest='PublicKeyHashFile', type=argparse.FileType('wb'), help="specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in binary format") + parser.add_argument("--public-key-hash-c", dest='PublicKeyHashCFile', type=argparse.FileType('wb'), help="specify the public key hash filename that is SHA 256 hash of 2048 bit RSA public key in C structure format") + parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages") + parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages") + parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level") + parser.add_argument("--version", dest='Version', action="store_true", help="display the program version and exit") + parser.add_argument("-h", "--help", dest='Help', action="help", help="display this help text") + + # + # Parse command line arguments + # + args = parser.parse_args() + + # + # Generate file path to Open SSL command + # + OpenSslCommand = 'openssl' + try: + OpenSslPath = os.environ['OPENSSL_PATH'] + OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand) + except: + pass + + # + # Verify that Open SSL command is available + # + try: + Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except: + print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH' + sys.exit(1) + + Version = Process.communicate() + if Process.returncode <> 0: + print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH' + sys.exit(Process.returncode) + print Version[0] + + args.PemFileName = [] + + # + # Check for output file argument + # + if args.OutputFile <> None: + for Item in args.OutputFile: + # + # Save PEM filename and close output file + # + args.PemFileName.append(Item.name) + Item.close() + + # + # Generate private key and save it to output file in a PEM file format + # + Process = subprocess.Popen('%s genrsa -out %s 2048' % (OpenSslCommand, Item.name), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + Process.communicate() + if Process.returncode <> 0: + print 'ERROR: RSA 2048 key generation failed' + sys.exit(Process.returncode) + + # + # Check for input file argument + # + if args.InputFile <> None: + for Item in args.InputFile: + # + # Save PEM filename and close input file + # + args.PemFileName.append(Item.name) + Item.close() + + PublicKeyHash = '' + for Item in args.PemFileName: + # + # Extract public key from private key into STDOUT + # + Process = subprocess.Popen('%s rsa -in %s -modulus -noout' % (OpenSslCommand, Item), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + PublicKeyHexString = Process.communicate()[0].split('=')[1].strip() + if Process.returncode <> 0: + print 'ERROR: Unable to extract public key from private key' + sys.exit(Process.returncode) + PublicKey = '' + for Index in range (0, len(PublicKeyHexString), 2): + PublicKey = PublicKey + chr(int(PublicKeyHexString[Index:Index + 2], 16)) + + # + # Generate SHA 256 hash of RSA 2048 bit public key into STDOUT + # + Process = subprocess.Popen('%s dgst -sha256 -binary' % (OpenSslCommand), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + Process.stdin.write (PublicKey) + PublicKeyHash = PublicKeyHash + Process.communicate()[0] + if Process.returncode <> 0: + print 'ERROR: Unable to extract SHA 256 hash of public key' + sys.exit(Process.returncode) + + # + # Write SHA 256 hash of 2048 bit binary public key to public key hash file + # + try: + args.PublicKeyHashFile.write (PublicKeyHash) + args.PublicKeyHashFile.close () + except: + pass + + # + # Convert public key hash to a C structure string + # + PublicKeyHashC = '{' + for Item in PublicKeyHash: + PublicKeyHashC = PublicKeyHashC + '0x%02x, ' % (ord(Item)) + PublicKeyHashC = PublicKeyHashC[:-2] + '}' + + # + # Write SHA 256 of 2048 bit binary public key to public key hash C structure file + # + try: + args.PublicKeyHashCFile.write (PublicKeyHashC) + args.PublicKeyHashCFile.close () + except: + pass + + # + # If verbose is enabled display the public key in C structure format + # + if args.Verbose: + print 'PublicKeySha256 = ' + PublicKeyHashC diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py new file mode 100644 index 0000000000..b4c9aa4ce4 --- /dev/null +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py @@ -0,0 +1,217 @@ +## @file +# This tool encodes and decodes GUIDed FFS sections for a GUID type of +# EFI_CERT_TYPE_RSA2048_SHA256_GUID defined in the UEFI 2.4 Specification as +# {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf}} +# This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013 +# +# Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.
+# This program and the accompanying materials +# are licensed and made available under the terms and conditions of the BSD License +# which accompanies this distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +# + +''' +Rsa2048Sha256Sign +''' + +import os +import sys +import argparse +import subprocess +import uuid +import struct +import collections + +# +# GUID for SHA 256 Hash Algorithm from UEFI Specification +# +EFI_HASH_ALGORITHM_SHA256_GUID = uuid.UUID('{51aa59de-fdf2-4ea3-bc63-875fb7842ee9}') + +# +# Structure defintion to unpack EFI_CERT_BLOCK_RSA_2048_SHA256 from UEFI 2.4 Specification +# +# typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 { +# EFI_GUID HashType; +# UINT8 PublicKey[256]; +# UINT8 Signature[256]; +# } EFI_CERT_BLOCK_RSA_2048_SHA256; +# +EFI_CERT_BLOCK_RSA_2048_SHA256 = collections.namedtuple('EFI_CERT_BLOCK_RSA_2048_SHA256', ['HashType','PublicKey','Signature']) +EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT = struct.Struct('16s256s256s') + +# +# Filename of test signing private key that is stored in same directory as this tool +# +TEST_SIGNING_PRIVATE_KEY_FILENAME = 'TestSigningPrivateKey.pem' + +if __name__ == '__main__': + # + # Save name of the program + # + ProgramName = sys.argv[0] + + # + # Print copyright + # + print '%s - Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.' % (ProgramName) + + # + # Create command line argument parser object + # + parser = argparse.ArgumentParser(prog=ProgramName, usage='%(prog)s -e|-d [options] ', add_help=False) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("-e", action="store_true", dest='Encode', help='encode file') + group.add_argument("-d", action="store_true", dest='Decode', help='decode file') + parser.add_argument("-o", "--output", dest='OutputFile', type=argparse.FileType('wb'), metavar='filename', help="specify the output filename", required=True) + parser.add_argument("--private-key", dest='PrivateKeyFile', type=argparse.FileType('rb'), help="specify the private key filename. If not specified, a test signing key is used.") + parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages") + parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages") + parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level") + parser.add_argument("--version", dest='Version', action="store_true", help="display the program version and exit") + parser.add_argument("-h", "--help", dest='Help', action="help", help="display this help text") + parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename") + + # + # Parse command line arguments + # + args = parser.parse_args() + + # + # Generate file path to Open SSL command + # + OpenSslCommand = 'openssl' + try: + OpenSslPath = os.environ['OPENSSL_PATH'] + OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand) + except: + pass + + # + # Verify that Open SSL command is available + # + try: + Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except: + print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH' + sys.exit(1) + + Version = Process.communicate() + if Process.returncode <> 0: + print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH' + sys.exit(Process.returncode) + print Version[0] + + # + # Read input file into a buffer and save input filename + # + args.InputFileName = args.InputFile.name + args.InputFileBuffer = args.InputFile.read() + args.InputFile.close() + + # + # Save output filename and close output file + # + args.OutputFileName = args.OutputFile.name + args.OutputFile.close() + + # + # Save private key filename and close private key file + # + try: + args.PrivateKeyFileName = args.PrivateKeyFile.name + args.PrivateKeyFile.close() + except: + try: + # + # Get path to currently executing script or executable + # + if hasattr(sys, 'frozen'): + RsaToolPath = sys.executable + else: + RsaToolPath = sys.argv[0] + if RsaToolPath.startswith('"'): + RsaToolPath = RsaToolPath[1:] + if RsaToolPath.endswith('"'): + RsaToolPath = RsaToolPath[:-1] + args.PrivateKeyFileName = os.path.join(os.path.dirname(os.path.realpath(RsaToolPath)), TEST_SIGNING_PRIVATE_KEY_FILENAME) + args.PrivateKeyFile = open(args.PrivateKeyFileName, 'rb') + args.PrivateKeyFile.close() + except: + print 'ERROR: test signing private key file %s missing' % (args.PrivateKeyFileName) + sys.exit(1) + + # + # Extract public key from private key into STDOUT + # + Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + PublicKeyHexString = Process.communicate()[0].split('=')[1].strip() + PublicKey = '' + while len(PublicKeyHexString) > 0: + PublicKey = PublicKey + chr(int(PublicKeyHexString[0:2],16)) + PublicKeyHexString=PublicKeyHexString[2:] + if Process.returncode <> 0: + sys.exit(Process.returncode) + + if args.Encode: + # + # Sign the input file using the specified private key and capture signature from STDOUT + # + Process = subprocess.Popen('%s sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + Signature = Process.communicate(input=args.InputFileBuffer)[0] + if Process.returncode <> 0: + sys.exit(Process.returncode) + + # + # Write output file that contains hash GUID, Public Key, Signature, and Input data + # + args.OutputFile = open(args.OutputFileName, 'wb') + args.OutputFile.write(EFI_HASH_ALGORITHM_SHA256_GUID.get_bytes_le()) + args.OutputFile.write(PublicKey) + args.OutputFile.write(Signature) + args.OutputFile.write(args.InputFileBuffer) + args.OutputFile.close() + + if args.Decode: + # + # Parse Hash Type, Public Key, and Signature from the section header + # + Header = EFI_CERT_BLOCK_RSA_2048_SHA256._make(EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.unpack_from(args.InputFileBuffer)) + args.InputFileBuffer = args.InputFileBuffer[EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.size:] + + # + # Verify that the Hash Type matches the expected SHA256 type + # + if uuid.UUID(bytes_le = Header.HashType) <> EFI_HASH_ALGORITHM_SHA256_GUID: + print 'ERROR: unsupport hash GUID' + sys.exit(1) + + # + # Verify the public key + # + if Header.PublicKey <> PublicKey: + print 'ERROR: Public key in input file does not match public key from private key file' + sys.exit(1) + + # + # Write Signature to output file + # + open(args.OutputFileName, 'wb').write(Header.Signature) + + # + # Verify signature + # + Process = subprocess.Popen('%s sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + Process.communicate(args.InputFileBuffer) + if Process.returncode <> 0: + print 'ERROR: Verification failed' + os.remove (args.OutputFileName) + sys.exit(Process.returncode) + + # + # Save output file contents from input file + # + open(args.OutputFileName, 'wb').write(args.InputFileBuffer) diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPrivateKey.pem b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPrivateKey.pem new file mode 100644 index 0000000000..ced4888799 --- /dev/null +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPrivateKey.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAudErrthutWCNdQy+XWCiKg89B9BPb9GaOtEBL0tIOGCkmAY3 +/aT13OCxR1f4FIGavKT+7aDZDnwyK3g1U/J2q4DdPHzSRoOOK5h9dqRabqEtlgaE +2OQeLvs20hKARzQEHSj9aaUKPfN/uF7DYENs1N38QqSo//R1FZ4jJ1th5z+4RoIE +/M3+yaSxGvOi+0FUEW57stqLGMTY8WFZeUOmCuRMGKC+5o57/H2OJa+Nh9rcO+8e +Nc7/mR5ZB3lbkzq/3Wf9wZcQkCZaIA2uKSEM81I/3SGvu8P9+jfPDJ027dQOdjop +M+0CA+Id5+XPoUFOy1aWKnM6Keq8BWsqA2f/awIDAQABAoIBAQCElZVfupqz3GLS +w/cI1ayf6iOX8bDcjmhH013PCx5K69pFhxpoZ03u/nw/9arTpu5r8CbeE0kNJtz9 +W1Zhwb2e/eHeCQpYugG1ZacQApFsIqFOTPR5dbt7tlAVcJILPDg7PkYjHVnDfn0B +ZsxtYW7ELGiUfL0BdMIeXKmkqXWf9AU37Frky3i1GwmyNy15RWj9T/JS8Wg6G3vq +ZCqk7nOjMap8vFw0w6Z0FodapEiYxvfLsq/CQxZm5B2IeYPiIXuTif69Fw0Yhm5x ++GBOrrOZjFJuhFWngJg8lkh77P++CfmkX+V9WUHBPYyU6R9WPnpyC9T2sfyrTBG0 +yVc1mGTxAoGBAOtc3EaV7tVqzAQupTI4lyD1+eOfYIzPGbPVYkEQg81ru+O4SuNw +n8P31L0O1F+YnlhHsDW2B2CsEAi1dFgfj5uUni4Ug42tNZLQKYHy6x436HYj2BRC +fvju4gUDj2rJaKMo4bb1shpyIZce5APg0kO4Pfp8B29+qaNjJJSm/xdfAoGBAMoc +KzKIQN+uHnXdRMCTnKStiyxJ5RRlhkeDEgrhjirL3d5GCsNxd1AJUYBEkgs7K6aX +4HbuJxIypTNQJwqMe4ltGQazOxG4JKv7JB0bchXMBfzGUA4tTbyQ45APFvPhtWG9 +3xwIyJy602dWQzF7nrNkQo81HHgd8RBlQDjY5E91AoGBAJW12KvRfT0llKZoYU4j +rwYZUJ2YaFrI9WltpvUKIzyMddRxCrnHjuihgSHNCAvS0Y4H868GnYTBjeVsPpg7 +Yyasjz1ycQeykKxVWsG9Gg97spNLU4v3jDqeAQj9bcGYYcW/IGw3ttWZmYI99P3+ +iODolgv5zuT95bv3OXKRExvzAoGAQeJ04oAwRbqJC3saEn0ML1Kzb7iXCNMftugv +VYS5x5G1veOvVo8CigC/pMS1pxue2yvfbGWuLux7lgKm93VcQCxkYB7FPr18luPD +ngl4Y0qjGQe8ySJTmQjSZf/FR7NoYXh35remThFJIQKp3NOjpG8mk3CI209HakTX +brClnJECgYA+Qw69eMTrIIBH2Kw0mazgG9lCoCRA5GF8/qwgH0yxyP0yy/gtxXMs +nMqwo7X3yIIf5Aracc5MbXfaJgR5fOpCrtu3NJGdHC63JblB//7hXiklGNKDaCiV +EBkLJ3YHYn8fAr8n+agE0PSfXFVnC1ToPRWUbBcGrgE16bpzn8o9gw== +-----END RSA PRIVATE KEY----- diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.bin b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.bin new file mode 100644 index 0000000000..8c15a0003b --- /dev/null +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.bin @@ -0,0 +1 @@ +‘)ĽêmÚ³ªoPüÛK~<ÖܤzÝæŒs–¢Ô¦M \ No newline at end of file diff --git a/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.txt b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.txt new file mode 100644 index 0000000000..b0492e2914 --- /dev/null +++ b/BaseTools/Source/Python/Rsa2048Sha256Sign/TestSigningPublicKey.txt @@ -0,0 +1 @@ +{0x91, 0x29, 0xc4, 0xbd, 0xea, 0x6d, 0xda, 0xb3, 0xaa, 0x6f, 0x50, 0x16, 0xfc, 0xdb, 0x4b, 0x7e, 0x3c, 0xd6, 0xdc, 0xa4, 0x7a, 0x0e, 0xdd, 0xe6, 0x15, 0x8c, 0x73, 0x96, 0xa2, 0xd4, 0xa6, 0x4d} \ No newline at end of file -- 2.39.2