Debian Codegraph @

src/TestDB/generate-test-certificates

raw
1 #!/usr/bin/env python3
2 # ==========================================================================
3 # ____ _ _____ _
4 # / ___| _ _ ___| |_ ___ _ __ ___ |_ _|__ ___ | |___
5 # \___ \| | | / __| __/ _ \ '_ ` _ \ _____| |/ _ \ / _ \| / __|
6 # ___) | |_| \__ \ || __/ | | | | |_____| | (_) | (_) | \__ \
7 # |____/ \__, |___/\__\___|_| |_| |_| |_|\___/ \___/|_|___/
8 # |___/
9 # --- System-Tools ---
10 # https://www.nntb.no/~dreibh/system-tools/
11 # ==========================================================================
12 #
13 # X.509 CA and Certificate Test Setup Script
14 # Copyright (C) 2015-2026 by Thomas Dreibholz
15 #
16 # This program is free software: you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation, either version 3 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 #
26 # You should have received a copy of the GNU General Public License
27 # along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #
29 # Contact: [email protected]
30
31 import getopt
32 import sys
33
34 from typing import Any
35 from CertificateHelper import *
36
37
38 # ###### Print usage and exit ###############################################
39 def usage(exitCode : int = 0) -> None:
40 sys.stderr.write('Usage: ' + sys.argv[0] + ' ssl_directory [-s|--server|-c|--client|-u|--user] [-x|--revoke-if-existing|-i|--ignore-if-existing] [-r|--revoke] [-S|--san|--subjectAltName subjectAltName|LOCAL|LOOKUP] [-K|--keylen-ca length] [-k|--keylen-cert length] name ...\n')
41 sys.exit(exitCode)
42
43
44 # ###### Main program #######################################################
45
46 caKeyLength : int = DefaultCAKeyLength
47 certKeyLength : int = DefaultCertKeyLength
48
49 # ====== Handle command-line parameters =====================================
50 certificatesToCreate : list[dict[str,Any]] = []
51 subjectAltName : str | None = None
52 certType : CertificateType = CertificateType.Server
53 revokeIfExisting : bool = True
54 revoke : bool = False
55
56 # ====== Handle arguments ===================================================
57 try:
58 options, args = getopt.gnu_getopt(
59 sys.argv[1:],
60 'scuxirS:K:k:',
61 [ 'server',
62 'client',
63 'user',
64 'revoke-if-existing',
65 'ignore-if-existing',
66 'revoke',
67 'san=',
68 'keylen-ca=',
69 'keylen-cert='
70 ])
71 for option, optarg in options:
72 if option in ( '-s', '--server' ):
73 certType = CertificateType.Server
74 elif option in ( '-c', '--client' ):
75 certType = CertificateType.Client
76 elif option in ( '-u', '--user' ):
77 certType = CertificateType.User
78 elif option in ( '-r', '--revoke' ):
79 revoke = True
80 elif option in ( '-x', '--revoke-if-existing' ):
81 revokeIfExisting = True
82 elif option in ( '-i', '--ignore-if-existing' ):
83 revokeIfExisting = False
84 elif option in ( '-S', '--san', '--subjectAltName' ):
85 subjectAltName = optarg
86 elif option in ( '-K', '--keylen-ca' ):
87 caKeyLength = int(optarg)
88 elif option in ( '-k', '--keylen-cert' ):
89 certKeyLength = int(optarg)
90 except getopt.GetoptError as error:
91 sys.stderr.write('ERROR: ' + str(error) + '\n')
92 usage(1)
93 if len(args) < 2:
94 usage(1)
95
96 mainDirectory : str = args[0]
97 for i in range(1, len(args)):
98 ( name, san ) = prepareSubjectAltName(certType, args[i], subjectAltName)
99 certificatesToCreate.append({ 'name' : name,
100 'type' : certType,
101 'subjectAltName' : san,
102 'revokeIfExisting' : revokeIfExisting })
103 # print(certificatesToCreate)
104
105
106 # ====== Create CA hierarchy, if not existing ===============================
107
108 # ===========================================================================
109 # Hierarchy to be created:
110 # TestLevel1
111 # - TestLevel2
112 # - TestIntermediate1
113 # - TestIntermediate2
114 # - TestLeaf
115 # - Servers ...
116 # - Clients ...
117 # - Users ...
118 # ===========================================================================
119
120
121 # ====== Create Test CAs ====================================================
122 globalCRLFileName = "TestGlobal.crl"
123
124 # Create Test Root Level-1 CA certificate (self-signed):
125 TestLevel1 = CA(mainDirectory, 'TestLevel1',
126 parentCA = None,
127 subject = '/C=NO/ST=Oslo/L=Oslo/O=Simula Research Laboratory/streetAddress=Kristian Augusts gate 23/postalCode=0164/CN=Test Level-1 CA Certificate',
128 certType = CertificateType.RootCA,
129 keyLength = caKeyLength, globalCRLFileName = globalCRLFileName)
130
131 # Create Test Root Level-2 CA certificate (signed by Test Root Level-1):
132 TestLevel2 = CA(mainDirectory, 'TestLevel2',
133 parentCA = TestLevel1,
134 subject = '/C=NO/ST=Oslo/L=Oslo/O=Simula Research Laboratory/streetAddress=Kristian Augusts gate 23/postalCode=0164/CN=Test Level-2 CA Certificate',
135 certType = CertificateType.IntermediateCA,
136 keyLength = caKeyLength, globalCRLFileName = globalCRLFileName)
137
138 # Create Test Intermediate CA certificate (signed by Test Root Level-2):
139 TestIntermediate1 = CA(mainDirectory, 'TestIntermediate1',
140 parentCA = TestLevel2,
141 subject = '/C=NO/ST=Oslo/L=Oslo/O=Simula Metropolitan Centre for Digital Engineering (SimulaMet)/streetAddress=Stensberggata 27/postalCode=0170/CN=*',
142 certType = CertificateType.IntermediateCA,
143 keyLength = caKeyLength, globalCRLFileName = globalCRLFileName)
144
145 # Create Test Intermediate CA certificate (signed by Test Root Level-2):
146 TestIntermediate2 = CA(mainDirectory, 'TestIntermediate2',
147 parentCA = TestIntermediate1,
148 subject = '/C=NO/ST=Oslo/L=Oslo/O=Simula Metropolitan Centre for Digital Engineering (SimulaMet)/OU=Centre for Resilient Networks and Applications (CRNA)/streetAddress=Stensberggata 27/postalCode=0170/CN=*',
149 certType = CertificateType.IntermediateCA,
150 keyLength = caKeyLength, globalCRLFileName = globalCRLFileName)
151
152 # Create Test Leaf CA certificate (signed by Test Intermediate):
153 TestLeaf = CA(mainDirectory, 'TestLeaf',
154 parentCA = TestIntermediate2,
155 subject = '/C=NO/ST=Oslo/L=Oslo/O=Simula Metropolitan Centre for Digital Engineering (SimulaMet)/OU=SimulaMet Interoperability Lab (SMIL)/streetAddress=Stensberggata 27/postalCode=0170/CN=*/',
156 certType = CertificateType.LeafCA,
157 keyLength = caKeyLength, globalCRLFileName = globalCRLFileName)
158
159
160 # ====== Create Test Servers ================================================
161 defaultSubjectWithoutCN = '/C=NO/ST=Oslo/L=Oslo/O=Simula Metropolitan Centre for Digital Engineering (SimulaMet)/OU=SimulaMet Interoperability Lab (SMIL)/streetAddress=Stensberggata 27/postalCode=0170'
162
163 certificates = { }
164 for certificateToCreate in certificatesToCreate:
165 print(certificateToCreate)
166
167 name = certificateToCreate['name']
168 if certificateToCreate['type'] != CertificateType.User:
169 subjectWithoutCN = defaultSubjectWithoutCN
170 else:
171 subjectWithoutCN = defaultSubjectWithoutCN + prepareUserSubject(name)
172 certificates[name] = Certificate(mainDirectory, name, TestLeaf,
173 subjectWithoutCN, certificateToCreate['subjectAltName'],
174 certificateToCreate['type'],
175 keyLength = certKeyLength,
176 revokeIfExisting = revokeIfExisting)
177
178 if revoke:
179 certificates[name].revoke()
180
181
182 # ====== Finally, force regeneration of the CRL to ensure it is up-to-date ==
183 TestLevel1.generateCRL()