2 # This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.
4 # This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID
5 # {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7}}
7 # This tool has been tested with OpenSSL.
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
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.
22 from __future__
import print_function
31 from Common
.BuildVersion
import gBUILD_VERSION
34 # Globals for help information
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__
)
42 # GUID for PKCS7 from UEFI Specification
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}')
49 # typedef struct _WIN_CERTIFICATE {
52 # UINT16 wCertificateType;
53 # //UINT8 bCertificate[ANYSIZE_ARRAY];
56 # typedef struct _WIN_CERTIFICATE_UEFI_GUID {
57 # WIN_CERTIFICATE Hdr;
59 # //UINT8 CertData[ANYSIZE_ARRAY];
60 # } WIN_CERTIFICATE_UEFI_GUID;
63 # UINT64 MonotonicCount;
64 # WIN_CERTIFICATE_UEFI_GUID AuthInfo;
65 # } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
69 # Filename of test signing private cert that is stored in same directory as this tool
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'
75 if __name__
== '__main__':
77 # Create command line argument parser object
79 parser
= argparse
.ArgumentParser(prog
=__prog__
, 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 group
.add_argument("--version", action
='version', version
=__version__
)
84 parser
.add_argument("-o", "--output", dest
='OutputFile', type=str, metavar
='filename', help="specify the output filename", required
=True)
85 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.")
86 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.")
87 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.")
88 parser
.add_argument("--monotonic-count", dest
='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule. If not specified, 0 is used.")
89 parser
.add_argument("--signature-size", dest
='SignatureSizeStr', type=str, help="specify the signature size for decode process.")
90 parser
.add_argument("-v", "--verbose", dest
='Verbose', action
="store_true", help="increase output messages")
91 parser
.add_argument("-q", "--quiet", dest
='Quiet', action
="store_true", help="reduce output messages")
92 parser
.add_argument("--debug", dest
='Debug', type=int, metavar
='[0-9]', choices
=range(0, 10), default
=0, help="set debug level")
93 parser
.add_argument(metavar
="input_file", dest
='InputFile', type=argparse
.FileType('rb'), help="specify the input filename")
96 # Parse command line arguments
98 args
= parser
.parse_args()
101 # Generate file path to Open SSL command
103 OpenSslCommand
= 'openssl'
105 OpenSslPath
= os
.environ
['OPENSSL_PATH']
106 OpenSslCommand
= os
.path
.join(OpenSslPath
, OpenSslCommand
)
107 if ' ' in OpenSslCommand
:
108 OpenSslCommand
= '"' + OpenSslCommand
+ '"'
113 # Verify that Open SSL command is available
116 Process
= subprocess
.Popen('%s version' % (OpenSslCommand
), stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
118 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
121 Version
= Process
.communicate()
122 if Process
.returncode
!= 0:
123 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
124 sys
.exit(Process
.returncode
)
125 print(Version
[0].decode())
128 # Read input file into a buffer and save input filename
130 args
.InputFileName
= args
.InputFile
.name
131 args
.InputFileBuffer
= args
.InputFile
.read()
132 args
.InputFile
.close()
135 # Save output filename and check if path exists
137 OutputDir
= os
.path
.dirname(args
.OutputFile
)
138 if not os
.path
.exists(OutputDir
):
139 print('ERROR: The output path does not exist: %s' % OutputDir
)
141 args
.OutputFileName
= args
.OutputFile
144 if args
.MonotonicCountStr
.upper().startswith('0X'):
145 args
.MonotonicCountValue
= int(args
.MonotonicCountStr
, 16)
147 args
.MonotonicCountValue
= int(args
.MonotonicCountStr
)
149 args
.MonotonicCountValue
= int(0)
153 # Save signer private cert filename and close private cert file
156 args
.SignerPrivateCertFileName
= args
.SignerPrivateCertFile
.name
157 args
.SignerPrivateCertFile
.close()
161 # Get path to currently executing script or executable
163 if hasattr(sys
, 'frozen'):
164 Pkcs7ToolPath
= sys
.executable
166 Pkcs7ToolPath
= sys
.argv
[0]
167 if Pkcs7ToolPath
.startswith('"'):
168 Pkcs7ToolPath
= Pkcs7ToolPath
[1:]
169 if Pkcs7ToolPath
.endswith('"'):
170 Pkcs7ToolPath
= RsaToolPath
[:-1]
171 args
.SignerPrivateCertFileName
= os
.path
.join(os
.path
.dirname(os
.path
.realpath(Pkcs7ToolPath
)), TEST_SIGNER_PRIVATE_CERT_FILENAME
)
172 args
.SignerPrivateCertFile
= open(args
.SignerPrivateCertFileName
, 'rb')
173 args
.SignerPrivateCertFile
.close()
175 print('ERROR: test signer private cert file %s missing' % (args
.SignerPrivateCertFileName
))
179 # Save other public cert filename and close public cert file
182 args
.OtherPublicCertFileName
= args
.OtherPublicCertFile
.name
183 args
.OtherPublicCertFile
.close()
187 # Get path to currently executing script or executable
189 if hasattr(sys
, 'frozen'):
190 Pkcs7ToolPath
= sys
.executable
192 Pkcs7ToolPath
= sys
.argv
[0]
193 if Pkcs7ToolPath
.startswith('"'):
194 Pkcs7ToolPath
= Pkcs7ToolPath
[1:]
195 if Pkcs7ToolPath
.endswith('"'):
196 Pkcs7ToolPath
= RsaToolPath
[:-1]
197 args
.OtherPublicCertFileName
= os
.path
.join(os
.path
.dirname(os
.path
.realpath(Pkcs7ToolPath
)), TEST_OTHER_PUBLIC_CERT_FILENAME
)
198 args
.OtherPublicCertFile
= open(args
.OtherPublicCertFileName
, 'rb')
199 args
.OtherPublicCertFile
.close()
201 print('ERROR: test other public cert file %s missing' % (args
.OtherPublicCertFileName
))
204 format
= "%dsQ" % len(args
.InputFileBuffer
)
205 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
208 # Sign the input file using the specified private key and capture signature from STDOUT
210 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)
211 Signature
= Process
.communicate(input=FullInputFileBuffer
)[0]
212 if Process
.returncode
!= 0:
213 sys
.exit(Process
.returncode
)
216 # Write output file that contains Signature, and Input data
218 args
.OutputFile
= open(args
.OutputFileName
, 'wb')
219 args
.OutputFile
.write(Signature
)
220 args
.OutputFile
.write(args
.InputFileBuffer
)
221 args
.OutputFile
.close()
225 # Save trusted public cert filename and close public cert file
228 args
.TrustedPublicCertFileName
= args
.TrustedPublicCertFile
.name
229 args
.TrustedPublicCertFile
.close()
233 # Get path to currently executing script or executable
235 if hasattr(sys
, 'frozen'):
236 Pkcs7ToolPath
= sys
.executable
238 Pkcs7ToolPath
= sys
.argv
[0]
239 if Pkcs7ToolPath
.startswith('"'):
240 Pkcs7ToolPath
= Pkcs7ToolPath
[1:]
241 if Pkcs7ToolPath
.endswith('"'):
242 Pkcs7ToolPath
= RsaToolPath
[:-1]
243 args
.TrustedPublicCertFileName
= os
.path
.join(os
.path
.dirname(os
.path
.realpath(Pkcs7ToolPath
)), TEST_TRUSTED_PUBLIC_CERT_FILENAME
)
244 args
.TrustedPublicCertFile
= open(args
.TrustedPublicCertFileName
, 'rb')
245 args
.TrustedPublicCertFile
.close()
247 print('ERROR: test trusted public cert file %s missing' % (args
.TrustedPublicCertFileName
))
250 if not args
.SignatureSizeStr
:
251 print("ERROR: please use the option --signature-size to specify the size of the signature data!")
254 if args
.SignatureSizeStr
.upper().startswith('0X'):
255 SignatureSize
= int(args
.SignatureSizeStr
, 16)
257 SignatureSize
= int(args
.SignatureSizeStr
)
258 if SignatureSize
< 0:
259 print("ERROR: The value of option --signature-size can't be set to negative value!")
261 elif SignatureSize
> len(args
.InputFileBuffer
):
262 print("ERROR: The value of option --signature-size is exceed the size of the input file !")
265 args
.SignatureBuffer
= args
.InputFileBuffer
[0:SignatureSize
]
266 args
.InputFileBuffer
= args
.InputFileBuffer
[SignatureSize
:]
268 format
= "%dsQ" % len(args
.InputFileBuffer
)
269 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
272 # Save output file contents from input file
274 open(args
.OutputFileName
, 'wb').write(FullInputFileBuffer
)
279 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)
280 Process
.communicate(input=args
.SignatureBuffer
)[0]
281 if Process
.returncode
!= 0:
282 print('ERROR: Verification failed')
283 os
.remove (args
.OutputFileName
)
284 sys
.exit(Process
.returncode
)
286 open(args
.OutputFileName
, 'wb').write(args
.InputFileBuffer
)