]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Pkcs7Sign/Pkcs7Sign.py
BaseTools: Remove the "from __future__ import" items
[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
ccaa7754 90 parser.add_argument("--debug", dest='Debug', type=int, metavar='[0-9]', choices=range(0, 10), default=0, help="set debug level")\r
11eaa7af
YZ
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
b1051537
YZ
105 if ' ' in OpenSslCommand:\r
106 OpenSslCommand = '"' + OpenSslCommand + '"'\r
11eaa7af
YZ
107 except:\r
108 pass\r
109\r
110 #\r
111 # Verify that Open SSL command is available\r
112 #\r
113 try:\r
8a0933f4 114 Process = subprocess.Popen('%s version' % (OpenSslCommand), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\r
11eaa7af 115 except:\r
72443dd2 116 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')\r
11eaa7af
YZ
117 sys.exit(1)\r
118\r
119 Version = Process.communicate()\r
87d2afd0 120 if Process.returncode != 0:\r
72443dd2 121 print('ERROR: Open SSL command not available. Please verify PATH or set OPENSSL_PATH')\r
11eaa7af 122 sys.exit(Process.returncode)\r
72443dd2 123 print(Version[0])\r
11eaa7af
YZ
124\r
125 #\r
126 # Read input file into a buffer and save input filename\r
127 #\r
128 args.InputFileName = args.InputFile.name\r
129 args.InputFileBuffer = args.InputFile.read()\r
130 args.InputFile.close()\r
131\r
132 #\r
133 # Save output filename and check if path exists\r
134 #\r
135 OutputDir = os.path.dirname(args.OutputFile)\r
136 if not os.path.exists(OutputDir):\r
72443dd2 137 print('ERROR: The output path does not exist: %s' % OutputDir)\r
11eaa7af
YZ
138 sys.exit(1)\r
139 args.OutputFileName = args.OutputFile\r
140\r
141 try:\r
142 if args.MonotonicCountStr.upper().startswith('0X'):\r
143 args.MonotonicCountValue = (long)(args.MonotonicCountStr, 16)\r
144 else:\r
145 args.MonotonicCountValue = (long)(args.MonotonicCountStr)\r
146 except:\r
147 args.MonotonicCountValue = (long)(0)\r
148\r
149 if args.Encode:\r
150 #\r
151 # Save signer private cert filename and close private cert file\r
152 #\r
153 try:\r
154 args.SignerPrivateCertFileName = args.SignerPrivateCertFile.name\r
155 args.SignerPrivateCertFile.close()\r
156 except:\r
157 try:\r
158 #\r
159 # Get path to currently executing script or executable\r
160 #\r
161 if hasattr(sys, 'frozen'):\r
162 Pkcs7ToolPath = sys.executable\r
163 else:\r
164 Pkcs7ToolPath = sys.argv[0]\r
165 if Pkcs7ToolPath.startswith('"'):\r
166 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
167 if Pkcs7ToolPath.endswith('"'):\r
168 Pkcs7ToolPath = RsaToolPath[:-1]\r
169 args.SignerPrivateCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_SIGNER_PRIVATE_CERT_FILENAME)\r
170 args.SignerPrivateCertFile = open(args.SignerPrivateCertFileName, 'rb')\r
171 args.SignerPrivateCertFile.close()\r
172 except:\r
72443dd2 173 print('ERROR: test signer private cert file %s missing' % (args.SignerPrivateCertFileName))\r
11eaa7af
YZ
174 sys.exit(1)\r
175\r
176 #\r
177 # Save other public cert filename and close public cert file\r
178 #\r
179 try:\r
180 args.OtherPublicCertFileName = args.OtherPublicCertFile.name\r
181 args.OtherPublicCertFile.close()\r
182 except:\r
183 try:\r
184 #\r
185 # Get path to currently executing script or executable\r
186 #\r
187 if hasattr(sys, 'frozen'):\r
188 Pkcs7ToolPath = sys.executable\r
189 else:\r
190 Pkcs7ToolPath = sys.argv[0]\r
191 if Pkcs7ToolPath.startswith('"'):\r
192 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
193 if Pkcs7ToolPath.endswith('"'):\r
194 Pkcs7ToolPath = RsaToolPath[:-1]\r
195 args.OtherPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_OTHER_PUBLIC_CERT_FILENAME)\r
196 args.OtherPublicCertFile = open(args.OtherPublicCertFileName, 'rb')\r
197 args.OtherPublicCertFile.close()\r
198 except:\r
72443dd2 199 print('ERROR: test other public cert file %s missing' % (args.OtherPublicCertFileName))\r
11eaa7af
YZ
200 sys.exit(1)\r
201\r
245cda66
YZ
202 format = "%dsQ" % len(args.InputFileBuffer)\r
203 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
11eaa7af
YZ
204\r
205 #\r
206 # Sign the input file using the specified private key and capture signature from STDOUT\r
207 #\r
a5f26fef 208 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 209 Signature = Process.communicate(input=FullInputFileBuffer)[0]\r
87d2afd0 210 if Process.returncode != 0:\r
11eaa7af
YZ
211 sys.exit(Process.returncode)\r
212\r
213 #\r
214 # Write output file that contains Signature, and Input data\r
215 #\r
216 args.OutputFile = open(args.OutputFileName, 'wb')\r
217 args.OutputFile.write(Signature)\r
218 args.OutputFile.write(args.InputFileBuffer)\r
219 args.OutputFile.close()\r
220\r
221 if args.Decode:\r
222 #\r
223 # Save trusted public cert filename and close public cert file\r
224 #\r
225 try:\r
226 args.TrustedPublicCertFileName = args.TrustedPublicCertFile.name\r
227 args.TrustedPublicCertFile.close()\r
228 except:\r
229 try:\r
230 #\r
231 # Get path to currently executing script or executable\r
232 #\r
233 if hasattr(sys, 'frozen'):\r
234 Pkcs7ToolPath = sys.executable\r
235 else:\r
236 Pkcs7ToolPath = sys.argv[0]\r
237 if Pkcs7ToolPath.startswith('"'):\r
238 Pkcs7ToolPath = Pkcs7ToolPath[1:]\r
239 if Pkcs7ToolPath.endswith('"'):\r
240 Pkcs7ToolPath = RsaToolPath[:-1]\r
241 args.TrustedPublicCertFileName = os.path.join(os.path.dirname(os.path.realpath(Pkcs7ToolPath)), TEST_TRUSTED_PUBLIC_CERT_FILENAME)\r
242 args.TrustedPublicCertFile = open(args.TrustedPublicCertFileName, 'rb')\r
243 args.TrustedPublicCertFile.close()\r
244 except:\r
72443dd2 245 print('ERROR: test trusted public cert file %s missing' % (args.TrustedPublicCertFileName))\r
11eaa7af
YZ
246 sys.exit(1)\r
247\r
248 if not args.SignatureSizeStr:\r
72443dd2 249 print("ERROR: please use the option --signature-size to specify the size of the signature data!")\r
11eaa7af
YZ
250 sys.exit(1)\r
251 else:\r
252 if args.SignatureSizeStr.upper().startswith('0X'):\r
253 SignatureSize = (long)(args.SignatureSizeStr, 16)\r
254 else:\r
255 SignatureSize = (long)(args.SignatureSizeStr)\r
256 if SignatureSize < 0:\r
72443dd2 257 print("ERROR: The value of option --signature-size can't be set to negative value!")\r
11eaa7af
YZ
258 sys.exit(1)\r
259 elif SignatureSize > len(args.InputFileBuffer):\r
72443dd2 260 print("ERROR: The value of option --signature-size is exceed the size of the input file !")\r
11eaa7af
YZ
261 sys.exit(1)\r
262\r
263 args.SignatureBuffer = args.InputFileBuffer[0:SignatureSize]\r
264 args.InputFileBuffer = args.InputFileBuffer[SignatureSize:]\r
265\r
245cda66
YZ
266 format = "%dsQ" % len(args.InputFileBuffer)\r
267 FullInputFileBuffer = struct.pack(format, args.InputFileBuffer, args.MonotonicCountValue)\r
11eaa7af
YZ
268\r
269 #\r
270 # Save output file contents from input file\r
271 #\r
272 open(args.OutputFileName, 'wb').write(FullInputFileBuffer)\r
273\r
274 #\r
275 # Verify signature\r
276 #\r
a5f26fef 277 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 278 Process.communicate(input=args.SignatureBuffer)[0]\r
87d2afd0 279 if Process.returncode != 0:\r
72443dd2 280 print('ERROR: Verification failed')\r
11eaa7af
YZ
281 os.remove (args.OutputFileName)\r
282 sys.exit(Process.returncode)\r
283\r
284 open(args.OutputFileName, 'wb').write(args.InputFileBuffer)\r