summaryrefslogtreecommitdiff
path: root/Platform/ARM/Features/Fwu/GenTestCert.py
blob: 1daaac47659dd40d5234c1f912aed7ad8af02cdb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
## @file
# Generating Test Certificates for VExpressPkg's System Fip FmpDevicePkg
#
# Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#

'''
GenTestCert.py
'''

import os
import sys
import argparse
import subprocess
import glob
import shutil
import struct
import datetime
import errno

#
# Globals for help information
#
__prog__        = 'GenTestCert.py'
__copyright__   = 'Copyright (c) 2025, Arm Limited. All rights reserved.'
__description__ = 'Generatiing Test Certificates for System Fip FmpDevicePkg.'

#
# Globals
#
gWorkspace = ''
gBaseToolsPath = ''
gFeatauresFwuPath = ''
gTestCertDir = ''
gTestCertsCnfFile = ''
gRootCerPcdFile = ''
gArgs      = None

#
# Command Templete
#
GenerateKeyCommand = '''
openssl genrsa
-aes256
-passout pass:
-out {KEY_FILE} 2048
'''
GenerateRootCertCommand = '''
openssl req
-config {OPENSSL_CNF_FILE}
-extensions v3_ca
-new
-x509
-days 3650
-key {KEY_FILE}
-passin pass:
-subj "/C=UK/ST=test/O=test/CN=www.{DOMAIN_NAME}.com"
-out {OUT_CERT_FILE}
'''
GenerateCertCommand = '''
openssl req
-config {OPENSSL_CNF_FILE}
-new
-key {KEY_FILE}
-passin pass:
-subj "/C=UK/ST=test/O=test/CN=www.{DOMAIN_NAME}.com"
-out {OUT_CSR_FILE}
&&
openssl ca
-config {OPENSSL_CNF_FILE}
-extensions v3_ca
-batch
-in {OUT_CSR_FILE}
-days 3650
-cert {CA_CERT_FILE}
-keyfile {CA_KEY_FILE}
-passin pass:
-out {OUT_CERT_FILE}
'''
GeneratePubPemFromCertCommand = '''
openssl x509
-in {CERT_FILE}
-out {OUT_CER_FILE}
-outform DER
&&
openssl x509
-inform DER
-in {OUT_CER_FILE}
-out {OUT_PUB_PEM_FILE}
-outform PEM
'''

GeneratePkcsPemCommand = '''
openssl pkcs12
-export
-out
{OUT_PFX_FILE}
-inkey
{KEY_FILE}
-passin pass:
-passout pass:
-in
{CERT_FILE}
&&
openssl pkcs12
-in
{OUT_PFX_FILE}
-passin pass:
-nodes
-out
{OUT_PEM_FILE}
'''

BinToPcdCommand = '''
python {BASE_TOOLS_PATH}/Scripts/BinToPcd.py
-i {ROOT_CER_FILE}
-p gFmpDevicePkgTokenSpaceGuid.PcdFmpDevicePkcs7CertBufferXdr
-x
-o {OUT_PCD_FILE}
'''
def LogAlways(Message):
    sys.stdout.write(__prog__ + ': ' + Message + '\n')
    sys.stdout.flush()

def Log(Message):
    global gArgs
    if not gArgs.Verbose:
        return
    sys.stdout.write(__prog__ + ': ' + Message + '\n')
    sys.stdout.flush()

def Error(Message, ExitValue=1):
    sys.stderr.write(__prog__ + ': ERROR: ' + Message + '\n')
    sys.exit(ExitValue)

def RelativePath(target):
    global gWorkspace
    Log('RelativePath' + target)
    return os.path.relpath(target, gWorkspace)

def NormalizePath(target):
    if isinstance(target, tuple):
        return os.path.normpath(os.path.join(*target))
    else:
        return os.path.normpath(target)

def RunCommand(command, workdir):
    Command = ' '.join(command.splitlines()).strip()

    LogAlways(Command)

    Process = subprocess.Popen(
                Command,
                cwd=workdir,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True
                )

    ProcessOutput = Process.communicate()

    return Process.returncode

def CreateDirectory(target):
    target = NormalizePath(target)
    if not os.path.exists(target):
        Log('mkdir %s' % (RelativePath(target)))
        os.makedirs(target)

def CreateTestCertDirecotry():
    if not os.path.exists(gTestCertDir):
        CreateDirectory(gTestCertDir)

    TestCADir = NormalizePath((gTestCertDir, "demoCA"))
    if not os.path.exists(TestCADir):
        CreateDirectory(TestCADir)

    TestNewCertsDir = NormalizePath((TestCADir, "newcerts"))
    if not os.path.exists(TestNewCertsDir):
        CreateDirectory(TestNewCertsDir)

    SerialFile = NormalizePath((TestCADir, "serial"))
    if not os.path.exists(SerialFile):
        with open(SerialFile, 'w') as file:
            file.write("01")

    IndexFile = NormalizePath((TestCADir, "index.txt"))
    if not os.path.exists(IndexFile):
        open(IndexFile, 'w').close()

def GenerateRootKey():
    RootKeyFile = NormalizePath((gTestCertDir, "TestRoot.key"))

    if not os.path.exists(RootKeyFile):
        Command = GenerateKeyCommand.format(KEY_FILE = RootKeyFile)
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestRoot.key...", ret)

def GenerateRootCert():
    RootKeyFile = NormalizePath((gTestCertDir, "TestRoot.key"))
    RootCertFile = NormalizePath((gTestCertDir, "TestRoot.crt"))
    RootCerFile = NormalizePath((gTestCertDir, "TestRoot.cer"))
    RootPubPemFile = NormalizePath((gTestCertDir, "TestRoot.pub.pem"))
    DomainName = "testroot"

    if not os.path.exists(RootCerFile):
        Command = GenerateRootCertCommand.format(
                    OPENSSL_CNF_FILE = gTestCertsCnfFile,
                    KEY_FILE = RootKeyFile,
                    DOMAIN_NAME=DomainName,
                    OUT_CERT_FILE = RootCertFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestRoot.crt...", ret)

    if not os.path.exists(RootCerFile):
        Command = GeneratePubPemFromCertCommand.format(
                    CERT_FILE = RootCertFile,
                    OUT_CER_FILE = RootCerFile,
                    OUT_PUB_PEM_FILE = RootPubPemFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestRoot.pub.pem...", ret)

def GenerateCaKey():
    CaKeyFile = NormalizePath((gTestCertDir, "TestSub.key"))

    if not os.path.exists(CaKeyFile):
        Command = GenerateKeyCommand.format(KEY_FILE = CaKeyFile)
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestSub.key...", ret)

def GenerateCaCert():
    RootKeyFile = NormalizePath((gTestCertDir, "TestRoot.key"))
    RootCertFile = NormalizePath((gTestCertDir, "TestRoot.crt"))
    CaKeyFile = NormalizePath((gTestCertDir, "TestSub.key"))
    CaCsrFile = NormalizePath((gTestCertDir, "TestSub.csr"))
    CaCertFile = NormalizePath((gTestCertDir, "TestSub.crt"))
    CaCerFile = NormalizePath((gTestCertDir, "TestSub.cer"))
    CaPubPemFile = NormalizePath((gTestCertDir, "TestSub.pub.pem"))
    DomainName = "testsub"

    if not os.path.exists(CaCertFile):
        Command = GenerateCertCommand.format(
                    OPENSSL_CNF_FILE = gTestCertsCnfFile,
                    KEY_FILE = CaKeyFile,
                    DOMAIN_NAME=DomainName,
                    CA_KEY_FILE = RootKeyFile,
                    CA_CERT_FILE = RootCertFile,
                    OUT_CSR_FILE = CaCsrFile,
                    OUT_CERT_FILE = CaCertFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestSub.crt...", ret)

    if not os.path.exists(CaCerFile):
        Command = GeneratePubPemFromCertCommand.format(
                    CERT_FILE = CaCertFile,
                    OUT_CER_FILE = CaCerFile,
                    OUT_PUB_PEM_FILE = CaPubPemFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestSub.pub.pem...", ret)

def GenerateUserKey():
    UserKeyFile = NormalizePath((gTestCertDir, "TestUser.key"))

    if not os.path.exists(UserKeyFile):
        Command = GenerateKeyCommand.format(KEY_FILE = UserKeyFile)
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestUser.key...", ret)

def GenerateUserCert():
    CaKeyFile = NormalizePath((gTestCertDir, "TestSub.key"))
    CaCertFile = NormalizePath((gTestCertDir, "TestSub.crt"))
    UserKeyFile = NormalizePath((gTestCertDir, "TestUser.key"))
    UserCsrFile = NormalizePath((gTestCertDir, "TestUser.csr"))
    UserCertFile = NormalizePath((gTestCertDir, "TestUser.crt"))
    UserCerFile = NormalizePath((gTestCertDir, "TestUser.cer"))
    UserPubPemFile = NormalizePath((gTestCertDir, "TestUser.pub.pem"))
    DomainName = "testuser"

    if not os.path.exists(UserCertFile):
        Command = GenerateCertCommand.format(
                    OPENSSL_CNF_FILE = gTestCertsCnfFile,
                    KEY_FILE = UserKeyFile,
                    DOMAIN_NAME=DomainName,
                    CA_KEY_FILE = CaKeyFile,
                    CA_CERT_FILE = CaCertFile,
                    OUT_CSR_FILE = UserCsrFile,
                    OUT_CERT_FILE = UserCertFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestUser.crt...", ret)

    if not os.path.exists(UserCerFile):
        Command = GeneratePubPemFromCertCommand.format(
                    CERT_FILE = UserCertFile,
                    OUT_CER_FILE = UserCerFile,
                    OUT_PUB_PEM_FILE = UserPubPemFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestUser.pub.pem...", ret)

def GenerateUserPkcsPem():
    UserKeyFile = NormalizePath((gTestCertDir, "TestUser.key"))
    UserCertFile = NormalizePath((gTestCertDir, "TestUser.crt"))
    UserPfxFile = NormalizePath((gTestCertDir, "TestUser.pfx"))
    UserPemFile = NormalizePath((gTestCertDir, "TestUser.pem"))

    if not os.path.exists(UserPemFile):
        Command = GeneratePkcsPemCommand.format(
                    OUT_PFX_FILE = UserPfxFile,
                    KEY_FILE = UserKeyFile,
                    CERT_FILE = UserCertFile,
                    OUT_PEM_FILE = UserPemFile
                    )
        ret = RunCommand(Command, gTestCertDir)
        if ret != 0:
            Error ("Failed to generate TestUser.pem...", ret)

def GenerateRootCerPcdFile():
    RootCerFile = NormalizePath((gTestCertDir, "TestRoot.cer"))
    Command = BinToPcdCommand.format(
                BASE_TOOLS_PATH = gBaseToolsPath,
                ROOT_CER_FILE = RootCerFile,
                OUT_PCD_FILE = gRootCerPcdFile
                )
    ret = RunCommand(Command, None)
    if ret != 0:
        Error ("Failed to generate Root.cer.gFmpDevicePkgTokenSpaceGuid.PcdFmpDevicePkcs7CertBufferXdr.inc", ret)

    LogAlways("Root.cer.gFmpDevicePkgTokenSpaceGuid.PcdFmpDevicePkcs7CertBufferXdr.inc is gererated.")

if __name__ == '__main__':
    def convert_arg_line_to_args(arg_line):
        for arg in arg_line.split():
            if not arg.split():
                continue
            yield arg

    #
    # Create command line argument parser object
    #
    parser = argparse.ArgumentParser(
                        prog = __prog__,
                        description = __description__ + __copyright__,
                        conflict_handler = 'resolve'
                        )
    parser.convert_arg_line_to_args = convert_arg_line_to_args

    parser = argparse.ArgumentParser(
                        prog = __prog__,
                        description = __description__ + __copyright__,
                        conflict_handler = 'resolve'
                        )

    parser.add_argument(
             '-v', '--verbose', dest = 'Verbose', action = 'store_true',
             help = '''Turn on verbose output with informational messages printed'''
             )
    #
    # Parse command line arguments
    #
    gArgs, extra = parser.parse_known_args()

    #
    # Get WORKSPACE environment variable
    #
    try:
        gWorkspace = os.environ['WORKSPACE']
    except:
        Error ('WORKSPACE environment variable not set')

    #
    # Get PACKAGES_PATH and generate prioritized list of paths
    #
    PathList = [gWorkspace]
    try:
        PathList += os.environ['PACKAGES_PATH'].split(os.pathsep)
    except:
        pass

    try:
        gBaseToolsPath = os.environ['EDK_TOOLS_PATH']
    except:
        Error ('EDK_TOOLS_PATH enviroment variable not set')

    #
    # Determine full path of VExpressPkg
    #
    gFeaturesFwuPath = ''
    for Path in PathList:
        if gFeaturesFwuPath == '':
            if os.path.exists (os.path.join(Path, 'Platform/ARM/Features/Fwu')):
                gFeaturesFwuPath = os.path.join(Path, 'Platform/ARM/Features/Fwu')

    if gFeaturesFwuPath == '':
        Error ('Can not find VExpressPkg in WORKSPACE or PACKAGES_PATH')

    gTestCertDir = NormalizePath((gFeaturesFwuPath, "TestCert"))
    gTestCertsCnfFile = NormalizePath((gFeaturesFwuPath, "TestCerts.cnf"))
    gRootCerPcdFile = NormalizePath((
                        gFeaturesFwuPath,
                        "Root.cer.gFmpDevicePkgTokenSpaceGuid.PcdFmpDevicePkcs7CertBufferXdr.inc"
                        ))

    if not os.path.exists(gRootCerPcdFile) or os.stat(gRootCerPcdFile).st_size == 0:
        CreateTestCertDirecotry()
        GenerateRootKey()
        GenerateRootCert()
        GenerateCaKey()
        GenerateCaCert()
        GenerateUserKey()
        GenerateUserCert()
        GenerateUserPkcsPem()
        GenerateRootCerPcdFile()