Debian Codegraph @

dirsrvtests/tests/suites/tls/mldsa_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2026 Red Hat, Inc.
3 # All rights reserved.
4 #
5 # License: GPL (version 3 or any later version).
6 # See LICENSE for details.
7 # --- END COPYRIGHT BLOCK ---
8 #
9 import logging
10 import pytest
11 import os
12 import sys
13 import socket
14 import subprocess
15 from lib389.utils import ds_is_older, rpm_is_older
16 from lib389._constants import DN_DM, PW_DM, DEFAULT_SUFFIX
17 from lib389.config import Encryption, CertmapLegacy
18 from lib389.idm.user import UserAccount
19 from test389.topologies import topology_st as topo
20 from tempfile import TemporaryDirectory
21
22 pytestmark = pytest.mark.tier1
23
24 DEBUGGING = os.getenv("DEBUGGING", default=False)
25 if DEBUGGING:
26 logging.getLogger(__name__).setLevel(logging.DEBUG)
27 else:
28 logging.getLogger(__name__).setLevel(logging.INFO)
29 log = logging.getLogger(__name__)
30
31
32 script_content="""
33 #!/bin/bash
34 set -e # Exit if a command fails
35 set -x # Log the commands
36
37 cd {dir}
38 inst={instname}
39 url={url}
40 rootdn="{rootdn}"
41 rootpw="{rootpw}"
42
43 ################################
44 ###### GENERATE CA CERT ########
45 ################################
46
47 echo "
48 [ req ]
49 distinguished_name = req_distinguished_name
50 policy = policy_match
51 x509_extensions = v3_ca
52
53 # For the CA policy
54 [ policy_match ]
55 countryName = optional
56 stateOrProvinceName = optional
57 organizationName = optional
58 organizationalUnitName = optional
59 commonName = supplied
60 emailAddress = optional
61
62 [ req_distinguished_name ]
63 countryName = Country Name (2 letter code)
64 countryName_default = FR
65 countryName_min = 2
66 countryName_max = 2
67
68 stateOrProvinceName = State or Province Name (full name)
69 stateOrProvinceName_default = test
70
71 localityName = Locality Name (eg, city)
72
73 0.organizationName = Organization Name (eg, company)
74 0.organizationName_default = test-ML-DSA-CA
75
76 organizationalUnitName = Organizational Unit Name (eg, section)
77 #organizationalUnitName_default =
78
79 commonName = Common Name (e.g. server FQDN or YOUR name)
80 commonName_max = 64
81
82
83 [ v3_ca ]
84 subjectKeyIdentifier = hash
85 authorityKeyIdentifier = keyid:always,issuer
86 basicConstraints = critical,CA:true
87 #nsComment = "OpenSSL Generated Certificate"
88 keyUsage=critical, keyCertSign
89 " >ca.conf
90
91
92 openssl genpkey -algorithm ML-DSA-87 -out ca.key
93 openssl req -x509 -new -sha256 -key ca.key -nodes -days 3650 -config ca.conf -subj "/CN=`hostname`/O=test-ML-DSA-CA/C=FR" -out ca.pem -keyout ca.key
94 openssl x509 -outform der -in ca.pem -out ca.crt
95
96 openssl x509 -text -in ca.pem
97
98 ####################################
99 ###### GENERATE SERVER CERT ########
100 ####################################
101
102 echo "
103 [ req ]
104 distinguished_name = req_distinguished_name
105 policy = policy_match
106 x509_extensions = v3_cert
107
108 # For the cert policy
109 [ policy_match ]
110 countryName = optional
111 stateOrProvinceName = optional
112 organizationName = optional
113 organizationalUnitName = optional
114 commonName = supplied
115 emailAddress = optional
116
117 [ req_distinguished_name ]
118 countryName = Country Name (2 letter code)
119 countryName_default = FR
120 countryName_min = 2
121 countryName_max = 2
122
123 stateOrProvinceName = State or Province Name (full name)
124
125 localityName = Locality Name (eg, city)
126
127 0.organizationName = Organization Name (eg, company)
128 0.organizationName_default = test-ML-DSA
129
130 organizationalUnitName = Organizational Unit Name (eg, section)
131 #organizationalUnitName_default =
132
133 commonName = Common Name (e.g. server FQDN or YOUR name)
134 commonName_max = 64
135
136
137 [ v3_cert ]
138 basicConstraints = critical,CA:false
139 subjectAltName=DNS:`hostname`
140 keyUsage=digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
141 #nsComment = "OpenSSL Generated Certificate"
142 extendedKeyUsage=clientAuth, serverAuth
143 nsCertType=client, server
144 " >cert.conf
145
146 openssl genpkey -algorithm ML-DSA-65 -out cert.key
147 openssl req -new -sha256 -key cert.key -nodes -config cert.conf -subj "/CN=`hostname`/O=test-ML-DSA/C=FR" -out cert.csr
148 openssl x509 -req -sha256 -days 3650 -extensions v3_cert -extfile cert.conf -in cert.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out cert.pem
149 openssl pkcs12 -export -inkey cert.key -in cert.pem -name mldsacert -out cert.p12 -passout pass:secret12
150
151 openssl x509 -text -in cert.pem
152
153
154
155 ####################################
156 ###### GENERATE CLIENT CERT ########
157 ####################################
158
159 echo "
160 [ req ]
161 distinguished_name = req_distinguished_name
162 policy = policy_match
163 x509_extensions = v3_cert
164
165 # For the cert policy
166 [ policy_match ]
167 countryName = optional
168 stateOrProvinceName = optional
169 organizationName = optional
170 organizationalUnitName = optional
171 commonName = supplied
172 emailAddress = optional
173
174 [ req_distinguished_name ]
175 countryName = Country Name (2 letter code)
176 countryName_default = FR
177 countryName_min = 2
178 countryName_max = 2
179
180 stateOrProvinceName = State or Province Name (full name)
181
182 localityName = Locality Name (eg, city)
183
184 0.organizationName = Organization Name (eg, company)
185 0.organizationName_default = test-ML-DSA
186
187 organizationalUnitName = Organizational Unit Name (eg, section)
188 #organizationalUnitName_default =
189
190 commonName = Common Name (e.g. server FQDN or YOUR name)
191 commonName_max = 64
192
193
194 [ v3_cert ]
195 basicConstraints = critical,CA:false
196 subjectAltName=DNS:`hostname`
197 keyUsage=digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
198 #nsComment = "OpenSSL Generated Certificate"
199 extendedKeyUsage=clientAuth
200 nsCertType=client, server
201 " >client.conf
202
203 openssl genpkey -algorithm ML-DSA-65 -out client.key
204 openssl req -new -sha256 -key client.key -nodes -config client.conf -subj "/CN=`hostname`/O=client-test-ML-DSA/C=FR" -out client.csr
205 openssl x509 -req -sha256 -days 3650 -extensions v3_cert -extfile client.conf -in client.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out client.pem
206 openssl pkcs12 -export -inkey client.key -in client.pem -name mldsacert2 -out client.p12 -passout pass:secret12
207
208 openssl x509 -text -in client.pem
209
210
211 #############################
212 ###### INSTALL CERTS ########
213 #############################
214
215 certdbdir=$PREFIX/etc/dirsrv/slapd-$inst
216 rm -f $certdbdir/cert9.db $certdbdir/key4.db
217 certutil -N -d $certdbdir -f $certdbdir/pwdfile.txt
218
219 certutil -A -n Self-Signed-CA -t CT,, -f $certdbdir/pwdfile.txt -d $certdbdir -a -i ca.pem
220 certutil -A -n Client-Cert -t u,, -f $certdbdir/pwdfile.txt -d $certdbdir -a -i client.pem
221
222 dsctl $inst tls import-server-key-cert cert.pem cert.key
223
224 dsctl $inst restart
225
226
227 #########################
228 ###### TEST CERT ########
229 #########################
230 export LDAPTLS_CACERT=$PWD/ca.pem
231 export LDAPTLS_CERT=$PWD/client.pem
232 export LDAPTLS_KEY=$PWD/client.key
233
234 ldapsearch -x -H $url -D "$rootdn" -w "$rootpw" -b "" -s base
235 ldapsearch -Y external -H $url -b "" -s base
236 """
237
238 @pytest.mark.skipif(rpm_is_older("openssl", "3.5"), reason="OpenSSL too old to support PQC")
239 @pytest.mark.skipif(rpm_is_older("nss", "3.119.1"), reason="NSS too old to support PQC")
240 def test_mldsa(topo):
241 """Test using ML-DSA Certificate - (PQC)
242
243 :id: 87fb19ef-672d-4fa7-934d-dfb4397f2312
244 :setup: Standalone Instance
245 :steps:
246 1. Configure the certmap
247 2. Create user mapped with theclient certificate
248 3. Generate the test script
249 4. Run the test script
250 5. Check that ldapsearch returned the namingcontext
251 :expectedresults:
252 1. No error
253 2. No error
254 3. No error
255 4. No error and exit code should be 0
256 5. namingcontext should be in the script output
257 """
258
259 inst = topo.standalone
260 inst.config.set('nsslapd-errorlog-level', str(16384 + 8))
261 inst.enable_tls()
262
263 cm = CertmapLegacy(inst)
264 certmaps = cm.list()
265 certmaps['default'].update({'DNComps': None, 'CmapLdapAttr': 'description'})
266 cm.set(certmaps)
267
268 cert_dn = f'C=FR,O=client-test-ML-DSA,CN={socket.gethostname()}'
269 dn = f'uid=test_user,ou=people,{DEFAULT_SUFFIX}'
270 UserAccount(inst, dn=dn).create( properties= {
271 'uid': 'test_user',
272 'cn': 'Test user',
273 'sn': 'Test user',
274 'uidNumber': '99998',
275 'gidNumber': '99998',
276 'homeDirectory': '/var/empty',
277 'loginShell': '/bin/false',
278 'description': cert_dn })
279
280 inst.config.set("nsslapd-accesslog-logbuffering", "off")
281 inst.config.set("nsslapd-errorlog-logbuffering", "off")
282
283 tmpdir_kwargs = {}
284 if sys.version_info >= (3, 12):
285 tmpdir_kwargs['delete'] = not DEBUGGING
286 with TemporaryDirectory(**tmpdir_kwargs) as dir:
287 scriptname = f"{dir}/doit"
288 d = {
289 'dir': dir,
290 'instname': inst.serverid,
291 'url': f"ldaps://localhost:{inst.sslport}",
292 'rootdn': DN_DM,
293 'rootpw': PW_DM,
294 }
295 with open(scriptname, 'w') as f:
296 f.write(script_content.format(**d))
297 res = subprocess.run(('/bin/bash', scriptname), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8')
298 assert res
299 log.info(res.stdout)
300 res.check_returncode()
301 # If ldapsearch is successful then defaultnamingcontext should be in res.stdout
302 assert "defaultnamingcontext" in res.stdout
303 assert inst.ds_access_log.match('.*RESULT.*dn="uid=test_user,ou=people,dc=example,dc=com".*')
304 assert inst.ds_access_log.match('.*TLS.*[PQC].*')
305 assert inst.ds_error_log.match('.*check_pqc.*')
306
307
308 if __name__ == '__main__':
309 # Run isolated
310 # -s for DEBUG mode
311 CURRENT_FILE = os.path.realpath(__file__)
312 pytest.main(["-s", CURRENT_FILE])