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