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