]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Rsa2048Sha256Sign/Rsa2048Sha256Sign.py
6cea8858532d2e70f67442f316ed98de4edb3fe1
[mirror_edk2.git] / BaseTools / Source / Python / Rsa2048Sha256Sign / Rsa2048Sha256Sign.py
1 ## @file
2 # This tool encodes and decodes GUIDed FFS sections or FMP capsule for a GUID type of
3 # EFI_CERT_TYPE_RSA2048_SHA256_GUID defined in the UEFI 2.4 Specification as
4 # {0xa7717414, 0xc616, 0x4977, {0x94, 0x20, 0x84, 0x47, 0x12, 0xa7, 0x35, 0xbf}}
5 # This tool has been tested with OpenSSL 1.0.1e 11 Feb 2013
6 #
7 # Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR>
8 # This program and the accompanying materials
9 # are licensed and made available under the terms and conditions of the BSD License
10 # which accompanies this distribution. The full text of the license may be found at
11 # http://opensource.org/licenses/bsd-license.php
12 #
13 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
15 #
16
17 '''
18 Rsa2048Sha256Sign
19 '''
20 from __future__ import print_function
21
22 import os
23 import sys
24 import argparse
25 import subprocess
26 import uuid
27 import struct
28 import collections
29 from Common.BuildVersion import gBUILD_VERSION
30
31 #
32 # Globals for help information
33 #
34 __prog__ = 'Rsa2048Sha256Sign'
35 __version__ = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
36 __copyright__ = 'Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.'
37 __usage__ = '%s -e|-d [options] <input_file>' % (__prog__)
38
39 #
40 # GUID for SHA 256 Hash Algorithm from UEFI Specification
41 #
42 EFI_HASH_ALGORITHM_SHA256_GUID = uuid.UUID('{51aa59de-fdf2-4ea3-bc63-875fb7842ee9}')
43
44 #
45 # Structure defintion to unpack EFI_CERT_BLOCK_RSA_2048_SHA256 from UEFI 2.4 Specification
46 #
47 # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
48 # EFI_GUID HashType;
49 # UINT8 PublicKey[256];
50 # UINT8 Signature[256];
51 # } EFI_CERT_BLOCK_RSA_2048_SHA256;
52 #
53 EFI_CERT_BLOCK_RSA_2048_SHA256 = collections.namedtuple('EFI_CERT_BLOCK_RSA_2048_SHA256', ['HashType', 'PublicKey', 'Signature'])
54 EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT = struct.Struct('16s256s256s')
55
56 #
57 # Filename of test signing private key that is stored in same directory as this tool
58 #
59 TEST_SIGNING_PRIVATE_KEY_FILENAME = 'TestSigningPrivateKey.pem'
60
61 if __name__ == '__main__':
62 #
63 # Create command line argument parser object
64 #
65 parser = argparse.ArgumentParser(prog=__prog__, usage=__usage__, description=__copyright__, conflict_handler='resolve')
66 group = parser.add_mutually_exclusive_group(required=True)
67 group.add_argument("-e", action="store_true", dest='Encode', help='encode file')
68 group.add_argument("-d", action="store_true", dest='Decode', help='decode file')
69 group.add_argument("--version", action='version', version=__version__)
70 parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)
71 parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule.")
72 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.")
73 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")
74 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")
75 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0, 10), default=0, help="set debug level")
76 parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")
77
78 #
79 # Parse command line arguments
80 #
81 args = parser.parse_args()
82
83 #
84 # Generate file path to Open SSL command
85 #
86 OpenSslCommand = 'openssl'
87 try:
88 OpenSslPath = os.environ['OPENSSL_PATH']
89 OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
90 if ' ' in OpenSslCommand:
91 OpenSslCommand = '"' + OpenSslCommand + '"'
92 except:
93 pass
94
95 #
96 # Verify that Open SSL command is available
97 #
98 try:
99 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
100 except:
101 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
102 sys.exit(1)
103
104 Version = Process.communicate()
105 if Process.returncode != 0:
106 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
107 sys.exit(Process.returncode)
108 print(Version[0].decode('utf-8'))
109
110 #
111 # Read input file into a buffer and save input filename
112 #
113 args.InputFileName = args.InputFile.name
114 args.InputFileBuffer = args.InputFile.read()
115 args.InputFile.close()
116
117 #
118 # Save output filename and check if path exists
119 #
120 OutputDir = os.path.dirname(args.OutputFile)
121 if not os.path.exists(OutputDir):
122 print('ERROR: The output path does not exist: %s' % OutputDir)
123 sys.exit(1)
124 args.OutputFileName = args.OutputFile
125
126 #
127 # Save private key filename and close private key file
128 #
129 try:
130 args.PrivateKeyFileName = args.PrivateKeyFile.name
131 args.PrivateKeyFile.close()
132 except:
133 try:
134 #
135 # Get path to currently executing script or executable
136 #
137 if hasattr(sys, 'frozen'):
138 RsaToolPath = sys.executable
139 else:
140 RsaToolPath = sys.argv[0]
141 if RsaToolPath.startswith('"'):
142 RsaToolPath = RsaToolPath[1:]
143 if RsaToolPath.endswith('"'):
144 RsaToolPath = RsaToolPath[:-1]
145 args.PrivateKeyFileName = os.path.join(os.path.dirname(os.path.realpath(RsaToolPath)), TEST_SIGNING_PRIVATE_KEY_FILENAME)
146 args.PrivateKeyFile = open(args.PrivateKeyFileName, 'rb')
147 args.PrivateKeyFile.close()
148 except:
149 print('ERROR: test signing private key file %s missing' % (args.PrivateKeyFileName))
150 sys.exit(1)
151
152 #
153 # Extract public key from private key into STDOUT
154 #
155 Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
156 PublicKeyHexString = Process.communicate()[0].split(b'=')[1].strip()
157 PublicKeyHexString = PublicKeyHexString.decode('utf-8')
158 PublicKey = ''
159 while len(PublicKeyHexString) > 0:
160 PublicKey = PublicKey + PublicKeyHexString[0:2]
161 PublicKeyHexString=PublicKeyHexString[2:]
162 if Process.returncode != 0:
163 sys.exit(Process.returncode)
164
165 if args.MonotonicCountStr:
166 try:
167 if args.MonotonicCountStr.upper().startswith('0X'):
168 args.MonotonicCountValue = int(args.MonotonicCountStr, 16)
169 else:
170 args.MonotonicCountValue = int(args.MonotonicCountStr)
171 except:
172 pass
173
174 if args.Encode:
175 FullInputFileBuffer = args.InputFileBuffer
176 if args.MonotonicCountStr:
177 format = "%dsQ" % len(args.InputFileBuffer)
178 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)
179 #
180 # Sign the input file using the specified private key and capture signature from STDOUT
181 #
182 Process = subprocess.Popen('%s dgst -sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
183 Signature = Process.communicate(input=FullInputFileBuffer)[0]
184 if Process.returncode != 0:
185 sys.exit(Process.returncode)
186
187 #
188 # Write output file that contains hash GUID, Public Key, Signature, and Input data
189 #
190 args.OutputFile = open(args.OutputFileName, 'wb')
191 args.OutputFile.write(EFI_HASH_ALGORITHM_SHA256_GUID.bytes_le)
192 args.OutputFile.write(bytearray.fromhex(str(PublicKey)))
193 args.OutputFile.write(Signature)
194 args.OutputFile.write(args.InputFileBuffer)
195 args.OutputFile.close()
196
197 if args.Decode:
198 #
199 # Parse Hash Type, Public Key, and Signature from the section header
200 #
201 Header = EFI_CERT_BLOCK_RSA_2048_SHA256._make(EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.unpack_from(args.InputFileBuffer))
202 args.InputFileBuffer = args.InputFileBuffer[EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.size:]
203
204 #
205 # Verify that the Hash Type matches the expected SHA256 type
206 #
207 if uuid.UUID(bytes_le = Header.HashType) != EFI_HASH_ALGORITHM_SHA256_GUID:
208 print('ERROR: unsupport hash GUID')
209 sys.exit(1)
210
211 #
212 # Verify the public key
213 #
214 if Header.PublicKey != bytearray.fromhex(PublicKey):
215 print('ERROR: Public key in input file does not match public key from private key file')
216 sys.exit(1)
217
218 FullInputFileBuffer = args.InputFileBuffer
219 if args.MonotonicCountStr:
220 format = "%dsQ" % len(args.InputFileBuffer)
221 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)
222
223 #
224 # Write Signature to output file
225 #
226 open(args.OutputFileName, 'wb').write(Header.Signature)
227
228 #
229 # Verify signature
230 #
231 Process = subprocess.Popen('%s dgst -sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
232 Process.communicate(input=FullInputFileBuffer)
233 if Process.returncode != 0:
234 print('ERROR: Verification failed')
235 os.remove (args.OutputFileName)
236 sys.exit(Process.returncode)
237
238 #
239 # Save output file contents from input file
240 #
241 open(args.OutputFileName, 'wb').write(args.InputFileBuffer)