b83c9d4d42c43bc163c05417a5d67f51c8f7891d
[mirror_edk2.git] / BaseTools / Source / Python / Rsa2048Sha256Sign / Rsa2048Sha256Sign.py
1 ## @file
2 # This tool encodes and decodes GUIDed FFS sections 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
6 #
7 # Copyright (c) 2013 - 2014, 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
12 #
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.
15 #
16
17 '''
18 Rsa2048Sha256Sign
19 '''
20
21 import os
22 import sys
23 import argparse
24 import subprocess
25 import uuid
26 import struct
27 import collections
28 from Common.BuildVersion import gBUILD_VERSION
29
30 #
31 # Globals for help information
32 #
33 __prog__ = 'Rsa2048Sha256Sign'
34 __version__ = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)
35 __copyright__ = 'Copyright (c) 2013 - 2014, Intel Corporation. All rights reserved.'
36 __usage__ = '%s -e|-d [options] <input_file>' % (__prog__)
37
38 #
39 # GUID for SHA 256 Hash Algorithm from UEFI Specification
40 #
41 EFI_HASH_ALGORITHM_SHA256_GUID = uuid.UUID('{51aa59de-fdf2-4ea3-bc63-875fb7842ee9}')
42
43 #
44 # Structure defintion to unpack EFI_CERT_BLOCK_RSA_2048_SHA256 from UEFI 2.4 Specification
45 #
46 # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 {
47 # EFI_GUID HashType;
48 # UINT8 PublicKey[256];
49 # UINT8 Signature[256];
50 # } EFI_CERT_BLOCK_RSA_2048_SHA256;
51 #
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')
54
55 #
56 # Filename of test signing private key that is stored in same directory as this tool
57 #
58 TEST_SIGNING_PRIVATE_KEY_FILENAME = 'TestSigningPrivateKey.pem'
59
60 if __name__ == '__main__':
61 #
62 # Create command line argument parser object
63 #
64 parser = argparse.ArgumentParser(prog=__prog__, version=__version__, usage=__usage__, description=__copyright__, conflict_handler='resolve')
65 group = parser.add_mutually_exclusive_group(required=True)
66 group.add_argument("-e", action="store_true", dest='Encode', help='encode file')
67 group.add_argument("-d", action="store_true", dest='Decode', help='decode file')
68 parser.add_argument("-o", "--output", dest='OutputFile', type=argparse.FileType('wb'), metavar='filename', help="specify the output filename", required=True)
69 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.")
70 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")
71 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")
72 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")
73 parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")
74
75 #
76 # Parse command line arguments
77 #
78 args = parser.parse_args()
79
80 #
81 # Generate file path to Open SSL command
82 #
83 OpenSslCommand = 'openssl'
84 try:
85 OpenSslPath = os.environ['OPENSSL_PATH']
86 OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)
87 except:
88 pass
89
90 #
91 # Verify that Open SSL command is available
92 #
93 try:
94 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
95 except:
96 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'
97 sys.exit(1)
98
99 Version = Process.communicate()
100 if Process.returncode <> 0:
101 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'
102 sys.exit(Process.returncode)
103 print Version[0]
104
105 #
106 # Read input file into a buffer and save input filename
107 #
108 args.InputFileName = args.InputFile.name
109 args.InputFileBuffer = args.InputFile.read()
110 args.InputFile.close()
111
112 #
113 # Save output filename and close output file
114 #
115 args.OutputFileName = args.OutputFile.name
116 args.OutputFile.close()
117
118 #
119 # Save private key filename and close private key file
120 #
121 try:
122 args.PrivateKeyFileName = args.PrivateKeyFile.name
123 args.PrivateKeyFile.close()
124 except:
125 try:
126 #
127 # Get path to currently executing script or executable
128 #
129 if hasattr(sys, 'frozen'):
130 RsaToolPath = sys.executable
131 else:
132 RsaToolPath = sys.argv[0]
133 if RsaToolPath.startswith('"'):
134 RsaToolPath = RsaToolPath[1:]
135 if RsaToolPath.endswith('"'):
136 RsaToolPath = RsaToolPath[:-1]
137 args.PrivateKeyFileName = os.path.join(os.path.dirname(os.path.realpath(RsaToolPath)), TEST_SIGNING_PRIVATE_KEY_FILENAME)
138 args.PrivateKeyFile = open(args.PrivateKeyFileName, 'rb')
139 args.PrivateKeyFile.close()
140 except:
141 print 'ERROR: test signing private key file %s missing' % (args.PrivateKeyFileName)
142 sys.exit(1)
143
144 #
145 # Extract public key from private key into STDOUT
146 #
147 Process = subprocess.Popen('%s rsa -in "%s" -modulus -noout' % (OpenSslCommand, args.PrivateKeyFileName), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
148 PublicKeyHexString = Process.communicate()[0].split('=')[1].strip()
149 PublicKey = ''
150 while len(PublicKeyHexString) > 0:
151 PublicKey = PublicKey + chr(int(PublicKeyHexString[0:2],16))
152 PublicKeyHexString=PublicKeyHexString[2:]
153 if Process.returncode <> 0:
154 sys.exit(Process.returncode)
155
156 if args.Encode:
157 #
158 # Sign the input file using the specified private key and capture signature from STDOUT
159 #
160 Process = subprocess.Popen('%s sha256 -sign "%s"' % (OpenSslCommand, args.PrivateKeyFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
161 Signature = Process.communicate(input=args.InputFileBuffer)[0]
162 if Process.returncode <> 0:
163 sys.exit(Process.returncode)
164
165 #
166 # Write output file that contains hash GUID, Public Key, Signature, and Input data
167 #
168 args.OutputFile = open(args.OutputFileName, 'wb')
169 args.OutputFile.write(EFI_HASH_ALGORITHM_SHA256_GUID.get_bytes_le())
170 args.OutputFile.write(PublicKey)
171 args.OutputFile.write(Signature)
172 args.OutputFile.write(args.InputFileBuffer)
173 args.OutputFile.close()
174
175 if args.Decode:
176 #
177 # Parse Hash Type, Public Key, and Signature from the section header
178 #
179 Header = EFI_CERT_BLOCK_RSA_2048_SHA256._make(EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.unpack_from(args.InputFileBuffer))
180 args.InputFileBuffer = args.InputFileBuffer[EFI_CERT_BLOCK_RSA_2048_SHA256_STRUCT.size:]
181
182 #
183 # Verify that the Hash Type matches the expected SHA256 type
184 #
185 if uuid.UUID(bytes_le = Header.HashType) <> EFI_HASH_ALGORITHM_SHA256_GUID:
186 print 'ERROR: unsupport hash GUID'
187 sys.exit(1)
188
189 #
190 # Verify the public key
191 #
192 if Header.PublicKey <> PublicKey:
193 print 'ERROR: Public key in input file does not match public key from private key file'
194 sys.exit(1)
195
196 #
197 # Write Signature to output file
198 #
199 open(args.OutputFileName, 'wb').write(Header.Signature)
200
201 #
202 # Verify signature
203 #
204 Process = subprocess.Popen('%s sha256 -prverify "%s" -signature %s' % (OpenSslCommand, args.PrivateKeyFileName, args.OutputFileName), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
205 Process.communicate(args.InputFileBuffer)
206 if Process.returncode <> 0:
207 print 'ERROR: Verification failed'
208 os.remove (args.OutputFileName)
209 sys.exit(Process.returncode)
210
211 #
212 # Save output file contents from input file
213 #
214 open(args.OutputFileName, 'wb').write(args.InputFileBuffer)