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
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
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.
28 from Common
.BuildVersion
import gBUILD_VERSION
31 # Globals for help information
33 __prog__
= 'Rsa2048Sha256Sign'
34 __version__
= '%s Version %s' % (__prog__
, '0.9 ' + gBUILD_VERSION
)
35 __copyright__
= 'Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.'
36 __usage__
= '%s -e|-d [options] <input_file>' % (__prog__
)
39 # GUID for SHA 256 Hash Algorithm from UEFI Specification
41 EFI_HASH_ALGORITHM_SHA256_GUID
= uuid
.UUID('{51aa59de-fdf2-4ea3-bc63-875fb7842ee9}')
44 # Structure defintion to unpack EFI_CERT_BLOCK_RSA_2048_SHA256 from UEFI 2.4 Specification
46 # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
48 # UINT8 PublicKey[256];
49 # UINT8 Signature[256];
50 # } EFI_CERT_BLOCK_RSA_2048_SHA256;
52 EFI_CERT_BLOCK_RSA_2048_SHA256
= collections
.namedtuple('EFI_CERT_BLOCK_RSA_2048_SHA256', ['HashType', 'PublicKey', 'Signature'])
53 EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT
= struct
.Struct('16s256s256s')
56 # Filename of test signing private key that is stored in same directory as this tool
58 TEST_SIGNING_PRIVATE_KEY_FILENAME
= 'TestSigningPrivateKey.pem'
60 if __name__
== '__main__':
62 # Create command line argument parser object
64 parser
= argparse
.ArgumentParser(prog
=__prog__
, usage
=__usage__
, description
=__copyright__
, conflict_handler
='resolve')
65 group
= parser
.add_mutually_exclusive_group(required
=True)
66 group
.add_argument("--version", action
='version', version
=__version__
)
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 parser
.add_argument("-o", "--output", dest
='OutputFile', type=str, metavar
='filename', help="specify the output filename", required
=True)
70 parser
.add_argument("--monotonic-count", dest
='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule.")
71 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.")
72 parser
.add_argument("-v", "--verbose", dest
='Verbose', action
="store_true", help="increase output messages")
73 parser
.add_argument("-q", "--quiet", dest
='Quiet', action
="store_true", help="reduce output messages")
74 parser
.add_argument("--debug", dest
='Debug', type=int, metavar
='[0-9]', choices
=range(0, 10), default
=0, help="set debug level")
75 parser
.add_argument(metavar
="input_file", dest
='InputFile', type=argparse
.FileType('rb'), help="specify the input filename")
78 # Parse command line arguments
80 args
= parser
.parse_args()
83 # Generate file path to Open SSL command
85 OpenSslCommand
= 'openssl'
87 OpenSslPath
= os
.environ
['OPENSSL_PATH']
88 OpenSslCommand
= os
.path
.join(OpenSslPath
, OpenSslCommand
)
89 if ' ' in OpenSslCommand
:
90 OpenSslCommand
= '"' + OpenSslCommand
+ '"'
95 # Verify that Open SSL command is available
98 Process
= subprocess
.Popen('%s version' % (OpenSslCommand
), stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
100 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
103 Version
= Process
.communicate()
104 if Process
.returncode
!= 0:
105 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')
106 sys
.exit(Process
.returncode
)
107 print(Version
[0].decode())
110 # Read input file into a buffer and save input filename
112 args
.InputFileName
= args
.InputFile
.name
113 args
.InputFileBuffer
= args
.InputFile
.read()
114 args
.InputFile
.close()
117 # Save output filename and check if path exists
119 OutputDir
= os
.path
.dirname(args
.OutputFile
)
120 if not os
.path
.exists(OutputDir
):
121 print('ERROR: The output path does not exist: %s' % OutputDir
)
123 args
.OutputFileName
= args
.OutputFile
126 # Save private key filename and close private key file
129 args
.PrivateKeyFileName
= args
.PrivateKeyFile
.name
130 args
.PrivateKeyFile
.close()
134 # Get path to currently executing script or executable
136 if hasattr(sys
, 'frozen'):
137 RsaToolPath
= sys
.executable
139 RsaToolPath
= sys
.argv
[0]
140 if RsaToolPath
.startswith('"'):
141 RsaToolPath
= RsaToolPath
[1:]
142 if RsaToolPath
.endswith('"'):
143 RsaToolPath
= RsaToolPath
[:-1]
144 args
.PrivateKeyFileName
= os
.path
.join(os
.path
.dirname(os
.path
.realpath(RsaToolPath
)), TEST_SIGNING_PRIVATE_KEY_FILENAME
)
145 args
.PrivateKeyFile
= open(args
.PrivateKeyFileName
, 'rb')
146 args
.PrivateKeyFile
.close()
148 print('ERROR: test signing private key file %s missing' % (args
.PrivateKeyFileName
))
152 # Extract public key from private key into STDOUT
154 Process
= subprocess
.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand
, args
.PrivateKeyFileName
), stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
155 PublicKeyHexString
= Process
.communicate()[0].split(b
'=')[1].strip()
156 PublicKeyHexString
= PublicKeyHexString
.decode(encoding
='utf-8')
158 while len(PublicKeyHexString
) > 0:
159 PublicKey
= PublicKey
+ PublicKeyHexString
[0:2]
160 PublicKeyHexString
=PublicKeyHexString
[2:]
161 if Process
.returncode
!= 0:
162 sys
.exit(Process
.returncode
)
164 if args
.MonotonicCountStr
:
166 if args
.MonotonicCountStr
.upper().startswith('0X'):
167 args
.MonotonicCountValue
= (int)(args
.MonotonicCountStr
, 16)
169 args
.MonotonicCountValue
= (int)(args
.MonotonicCountStr
)
174 FullInputFileBuffer
= args
.InputFileBuffer
175 if args
.MonotonicCountStr
:
176 format
= "%dsQ" % len(args
.InputFileBuffer
)
177 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
179 # Sign the input file using the specified private key and capture signature from STDOUT
181 Process
= subprocess
.Popen('%s dgst -sha256 -sign "%s"' % (OpenSslCommand
, args
.PrivateKeyFileName
), stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, shell
=True)
182 Signature
= Process
.communicate(input=FullInputFileBuffer
)[0]
183 if Process
.returncode
!= 0:
184 sys
.exit(Process
.returncode
)
187 # Write output file that contains hash GUID, Public Key, Signature, and Input data
189 args
.OutputFile
= open(args
.OutputFileName
, 'wb')
190 args
.OutputFile
.write(EFI_HASH_ALGORITHM_SHA256_GUID
.bytes_le
)
191 args
.OutputFile
.write(bytearray
.fromhex(PublicKey
))
192 args
.OutputFile
.write(Signature
)
193 args
.OutputFile
.write(args
.InputFileBuffer
)
194 args
.OutputFile
.close()
198 # Parse Hash Type, Public Key, and Signature from the section header
200 Header
= EFI_CERT_BLOCK_RSA_2048_SHA256
._make(EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT
.unpack_from(args
.InputFileBuffer
))
201 args
.InputFileBuffer
= args
.InputFileBuffer
[EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT
.size
:]
204 # Verify that the Hash Type matches the expected SHA256 type
206 if uuid
.UUID(bytes_le
= Header
.HashType
) != EFI_HASH_ALGORITHM_SHA256_GUID
:
207 print('ERROR: unsupport hash GUID')
211 # Verify the public key
213 if Header
.PublicKey
!= bytearray
.fromhex(PublicKey
):
214 print('ERROR: Public key in input file does not match public key from private key file')
217 FullInputFileBuffer
= args
.InputFileBuffer
218 if args
.MonotonicCountStr
:
219 format
= "%dsQ" % len(args
.InputFileBuffer
)
220 FullInputFileBuffer
= struct
.pack(format
, args
.InputFileBuffer
, args
.MonotonicCountValue
)
223 # Write Signature to output file
225 open(args
.OutputFileName
, 'wb').write(Header
.Signature
)
230 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)
231 Process
.communicate(input=FullInputFileBuffer
)
232 if Process
.returncode
!= 0:
233 print('ERROR: Verification failed')
234 os
.remove (args
.OutputFileName
)
235 sys
.exit(Process
.returncode
)
238 # Save output file contents from input file
240 open(args
.OutputFileName
, 'wb').write(args
.InputFileBuffer
)