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