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