]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py
BaseTools/Pkcs7Sign: Update the test certificates & Readme.md
[mirror_edk2.git] / BaseTools / Source / Python / Pkcs7Sign / Pkcs7Sign.py
CommitLineData
11eaa7af
YZ
1## @file\r
2# This tool adds EFI_FIRMWARE_IMAGE_AUTHENTICATION for a binary.\r
3#\r
4# This tool only support CertType - EFI_CERT_TYPE_PKCS7_GUID\r
5# {0x4aafd29d, 0x68df, 0x49ee, {0x8a, 0xa9, 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7}}\r
6#\r
7# This tool has been tested with OpenSSL.\r
8#\r
8a0933f4 9# Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.<BR>\r
11eaa7af
YZ
10# This program and the accompanying materials\r
11# are licensed and made available under the terms and conditions of the BSD License\r
12# which accompanies this distribution. The full text of the license may be found at\r
13# http://opensource.org/licenses/bsd-license.php\r
14#\r
15# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
16# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
17#\r
18\r
19'''\r
20Pkcs7Sign\r
21'''\r
22\r
23import os\r
24import sys\r
25import argparse\r
26import subprocess\r
27import uuid\r
28import struct\r
29import collections\r
30from Common.BuildVersion import gBUILD_VERSION\r
31\r
32#\r
33# Globals for help information\r
34#\r
35__prog__ = 'Pkcs7Sign'\r
36__version__ = '%s Version %s' % (__prog__, '0.9 ' + gBUILD_VERSION)\r
37__copyright__ = 'Copyright (c) 2016, Intel Corporation. All rights reserved.'\r
38__usage__ = '%s -e|-d [options] <input_file>' % (__prog__)\r
39\r
40#\r
41# GUID for PKCS7 from UEFI Specification\r
42#\r
43WIN_CERT_REVISION = 0x0200\r
44WIN_CERT_TYPE_EFI_GUID = 0x0EF1\r
45EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}')\r
46\r
47#\r
48# typedef struct _WIN_CERTIFICATE {\r
49# UINT32 dwLength;\r
50# UINT16 wRevision;\r
51# UINT16 wCertificateType;\r
52# //UINT8 bCertificate[ANYSIZE_ARRAY];\r
53# } WIN_CERTIFICATE;\r
54#\r
55# typedef struct _WIN_CERTIFICATE_UEFI_GUID {\r
56# WIN_CERTIFICATE Hdr;\r
57# EFI_GUID CertType;\r
58# //UINT8 CertData[ANYSIZE_ARRAY];\r
59# } WIN_CERTIFICATE_UEFI_GUID;\r
60#\r
61# typedef struct {\r
62# UINT64 MonotonicCount;\r
63# WIN_CERTIFICATE_UEFI_GUID AuthInfo;\r
64# } EFI_FIRMWARE_IMAGE_AUTHENTICATION;\r
65#\r
66\r
67#\r
68# Filename of test signing private cert that is stored in same directory as this tool\r
69#\r
70TEST_SIGNER_PRIVATE_CERT_FILENAME = 'TestCert.pem'\r
71TEST_OTHER_PUBLIC_CERT_FILENAME = 'TestSub.pub.pem'\r
72TEST_TRUSTED_PUBLIC_CERT_FILENAME = 'TestRoot.pub.pem'\r
73\r
74if __name__ == '__main__':\r
75 #\r
76 # Create command line argument parser object\r
77 #\r
78 parser = argparse.ArgumentParser(prog=__prog__, version=__version__, usage=__usage__, description=__copyright__, conflict_handler='resolve')\r
79 group = parser.add_mutually_exclusive_group(required=True)\r
80 group.add_argument("-e", action="store_true", dest='Encode', help='encode file')\r
81 group.add_argument("-d", action="store_true", dest='Decode', help='decode file')\r
82 parser.add_argument("-o", "--output", dest='OutputFile', type=str, metavar='filename', help="specify the output filename", required=True)\r
83 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.")\r
84 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.")\r
85 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.")\r
86 parser.add_argument("--monotonic-count", dest='MonotonicCountStr', type=str, help="specify the MonotonicCount in FMP capsule. If not specified, 0 is used.")\r
87 parser.add_argument("--signature-size", dest='SignatureSizeStr', type=str, help="specify the signature size for decode process.")\r
88 parser.add_argument("-v", "--verbose", dest='Verbose', action="store_true", help="increase output messages")\r
89 parser.add_argument("-q", "--quiet", dest='Quiet', action="store_true", help="reduce output messages")\r
90 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0,10), default=0, help="set debug level")\r
91 parser.add_argument(metavar="input_file", dest='InputFile', type=argparse.FileType('rb'), help="specify the input filename")\r
92\r
93 #\r
94 # Parse command line arguments\r
95 #\r
96 args = parser.parse_args()\r
97\r
98 #\r
99 # Generate file path to Open SSL command\r
100 #\r
101 OpenSslCommand = 'openssl'\r
102 try:\r
103 OpenSslPath = os.environ['OPENSSL_PATH']\r
104 OpenSslCommand = os.path.join(OpenSslPath, OpenSslCommand)\r
105 except:\r
106 pass\r
107\r
108 #\r
109 # Verify that Open SSL command is available\r
110 #\r
111 try:\r
8a0933f4 112 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
11eaa7af
YZ
113 except:\r
114 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'\r
115 sys.exit(1)\r
116\r
117 Version = Process.communicate()\r
118 if Process.returncode <> 0:\r
119 print 'ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH'\r
120 sys.exit(Process.returncode)\r
121 print Version[0]\r
122\r
123 #\r
124 # Read input file into a buffer and save input filename\r
125 #\r
126 args.InputFileName = args.InputFile.name\r
127 args.InputFileBuffer = args.InputFile.read()\r
128 args.InputFile.close()\r
129\r
130 #\r
131 # Save output filename and check if path exists\r
132 #\r
133 OutputDir = os.path.dirname(args.OutputFile)\r
134 if not os.path.exists(OutputDir):\r
135 print 'ERROR: The output path does not exist: %s' % OutputDir\r
136 sys.exit(1)\r
137 args.OutputFileName = args.OutputFile\r
138\r
139 try:\r
140 if args.MonotonicCountStr.upper().startswith('0X'):\r
141 args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)\r
142 else:\r
143 args.MonotonicCountValue = (long)(args.MonotonicCountStr)\r
144 except:\r
145 args.MonotonicCountValue = (long)(0)\r
146\r
147 if args.Encode:\r
148 #\r
149 # Save signer private cert filename and close private cert file\r
150 #\r
151 try:\r
152 args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name\r
153 args.SignerPrivateCertFile.close()\r
154 except:\r
155 try:\r
156 #\r
157 # Get path to currently executing script or executable\r
158 #\r
159 if hasattr(sys, 'frozen'):\r
160 Pkcs7ToolPath = sys.executable\r
161 else:\r
162 Pkcs7ToolPath = sys.argv[0]\r
163 if Pkcs7ToolPath.startswith('"'):\r
164 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
165 if Pkcs7ToolPath.endswith('"'):\r
166 Pkcs7ToolPath = RsaToolPath[:-1]\r
167 args.SignerPrivateCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_SIGNER_PRIVATE_CERT_FILENAME)\r
168 args.SignerPrivateCertFile = open(args.SignerPrivateCertFileName, 'rb')\r
169 args.SignerPrivateCertFile.close()\r
170 except:\r
171 print 'ERROR: test signer private cert file %s missing' % (args.SignerPrivateCertFileName)\r
172 sys.exit(1)\r
173\r
174 #\r
175 # Save other public cert filename and close public cert file\r
176 #\r
177 try:\r
178 args.OtherPublicCertFileName = args.OtherPublicCertFile.name\r
179 args.OtherPublicCertFile.close()\r
180 except:\r
181 try:\r
182 #\r
183 # Get path to currently executing script or executable\r
184 #\r
185 if hasattr(sys, 'frozen'):\r
186 Pkcs7ToolPath = sys.executable\r
187 else:\r
188 Pkcs7ToolPath = sys.argv[0]\r
189 if Pkcs7ToolPath.startswith('"'):\r
190 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
191 if Pkcs7ToolPath.endswith('"'):\r
192 Pkcs7ToolPath = RsaToolPath[:-1]\r
193 args.OtherPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_OTHER_PUBLIC_CERT_FILENAME)\r
194 args.OtherPublicCertFile = open(args.OtherPublicCertFileName, 'rb')\r
195 args.OtherPublicCertFile.close()\r
196 except:\r
197 print 'ERROR: test other public cert file %s missing' % (args.OtherPublicCertFileName)\r
198 sys.exit(1)\r
199\r
245cda66
YZ
200 format = "%dsQ" % len(args.InputFileBuffer)\r
201 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
11eaa7af
YZ
202\r
203 #\r
204 # Sign the input file using the specified private key and capture signature from STDOUT\r
205 #\r
a5f26fef 206 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)\r
11eaa7af
YZ
207 Signature = Process.communicate(input=FullInputFileBuffer)[0]\r
208 if Process.returncode <> 0:\r
209 sys.exit(Process.returncode)\r
210\r
211 #\r
212 # Write output file that contains Signature, and Input data\r
213 #\r
214 args.OutputFile = open(args.OutputFileName, 'wb')\r
215 args.OutputFile.write(Signature)\r
216 args.OutputFile.write(args.InputFileBuffer)\r
217 args.OutputFile.close()\r
218\r
219 if args.Decode:\r
220 #\r
221 # Save trusted public cert filename and close public cert file\r
222 #\r
223 try:\r
224 args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name\r
225 args.TrustedPublicCertFile.close()\r
226 except:\r
227 try:\r
228 #\r
229 # Get path to currently executing script or executable\r
230 #\r
231 if hasattr(sys, 'frozen'):\r
232 Pkcs7ToolPath = sys.executable\r
233 else:\r
234 Pkcs7ToolPath = sys.argv[0]\r
235 if Pkcs7ToolPath.startswith('"'):\r
236 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
237 if Pkcs7ToolPath.endswith('"'):\r
238 Pkcs7ToolPath = RsaToolPath[:-1]\r
239 args.TrustedPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_TRUSTED_PUBLIC_CERT_FILENAME)\r
240 args.TrustedPublicCertFile = open(args.TrustedPublicCertFileName, 'rb')\r
241 args.TrustedPublicCertFile.close()\r
242 except:\r
243 print 'ERROR: test trusted public cert file %s missing' % (args.TrustedPublicCertFileName)\r
244 sys.exit(1)\r
245\r
246 if not args.SignatureSizeStr:\r
247 print "ERROR: please use the option --signature-size to specify the size of the signature data!"\r
248 sys.exit(1)\r
249 else:\r
250 if args.SignatureSizeStr.upper().startswith('0X'):\r
251 SignatureSize = (long)(args.SignatureSizeStr, 16)\r
252 else:\r
253 SignatureSize = (long)(args.SignatureSizeStr)\r
254 if SignatureSize < 0:\r
255 print "ERROR: The value of option --signature-size can't be set to negative value!"\r
256 sys.exit(1)\r
257 elif SignatureSize > len(args.InputFileBuffer):\r
258 print "ERROR: The value of option --signature-size is exceed the size of the input file !"\r
259 sys.exit(1)\r
260\r
261 args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]\r
262 args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]\r
263\r
245cda66
YZ
264 format = "%dsQ" % len(args.InputFileBuffer)\r
265 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
11eaa7af
YZ
266\r
267 #\r
268 # Save output file contents from input file\r
269 #\r
270 open(args.OutputFileName, 'wb').write(FullInputFileBuffer)\r
271\r
272 #\r
273 # Verify signature\r
274 #\r
a5f26fef 275 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)\r
11eaa7af
YZ
276 Process.communicate(input=args.SignatureBuffer)[0]\r
277 if Process.returncode <> 0:\r
278 print 'ERROR: Verification failed'\r
279 os.remove (args.OutputFileName)\r
280 sys.exit(Process.returncode)\r
281\r
282 open(args.OutputFileName, 'wb').write(args.InputFileBuffer)\r