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