]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / BaseTools / Source / Python / Pkcs7Sign / Pkcs7Sign.py
1 ## @file
2 # This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
3 #
4 # This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID
5 # {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7}}
6 #
7 # This tool has been tested with OpenSSL.
8 #
9 # Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>
10 # SPDX-License-Identifier: BSD-2-Clause-Patent
11 #
12
13 '''
14 Pkcs7Sign
15 '''
16 from __future__ import print_function
17
18 import os
19 import sys
20 import argparse
21 import subprocess
22 import uuid
23 import struct
24 import collections
25 from Common.BuildVersion import gBUILD_VERSION
26
27 #
28 # Globals for help information
29 #
30 __prog__ = 'Pkcs7Sign'
31 __version__ = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
32 __copyright__ = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'
33 __usage__ = '%s -e|-d [options] <input_file>' % (__prog__)
34
35 #
36 # GUID for PKCS7 from UEFI Specification
37 #
38 WIN_CERT_REVISION = 0x0200
39 WIN_CERT_TYPE_EFI_GUID = 0x0EF1
40 EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')
41
42 #
43 # typedef struct _WIN_CERTIFICATE {
44 # UINT32 dwLength;
45 # UINT16 wRevision;
46 # UINT16 wCertificateType;
47 # //UINT8 bCertificate[ANYSIZE_ARRAY];
48 # } WIN_CERTIFICATE;
49 #
50 # typedef struct _WIN_CERTIFICATE_UEFI_GUID {
51 # WIN_CERTIFICATE Hdr;
52 # EFI_GUID CertType;
53 # //UINT8 CertData[ANYSIZE_ARRAY];
54 # } WIN_CERTIFICATE_UEFI_GUID;
55 #
56 # typedef struct {
57 # UINT64 MonotonicCount;
58 # WIN_CERTIFICATE_UEFI_GUID AuthInfo;
59 # } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
60 #
61
62 #
63 # Filename of test signing private cert that is stored in same directory as this tool
64 #
65 TEST_SIGNER_PRIVATE_CERT_FILENAME = 'TestCert.pem'
66 TEST_OTHER_PUBLIC_CERT_FILENAME = 'TestSub.pub.pem'
67 TEST_TRUSTED_PUBLIC_CERT_FILENAME = 'TestRoot.pub.pem'
68
69 if __name__ == '__main__':
70 #
71 # Create command line argument parser object
72 #
73 parser = argparse.ArgumentParser(prog=__prog__, usage=__usage__, description=__copyright__, conflict_handler='resolve')
74 group = parser.add_mutually_exclusive_group(required=True)
75 group.add_argument("-e", action="store_true", dest='Encode', help='encode file')
76 group.add_argument("-d", action="store_true", dest='Decode', help='decode file')
77 group.add_argument("--version", action='version', version=__version__)
78 parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)
79 parser.add_argument("--signer-private-cert", dest='SignerPrivateCertFile', type=argparse.FileType('rb'), help="specify the signer private cert filename. If not specified, a test signer private cert is used.")
80 parser.add_argument("--other-public-cert", dest='OtherPublicCertFile', type=argparse.FileType('rb'), help="specify the other public cert filename. If not specified, a test other public cert is used.")
81 parser.add_argument("--trusted-public-cert", dest='TrustedPublicCertFile', type=argparse.FileType('rb'), help="specify the trusted public cert filename. If not specified, a test trusted public cert is used.")
82 parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule. If not specified, 0 is used.")
83 parser.add_argument("--signature-size", dest='SignatureSizeStr', type=str, help="specify the signature size for decode process.")
84 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")
85 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")
86 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0, 10), default=0, help="set debug level")
87 parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")
88
89 #
90 # Parse command line arguments
91 #
92 args = parser.parse_args()
93
94 #
95 # Generate file path to Open SSL command
96 #
97 OpenSslCommand = 'openssl'
98 try:
99 OpenSslPath = os.environ['OPENSSL_PATH']
100 OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
101 if ' ' in OpenSslCommand:
102 OpenSslCommand = '"' + OpenSslCommand + '"'
103 except:
104 pass
105
106 #
107 # Verify that Open SSL command is available
108 #
109 try:
110 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
111 except:
112 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
113 sys.exit(1)
114
115 Version = Process.communicate()
116 if Process.returncode != 0:
117 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
118 sys.exit(Process.returncode)
119 print(Version[0].decode())
120
121 #
122 # Read input file into a buffer and save input filename
123 #
124 args.InputFileName = args.InputFile.name
125 args.InputFileBuffer = args.InputFile.read()
126 args.InputFile.close()
127
128 #
129 # Save output filename and check if path exists
130 #
131 OutputDir = os.path.dirname(args.OutputFile)
132 if not os.path.exists(OutputDir):
133 print('ERROR: The output path does not exist: %s' % OutputDir)
134 sys.exit(1)
135 args.OutputFileName = args.OutputFile
136
137 try:
138 if args.MonotonicCountStr.upper().startswith('0X'):
139 args.MonotonicCountValue = int(args.MonotonicCountStr, 16)
140 else:
141 args.MonotonicCountValue = int(args.MonotonicCountStr)
142 except:
143 args.MonotonicCountValue = int(0)
144
145 if args.Encode:
146 #
147 # Save signer private cert filename and close private cert file
148 #
149 try:
150 args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name
151 args.SignerPrivateCertFile.close()
152 except:
153 try:
154 #
155 # Get path to currently executing script or executable
156 #
157 if hasattr(sys, 'frozen'):
158 Pkcs7ToolPath = sys.executable
159 else:
160 Pkcs7ToolPath = sys.argv[0]
161 if Pkcs7ToolPath.startswith('"'):
162 Pkcs7ToolPath = Pkcs7ToolPath[1:]
163 if Pkcs7ToolPath.endswith('"'):
164 Pkcs7ToolPath = RsaToolPath[:-1]
165 args.SignerPrivateCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_SIGNER_PRIVATE_CERT_FILENAME)
166 args.SignerPrivateCertFile = open(args.SignerPrivateCertFileName, 'rb')
167 args.SignerPrivateCertFile.close()
168 except:
169 print('ERROR: test signer private cert file %s missing' % (args.SignerPrivateCertFileName))
170 sys.exit(1)
171
172 #
173 # Save other public cert filename and close public cert file
174 #
175 try:
176 args.OtherPublicCertFileName = args.OtherPublicCertFile.name
177 args.OtherPublicCertFile.close()
178 except:
179 try:
180 #
181 # Get path to currently executing script or executable
182 #
183 if hasattr(sys, 'frozen'):
184 Pkcs7ToolPath = sys.executable
185 else:
186 Pkcs7ToolPath = sys.argv[0]
187 if Pkcs7ToolPath.startswith('"'):
188 Pkcs7ToolPath = Pkcs7ToolPath[1:]
189 if Pkcs7ToolPath.endswith('"'):
190 Pkcs7ToolPath = RsaToolPath[:-1]
191 args.OtherPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_OTHER_PUBLIC_CERT_FILENAME)
192 args.OtherPublicCertFile = open(args.OtherPublicCertFileName, 'rb')
193 args.OtherPublicCertFile.close()
194 except:
195 print('ERROR: test other public cert file %s missing' % (args.OtherPublicCertFileName))
196 sys.exit(1)
197
198 format = "%dsQ" % len(args.InputFileBuffer)
199 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)
200
201 #
202 # Sign the input file using the specified private key and capture signature from STDOUT
203 #
204 Process = subprocess.Popen('%s smime -sign -binary -signer "%s" -outform DER -md sha256 -certfile "%s"' % (OpenSslCommand, args.SignerPrivateCertFileName, args.OtherPublicCertFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
205 Signature = Process.communicate(input=FullInputFileBuffer)[0]
206 if Process.returncode != 0:
207 sys.exit(Process.returncode)
208
209 #
210 # Write output file that contains Signature, and Input data
211 #
212 args.OutputFile = open(args.OutputFileName, 'wb')
213 args.OutputFile.write(Signature)
214 args.OutputFile.write(args.InputFileBuffer)
215 args.OutputFile.close()
216
217 if args.Decode:
218 #
219 # Save trusted public cert filename and close public cert file
220 #
221 try:
222 args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name
223 args.TrustedPublicCertFile.close()
224 except:
225 try:
226 #
227 # Get path to currently executing script or executable
228 #
229 if hasattr(sys, 'frozen'):
230 Pkcs7ToolPath = sys.executable
231 else:
232 Pkcs7ToolPath = sys.argv[0]
233 if Pkcs7ToolPath.startswith('"'):
234 Pkcs7ToolPath = Pkcs7ToolPath[1:]
235 if Pkcs7ToolPath.endswith('"'):
236 Pkcs7ToolPath = RsaToolPath[:-1]
237 args.TrustedPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_TRUSTED_PUBLIC_CERT_FILENAME)
238 args.TrustedPublicCertFile = open(args.TrustedPublicCertFileName, 'rb')
239 args.TrustedPublicCertFile.close()
240 except:
241 print('ERROR: test trusted public cert file %s missing' % (args.TrustedPublicCertFileName))
242 sys.exit(1)
243
244 if not args.SignatureSizeStr:
245 print("ERROR: please use the option --signature-size to specify the size of the signature data!")
246 sys.exit(1)
247 else:
248 if args.SignatureSizeStr.upper().startswith('0X'):
249 SignatureSize = int(args.SignatureSizeStr, 16)
250 else:
251 SignatureSize = int(args.SignatureSizeStr)
252 if SignatureSize < 0:
253 print("ERROR: The value of option --signature-size can't be set to negative value!")
254 sys.exit(1)
255 elif SignatureSize > len(args.InputFileBuffer):
256 print("ERROR: The value of option --signature-size is exceed the size of the input file !")
257 sys.exit(1)
258
259 args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]
260 args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]
261
262 format = "%dsQ" % len(args.InputFileBuffer)
263 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)
264
265 #
266 # Save output file contents from input file
267 #
268 open(args.OutputFileName, 'wb').write(FullInputFileBuffer)
269
270 #
271 # Verify signature
272 #
273 Process = subprocess.Popen('%s smime -verify -inform DER -content %s -CAfile %s' % (OpenSslCommand, args.OutputFileName, args.TrustedPublicCertFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
274 Process.communicate(input=args.SignatureBuffer)[0]
275 if Process.returncode != 0:
276 print('ERROR: Verification failed')
277 os.remove (args.OutputFileName)
278 sys.exit(Process.returncode)
279
280 open(args.OutputFileName, 'wb').write(args.InputFileBuffer)