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 # SPDX-License-Identifier: BSD-2-Clause-Patent
16 from __future__
import print_function
25 from Common
.BuildVersion
import gBUILD_VERSION
28 # Globals for help information
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__
)
36 # GUID for PKCS7 from UEFI Specification
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}')
43 # typedef struct _WIN_CERTIFICATE {
46 # UINT16 wCertificateType;
47 # //UINT8 bCertificate[ANYSIZE_ARRAY];
50 # typedef struct _WIN_CERTIFICATE_UEFI_GUID {
51 # WIN_CERTIFICATE Hdr;
53 # //UINT8 CertData[ANYSIZE_ARRAY];
54 # } WIN_CERTIFICATE_UEFI_GUID;
57 # UINT64 MonotonicCount;
58 # WIN_CERTIFICATE_UEFI_GUID AuthInfo;
59 # } EFI_FIRMWARE_IMAGE_AUTHENTICATION;
63 # Filename of test signing private cert that is stored in same directory as this tool
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'
69 if __name__
== '__main__':
71 # Create command line argument parser object
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")
90 # Parse command line arguments
92 args
= parser
.parse_args()
95 # Generate file path to Open SSL command
97 OpenSslCommand
= 'openssl'
99 OpenSslPath
= os
.environ
['OPENSSL_PATH']
100 OpenSslCommand
= os
.path
.join(OpenSslPath
, OpenSslCommand
)
101 if ' ' in OpenSslCommand
:
102 OpenSslCommand
= '"' + OpenSslCommand
+ '"'
107 # Verify that Open SSL command is available
110 Process
= subprocess
.Popen('%s version' % (OpenSslCommand
), stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
112 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
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())
122 # Read input file into a buffer and save input filename
124 args
.InputFileName
= args
.InputFile
.name
125 args
.InputFileBuffer
= args
.InputFile
.read()
126 args
.InputFile
.close()
129 # Save output filename and check if path exists
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
)
135 args
.OutputFileName
= args
.OutputFile
138 if args
.MonotonicCountStr
.upper().startswith('0X'):
139 args
.MonotonicCountValue
= int(args
.MonotonicCountStr
, 16)
141 args
.MonotonicCountValue
= int(args
.MonotonicCountStr
)
143 args
.MonotonicCountValue
= int(0)
147 # Save signer private cert filename and close private cert file
150 args
.SignerPrivateCertFileName
= args
.SignerPrivateCertFile
.name
151 args
.SignerPrivateCertFile
.close()
155 # Get path to currently executing script or executable
157 if hasattr(sys
, 'frozen'):
158 Pkcs7ToolPath
= sys
.executable
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()
169 print('ERROR: test signer private cert file %s missing' % (args
.SignerPrivateCertFileName
))
173 # Save other public cert filename and close public cert file
176 args
.OtherPublicCertFileName
= args
.OtherPublicCertFile
.name
177 args
.OtherPublicCertFile
.close()
181 # Get path to currently executing script or executable
183 if hasattr(sys
, 'frozen'):
184 Pkcs7ToolPath
= sys
.executable
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()
195 print('ERROR: test other public cert file %s missing' % (args
.OtherPublicCertFileName
))
198 format
= "%dsQ" % len(args
.InputFileBuffer
)
199 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
202 # Sign the input file using the specified private key and capture signature from STDOUT
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
)
210 # Write output file that contains Signature, and Input data
212 args
.OutputFile
= open(args
.OutputFileName
, 'wb')
213 args
.OutputFile
.write(Signature
)
214 args
.OutputFile
.write(args
.InputFileBuffer
)
215 args
.OutputFile
.close()
219 # Save trusted public cert filename and close public cert file
222 args
.TrustedPublicCertFileName
= args
.TrustedPublicCertFile
.name
223 args
.TrustedPublicCertFile
.close()
227 # Get path to currently executing script or executable
229 if hasattr(sys
, 'frozen'):
230 Pkcs7ToolPath
= sys
.executable
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()
241 print('ERROR: test trusted public cert file %s missing' % (args
.TrustedPublicCertFileName
))
244 if not args
.SignatureSizeStr
:
245 print("ERROR: please use the option --signature-size to specify the size of the signature data!")
248 if args
.SignatureSizeStr
.upper().startswith('0X'):
249 SignatureSize
= int(args
.SignatureSizeStr
, 16)
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!")
255 elif SignatureSize
> len(args
.InputFileBuffer
):
256 print("ERROR: The value of option --signature-size is exceed the size of the input file !")
259 args
.SignatureBuffer
= args
.InputFileBuffer
[0:SignatureSize
]
260 args
.InputFileBuffer
= args
.InputFileBuffer
[SignatureSize
:]
262 format
= "%dsQ" % len(args
.InputFileBuffer
)
263 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
266 # Save output file contents from input file
268 open(args
.OutputFileName
, 'wb').write(FullInputFileBuffer
)
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
)
280 open(args
.OutputFileName
, 'wb').write(args
.InputFileBuffer
)