| 1 |
# --- BEGIN COPYRIGHT BLOCK --- |
| 2 |
# Copyright (C) 2022 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 os |
| 10 |
import sys |
| 11 |
import copy |
| 12 |
import datetime |
| 13 |
import ipaddress |
| 14 |
import ldap |
| 15 |
import ldapurl |
| 16 |
import logging |
| 17 |
import pytest |
| 18 |
import secrets |
| 19 |
import shutil |
| 20 |
import socket |
| 21 |
import subprocess |
| 22 |
import textwrap |
| 23 |
import time |
| 24 |
from contextlib import contextmanager, suppress |
| 25 |
from cryptography.hazmat.backends import default_backend |
| 26 |
from cryptography.hazmat.primitives.asymmetric import ec |
| 27 |
from cryptography.hazmat.primitives import hashes, serialization |
| 28 |
from cryptography.hazmat.primitives.serialization import pkcs12 |
| 29 |
from cryptography import x509 |
| 30 |
from cryptography.x509.oid import NameOID, ExtensionOID |
| 31 |
from lib389.cli_base import FakeArgs |
| 32 |
from lib389._constants import DN_DM, PW_DM |
| 33 |
from lib389.dseldif import DSEldif |
| 34 |
from test389.topologies import topology_st as topo |
| 35 |
from lib389.utils import ds_is_older, ensure_str |
| 36 |
from tempfile import NamedTemporaryFile |
| 37 |
|
| 38 |
pytestmark = pytest.mark.tier1 |
| 39 |
|
| 40 |
DYNCERT_SUFFIX = "cn=dynamiccertificates" |
| 41 |
DEBUGGING = os.getenv("DEBUGGING", default=False) |
| 42 |
if DEBUGGING: |
| 43 |
logging.getLogger(__name__).setLevel(logging.DEBUG) |
| 44 |
else: |
| 45 |
logging.getLogger(__name__).setLevel(logging.INFO) |
| 46 |
log = logging.getLogger(__name__) |
| 47 |
|
| 48 |
tls_enabled = False |
| 49 |
|
| 50 |
|
| 51 |
@contextmanager |
| 52 |
def redirect_stdio(msg): |
| 53 |
# Used to log stdin/stdout in pytest logs |
| 54 |
with NamedTemporaryFile('w+t') as f: |
| 55 |
oldstdout = os.dup(1) |
| 56 |
oldstderr = os.dup(2) |
| 57 |
os.dup2(f.fileno(), 1) |
| 58 |
os.dup2(f.fileno(), 2) |
| 59 |
try: |
| 60 |
yield f |
| 61 |
finally: |
| 62 |
os.dup2(oldstdout, 1) |
| 63 |
os.dup2(oldstderr, 2) |
| 64 |
os.close(oldstdout) |
| 65 |
os.close(oldstderr) |
| 66 |
f.seek(0) |
| 67 |
log.info(f'STDIO TRACE: start of {msg} traces') |
| 68 |
for line in f: |
| 69 |
log.info(f'STDIO TRACE: {line.rstrip()}') |
| 70 |
log.info(f'STDIO TRACE: end of {msg} traces') |
| 71 |
|
| 72 |
|
| 73 |
@contextmanager |
| 74 |
def traced_ldap_connection(url, msg): |
| 75 |
# Open ldap connection with traces |
| 76 |
with redirect_stdio(msg) as f: |
| 77 |
ldap.set_option(ldap.OPT_DEBUG_LEVEL, -1) |
| 78 |
ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3) |
| 79 |
l = ldap.initialize(url, trace_level=0, trace_file=f, trace_stack_limit=1) |
| 80 |
try: |
| 81 |
yield l |
| 82 |
finally: |
| 83 |
l.unbind() |
| 84 |
|
| 85 |
@contextmanager |
| 86 |
def ldapi(inst): |
| 87 |
l = open_ldapi_conn(inst) |
| 88 |
try: |
| 89 |
yield l |
| 90 |
finally: |
| 91 |
l.unbind() |
| 92 |
|
| 93 |
|
| 94 |
def utcdate(): |
| 95 |
return datetime.datetime.utcnow() # Python 3.8 |
| 96 |
# return datetime.datetime.now(datetime.UTC) # Python 3.11 |
| 97 |
|
| 98 |
|
| 99 |
################################ |
| 100 |
###### GENERATE CA CERT ######## |
| 101 |
################################ |
| 102 |
class ECDSA_Certificate: |
| 103 |
"""Elliptic Curve Certificate Generator""" |
| 104 |
|
| 105 |
PKCS12_PASSWORD = "a+password" |
| 106 |
|
| 107 |
def __init__(self): |
| 108 |
self.nickname = None |
| 109 |
self.trust = None |
| 110 |
self.namingAttrs = {} |
| 111 |
self.subject = None |
| 112 |
self.validity_days = 365 |
| 113 |
self.isCA = False |
| 114 |
self.isRoot = False |
| 115 |
self.caChain = None |
| 116 |
|
| 117 |
@staticmethod |
| 118 |
def generateRootCA(nickname, namingAttributes={}, validity_days=3650): |
| 119 |
"""Generate a self-signed Root CA certificate using elliptic curve""" |
| 120 |
ca = ECDSA_Certificate() |
| 121 |
ca.namingAttrs = namingAttributes |
| 122 |
ca.validity_days = validity_days |
| 123 |
ca.isCA = True |
| 124 |
ca.isRoot = True |
| 125 |
ca.nickname = nickname |
| 126 |
ca.fixNamingAttributes() |
| 127 |
ca.subject = x509.Name([x509.NameAttribute(k,v) for k,v in ca.namingAttrs.items()]) |
| 128 |
ca.issuer = ca.subject |
| 129 |
ca.trust = 'CT,,' |
| 130 |
|
| 131 |
# Generate prime256v1 private key |
| 132 |
ca.pkey = ec.generate_private_key( ec.SECP256R1(), default_backend()) |
| 133 |
ca.cert = ( |
| 134 |
x509.CertificateBuilder() |
| 135 |
.subject_name(ca.subject) |
| 136 |
.issuer_name(ca.issuer) |
| 137 |
.public_key(ca.pkey.public_key()) |
| 138 |
.serial_number(x509.random_serial_number()) |
| 139 |
.not_valid_before(utcdate()) |
| 140 |
.not_valid_after(utcdate() + datetime.timedelta(days=validity_days)) |
| 141 |
# CA certificate extensions |
| 142 |
.add_extension( |
| 143 |
x509.BasicConstraints(ca=True, path_length=0), |
| 144 |
critical=True, |
| 145 |
) |
| 146 |
.add_extension( |
| 147 |
x509.KeyUsage( |
| 148 |
digital_signature=False, |
| 149 |
key_cert_sign=True, |
| 150 |
crl_sign=False, |
| 151 |
key_encipherment=False, |
| 152 |
content_commitment=False, |
| 153 |
data_encipherment=False, |
| 154 |
key_agreement=False, |
| 155 |
encipher_only=False, |
| 156 |
decipher_only=False, |
| 157 |
), |
| 158 |
critical=True, |
| 159 |
) |
| 160 |
.add_extension( |
| 161 |
x509.SubjectKeyIdentifier.from_public_key(ca.pkey.public_key()), |
| 162 |
critical=False, |
| 163 |
) |
| 164 |
.sign(ca.pkey, hashes.SHA256(), default_backend()) |
| 165 |
) |
| 166 |
return ca |
| 167 |
|
| 168 |
@staticmethod |
| 169 |
def save_pem_file(filename, *items): |
| 170 |
"""Save PEM formatted items to file""" |
| 171 |
with open(filename, "wb") as f: |
| 172 |
for item in items: |
| 173 |
if isinstance(item, ec.EllipticCurvePrivateKey): |
| 174 |
pem = item.private_bytes( |
| 175 |
encoding=serialization.Encoding.PEM, |
| 176 |
format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 177 |
encryption_algorithm=serialization.NoEncryption() |
| 178 |
) |
| 179 |
elif isinstance(item, x509.Certificate): |
| 180 |
pem = item.public_bytes(serialization.Encoding.PEM) |
| 181 |
else: |
| 182 |
raise ValueError(f"Unknown item type: {type(item)}") |
| 183 |
f.write(pem) |
| 184 |
|
| 185 |
@staticmethod |
| 186 |
def save_der_file(filename, item): |
| 187 |
"""Save DER formatted item to file""" |
| 188 |
with open(filename, "wb") as f: |
| 189 |
if isinstance(item, ec.EllipticCurvePrivateKey): |
| 190 |
der = item.private_bytes( |
| 191 |
encoding=serialization.Encoding.DER, |
| 192 |
format=serialization.PrivateFormat.PKCS8, #format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 193 |
encryption_algorithm=serialization.NoEncryption() |
| 194 |
) |
| 195 |
elif isinstance(item, x509.Certificate): |
| 196 |
der = item.public_bytes(serialization.Encoding.DER) |
| 197 |
else: |
| 198 |
raise ValueError(f"Unknown item type: {type(item)}") |
| 199 |
f.write(der) |
| 200 |
|
| 201 |
def fixNamingAttribute(self, name, vdef): |
| 202 |
"""Set value for naming attribute if it is missing""" |
| 203 |
if name not in self.namingAttrs: |
| 204 |
self.namingAttrs[name] = vdef |
| 205 |
|
| 206 |
def fixNamingAttributes(self): |
| 207 |
"""Set default value for mandatory naming attributes""" |
| 208 |
self.fixNamingAttribute(NameOID.COMMON_NAME, self.nickname) |
| 209 |
self.fixNamingAttribute(NameOID.COUNTRY_NAME, 'US') |
| 210 |
self.fixNamingAttribute(NameOID.ORGANIZATION_NAME, 'Example Organization') |
| 211 |
|
| 212 |
def generateCA(self, nickname, namingAttributes={}, validity_days=3650): |
| 213 |
"""Generate an intermediary CA certificate using elliptic curve""" |
| 214 |
ca = ECDSA_Certificate() |
| 215 |
ca.namingAttrs = namingAttributes |
| 216 |
ca.validity_days = validity_days |
| 217 |
ca.isCA = True |
| 218 |
ca.isRoot = False |
| 219 |
ca.nickname = nickname |
| 220 |
ca.fixNamingAttributes() |
| 221 |
ca.subject = x509.Name([x509.NameAttribute(k,v) for k,v in ca.namingAttrs.items()]) |
| 222 |
ca.issuer = self.subject |
| 223 |
ca.trust = 'CT,,' |
| 224 |
|
| 225 |
# Generate prime256v1 private key |
| 226 |
ca.pkey = ec.generate_private_key( ec.SECP256R1(), default_backend()) |
| 227 |
ca.cert = ( |
| 228 |
x509.CertificateBuilder() |
| 229 |
.subject_name(ca.subject) |
| 230 |
.issuer_name(ca.issuer) |
| 231 |
.public_key(ca.pkey.public_key()) |
| 232 |
.serial_number(x509.random_serial_number()) |
| 233 |
.not_valid_before(utcdate()) |
| 234 |
.not_valid_after(utcdate() + datetime.timedelta(days=validity_days)) |
| 235 |
# CA certificate extensions |
| 236 |
.add_extension( |
| 237 |
x509.BasicConstraints(ca=True, path_length=0), |
| 238 |
critical=True, |
| 239 |
) |
| 240 |
.add_extension( |
| 241 |
x509.KeyUsage( |
| 242 |
digital_signature=False, |
| 243 |
key_cert_sign=True, |
| 244 |
crl_sign=False, |
| 245 |
key_encipherment=False, |
| 246 |
content_commitment=False, |
| 247 |
data_encipherment=False, |
| 248 |
key_agreement=False, |
| 249 |
encipher_only=False, |
| 250 |
decipher_only=False, |
| 251 |
), |
| 252 |
critical=True, |
| 253 |
) |
| 254 |
.add_extension( |
| 255 |
x509.SubjectKeyIdentifier.from_public_key(ca.pkey.public_key()), |
| 256 |
critical=False, |
| 257 |
) |
| 258 |
.add_extension( |
| 259 |
x509.AuthorityKeyIdentifier.from_issuer_public_key(self.pkey.public_key()), |
| 260 |
critical=False, |
| 261 |
) |
| 262 |
.sign(self.pkey, hashes.SHA256(), default_backend()) |
| 263 |
) |
| 264 |
return ca |
| 265 |
|
| 266 |
def generateCertificate(self, nickname, namingAttributes={}, hostname=None, validity_days=3650): |
| 267 |
"""Generate an user certificate using elliptic curve""" |
| 268 |
cert = ECDSA_Certificate() |
| 269 |
cert.namingAttrs = namingAttributes |
| 270 |
cert.validity_days = validity_days |
| 271 |
cert.isCA = False |
| 272 |
cert.isRoot = False |
| 273 |
cert.nickname = nickname |
| 274 |
cert.fixNamingAttributes() |
| 275 |
cert.subject = x509.Name([x509.NameAttribute(k,v) for k,v in cert.namingAttrs.items()]) |
| 276 |
cert.issuer = self.subject |
| 277 |
cert.trust = 'u,u,u' |
| 278 |
cert.caChain = self |
| 279 |
|
| 280 |
if hostname is None: |
| 281 |
hostname = socket.gethostname() |
| 282 |
|
| 283 |
san_list = [x509.DNSName(hostname),] |
| 284 |
if hostname != 'localhost': |
| 285 |
san_list.append(x509.DNSName(hostname)) |
| 286 |
san_list.append(x509.IPAddress(ipaddress.ip_address("127.0.0.1"))) |
| 287 |
san_list.append(x509.IPAddress(ipaddress.ip_address("::1"))) |
| 288 |
|
| 289 |
# Generate prime256v1 private key |
| 290 |
cert.pkey = ec.generate_private_key( ec.SECP256R1(), default_backend()) |
| 291 |
cert.cert = ( |
| 292 |
x509.CertificateBuilder() |
| 293 |
.subject_name(cert.subject) |
| 294 |
.issuer_name(cert.issuer) |
| 295 |
.public_key(cert.pkey.public_key()) |
| 296 |
.serial_number(x509.random_serial_number()) |
| 297 |
.not_valid_before(utcdate()) |
| 298 |
.not_valid_after(utcdate() + datetime.timedelta(days=validity_days)) |
| 299 |
# Server certificate extensions |
| 300 |
.add_extension( |
| 301 |
x509.BasicConstraints(ca=False, path_length=None), |
| 302 |
critical=True, |
| 303 |
) |
| 304 |
.add_extension( |
| 305 |
x509.KeyUsage( |
| 306 |
digital_signature=True, |
| 307 |
key_encipherment=True, |
| 308 |
key_cert_sign=False, |
| 309 |
crl_sign=False, |
| 310 |
content_commitment=False, |
| 311 |
data_encipherment=False, |
| 312 |
key_agreement=False, |
| 313 |
encipher_only=False, |
| 314 |
decipher_only=False, |
| 315 |
), |
| 316 |
critical=True, |
| 317 |
) |
| 318 |
.add_extension( |
| 319 |
x509.ExtendedKeyUsage([ |
| 320 |
x509.oid.ExtendedKeyUsageOID.SERVER_AUTH, |
| 321 |
x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH, |
| 322 |
]), |
| 323 |
critical=True, |
| 324 |
) |
| 325 |
.add_extension( |
| 326 |
x509.SubjectAlternativeName(san_list), |
| 327 |
critical=False, |
| 328 |
) |
| 329 |
.add_extension( |
| 330 |
x509.SubjectKeyIdentifier.from_public_key(cert.pkey.public_key()), |
| 331 |
critical=False, |
| 332 |
) |
| 333 |
.add_extension( |
| 334 |
x509.AuthorityKeyIdentifier.from_issuer_public_key(self.pkey.public_key()), |
| 335 |
critical=False, |
| 336 |
) |
| 337 |
.sign(self.pkey, hashes.SHA256(), default_backend()) |
| 338 |
) |
| 339 |
return cert |
| 340 |
|
| 341 |
def write_pkcs12_file(self, filename, pw=PKCS12_PASSWORD): |
| 342 |
"""Save PKCS12 formatede certificate and private key""" |
| 343 |
if isinstance(pw, str): |
| 344 |
pw = pw.encode() |
| 345 |
if pw is None or pw == b"": |
| 346 |
enc = serialization.NoEncryption() |
| 347 |
else: |
| 348 |
enc = serialization.BestAvailableEncryption(pw) |
| 349 |
with open(filename, "wb") as f: |
| 350 |
f.write(pkcs12.serialize_key_and_certificates( |
| 351 |
self.nickname.encode(), |
| 352 |
self.pkey, |
| 353 |
self.cert, |
| 354 |
[], |
| 355 |
enc |
| 356 |
)) |
| 357 |
|
| 358 |
def save(self, dirname, pk12pw=PKCS12_PASSWORD): |
| 359 |
print(f'Writing files for {self.nickname}') |
| 360 |
if self.isCA: |
| 361 |
name = f'{dirname}/{self.nickname}-ca' |
| 362 |
else: |
| 363 |
name = f'{dirname}/{self.nickname}-cert' |
| 364 |
self.pem = f"{name}-cert.pem" |
| 365 |
self.der = f"{name}-cert.der" |
| 366 |
self.key = f"{name}-key.pem" |
| 367 |
self.kder = f"{name}-key.der" |
| 368 |
self.p12 = f"{name}.p12" |
| 369 |
ECDSA_Certificate.save_pem_file(self.pem, self.cert) |
| 370 |
ECDSA_Certificate.save_der_file(self.der, self.cert) |
| 371 |
ECDSA_Certificate.save_pem_file(self.key, self.pkey) |
| 372 |
ECDSA_Certificate.save_der_file(self.kder, self.pkey) |
| 373 |
self.write_pkcs12_file(self.p12, pk12pw) |
| 374 |
|
| 375 |
def run(self, cmd): |
| 376 |
log.info(f'Running: {" ".join(cmd)}') |
| 377 |
res = subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') |
| 378 |
assert res |
| 379 |
log.info(f'Stdout+Stderr:{res.stdout}') |
| 380 |
res.check_returncode() |
| 381 |
|
| 382 |
def __repr__(self): |
| 383 |
return self.nickname |
| 384 |
|
| 385 |
@staticmethod |
| 386 |
def nss_db_paths(inst): |
| 387 |
prefix = os.environ.get('PREFIX', "/") |
| 388 |
certdbdir = f"{prefix}/etc/dirsrv/slapd-{inst.serverid}" |
| 389 |
pwfile = f'{certdbdir}/pwdfile.txt' |
| 390 |
return ( prefix, certdbdir, pwfile ) |
| 391 |
|
| 392 |
def clear_nss_db(self, inst): |
| 393 |
prefix, certdbdir, pwfile = ECDSA_Certificate.nss_db_paths(inst) |
| 394 |
inst.stop() |
| 395 |
for f in ('cert9.db', 'key4.db'): |
| 396 |
try: |
| 397 |
os.remove(f'{certdbdir}/{f}') |
| 398 |
except OSError: |
| 399 |
pass |
| 400 |
self.run(('certutil', '-N', '-d', certdbdir, '-f', pwfile, '-@', pwfile)) |
| 401 |
|
| 402 |
def offline_install(self, inst): |
| 403 |
prefix, certdbdir, pwfile = ECDSA_Certificate.nss_db_paths(inst) |
| 404 |
if self.isCA: |
| 405 |
self.run(('certutil', '-A', '-n', self.nickname, '-t', 'CT,,', '-f', pwfile, '-d', certdbdir, '-a', '-i', self.pem)) |
| 406 |
else: |
| 407 |
self.run(('pk12util', '-v', '-i', self.p12, '-d', certdbdir, '-k', pwfile, '-W', ECDSA_Certificate.PKCS12_PASSWORD)) |
| 408 |
|
| 409 |
def show(self, inst): |
| 410 |
prefix, certdbdir, pwfile = ECDSA_Certificate.nss_db_paths(inst) |
| 411 |
self.run(('certutil', '-L', '-n', self.nickname, '-d', certdbdir)) |
| 412 |
|
| 413 |
def rename(self, inst, newname): |
| 414 |
olddn = f'cn={self.nickname},{DYNCERT_SUFFIX}' |
| 415 |
newdn = f'cn={newname}' |
| 416 |
with ldapi(inst) as ldc: |
| 417 |
ldc.modrdn_s(olddn, newdn) |
| 418 |
newobj = copy.copy(self) |
| 419 |
newobj.nickname = newname |
| 420 |
return newobj |
| 421 |
|
| 422 |
def delete(self, inst): |
| 423 |
dn = f'cn={self.nickname},{DYNCERT_SUFFIX}' |
| 424 |
with ldapi(inst) as ldc: |
| 425 |
ldc.delete_s(dn) |
| 426 |
|
| 427 |
def showAll(self, inst): |
| 428 |
prefix, certdbdir, pwfile = ECDSA_Certificate.nss_db_paths(inst) |
| 429 |
self.run(('certutil', '-L', '-d', certdbdir)) |
| 430 |
|
| 431 |
def read_cert(self, inst): |
| 432 |
with ldapi(inst) as ldc: |
| 433 |
with suppress(ldap.NO_SUCH_OBJECT): |
| 434 |
dn = f'cn={self.nickname},{DYNCERT_SUFFIX}' |
| 435 |
res = ldc.search_s(dn, ldap.SCOPE_BASE) |
| 436 |
log.info(f'Certificate {self.nickname} is {res}') |
| 437 |
return res |
| 438 |
log.info(f'Certificate {self.nickname} is not found') |
| 439 |
return None |
| 440 |
|
| 441 |
def online_install(self, inst): |
| 442 |
old_cert = self.read_cert(inst) |
| 443 |
log.info(f'Before online_install: cert={old_cert}') |
| 444 |
dn = f'cn={self.nickname},{DYNCERT_SUFFIX}' |
| 445 |
if self.isCA: |
| 446 |
# Read DER file |
| 447 |
with open(self.der, "rb") as f: |
| 448 |
dercert = f.read() |
| 449 |
derpkey = None |
| 450 |
else: |
| 451 |
# Read PKCS12 file |
| 452 |
with open(self.p12, "rb") as f: |
| 453 |
p12_data = f.read() |
| 454 |
p12pw = ECDSA_Certificate.PKCS12_PASSWORD.encode() |
| 455 |
privkey, cert, cas = pkcs12.load_key_and_certificates(p12_data, p12pw) |
| 456 |
dercert = cert.public_bytes(serialization.Encoding.DER) |
| 457 |
derpkey = privkey.private_bytes(encoding=serialization.Encoding.DER, |
| 458 |
format=serialization.PrivateFormat.PKCS8, |
| 459 |
encryption_algorithm=serialization.NoEncryption()) |
| 460 |
with ldapi(inst) as ldc: |
| 461 |
if old_cert: |
| 462 |
log.info(f'+++ Trying to replace {dn} +++') |
| 463 |
mods = [(ldap.MOD_REPLACE, 'nsDynamicCertificateDER', [ dercert, ]),] |
| 464 |
if derpkey: |
| 465 |
mods.append((ldap.MOD_REPLACE, 'nsDynamicCertificatePrivateKeyDER', [ derpkey, ])) |
| 466 |
ldc.modify_s(dn, mods) |
| 467 |
self.show(inst) |
| 468 |
else: |
| 469 |
log.info(f'+++ Trying to add {dn} +++') |
| 470 |
e = [ |
| 471 |
('cn', [ self.nickname.encode(encoding="utf-8"), ] ), |
| 472 |
('objectclass', [ b'top', b'extensibleobject' ] ), |
| 473 |
('dsDynamicCertificateDER', [ dercert, ] ), |
| 474 |
] |
| 475 |
if derpkey: |
| 476 |
e.append(('dsDynamicCertificatePrivateKeyDER', [derpkey,])) |
| 477 |
ldc.add_s(dn, e) |
| 478 |
new_cert = self.read_cert(inst) |
| 479 |
log.info(f'After online_install: cert={new_cert}') |
| 480 |
assert new_cert != old_cert |
| 481 |
|
| 482 |
def setSslPersonality(self, inst): |
| 483 |
ldc = open_ldapi_conn(inst) |
| 484 |
dn='cn=RSA,cn=encryption,cn=config' |
| 485 |
mods = [ (ldap.MOD_REPLACE, 'nsSSLPersonalitySSL', [ self.nickname.encode(), ]), ] |
| 486 |
ldc.modify_s(dn, mods) |
| 487 |
|
| 488 |
|
| 489 |
######################################################### |
| 490 |
###### Work around to debug libldap/liblber CERT ######## |
| 491 |
######################################################### |
| 492 |
|
| 493 |
def open_ldap(url, logfile): |
| 494 |
if logfile is not None: |
| 495 |
lutil_debug_file(logfile) |
| 496 |
ldap.set_option(ldap.OPT_DEBUG_LEVEL, -1) |
| 497 |
loglv = 3 |
| 498 |
else: |
| 499 |
lutil_debug_file(logfile) |
| 500 |
ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0) |
| 501 |
loglv = 0 |
| 502 |
logfile = sys.stderr |
| 503 |
ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3) |
| 504 |
return ldap.initialize(url, trace_level=loglv, trace_file=logfile) |
| 505 |
|
| 506 |
|
| 507 |
######################### |
| 508 |
###### TEST CERT ######## |
| 509 |
######################### |
| 510 |
|
| 511 |
def open_ldaps_conn(inst, ca): |
| 512 |
url = f'ldaps://localhost:{inst.sslport}' |
| 513 |
log.info(f'Attempt to connect to {url} using {ca.pem}') |
| 514 |
ld = ldap.initialize(url) |
| 515 |
#ld.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,ldap.OPT_X_TLS_NEVER) |
| 516 |
ld.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,ldap.OPT_X_TLS_DEMAND) |
| 517 |
ld.set_option(ldap.OPT_X_TLS_CACERTFILE, f'{ca.pem}') |
| 518 |
ld.set_option(ldap.OPT_X_TLS_NEWCTX, 0) |
| 519 |
return ld |
| 520 |
|
| 521 |
|
| 522 |
def open_ldapi_conn(inst, logfile=None): |
| 523 |
dse = DSEldif(inst) |
| 524 |
ldapi_socket = dse.get('cn=config', 'nsslapd-ldapifilepath', single=True) |
| 525 |
url = f"ldapi://{ldapurl.ldapUrlEscape(ensure_str(ldapi_socket))}" |
| 526 |
log.info(f'Attempt to connect to {url} using sasl external authentication') |
| 527 |
ld = ldap.initialize(url) |
| 528 |
# Perform autobind |
| 529 |
sasl_auth = ldap.sasl.external() |
| 530 |
ld.sasl_interactive_bind_s("", sasl_auth) |
| 531 |
return ld |
| 532 |
|
| 533 |
|
| 534 |
def tls_search(inst, ca): |
| 535 |
url = f'ldaps://localhost:{inst.sslport}' |
| 536 |
log.info(f'Attempt to connect to {url} using {ca.pem}') |
| 537 |
with traced_ldap_connection(url, f'ldaps bind using CA {ca}') as ld: |
| 538 |
#ld.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,ldap.OPT_X_TLS_NEVER) |
| 539 |
ld.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,ldap.OPT_X_TLS_DEMAND) |
| 540 |
ld.set_option(ldap.OPT_X_TLS_CACERTFILE, f'{ca.pem}') |
| 541 |
ld.set_option(ldap.OPT_X_TLS_NEWCTX, 0) |
| 542 |
ld.simple_bind_s(DN_DM, PW_DM) |
| 543 |
results = ld.search_s('', ldap.SCOPE_BASE) |
| 544 |
assert len(results) == 1 |
| 545 |
|
| 546 |
|
| 547 |
# |
| 548 |
# Ideally There should be a dsctl/dsconf subcommand |
| 549 |
# |
| 550 |
def refresh_certs(inst, timeout=60): |
| 551 |
ld = open_ldapi_conn(inst) |
| 552 |
ld.modify_s('cn=config', [(ldap.MOD_REPLACE, 'nsslapd-refresh-certificates', b'on')]) |
| 553 |
# Now lets wait until the config value is off again |
| 554 |
for _ in range(timeout): |
| 555 |
result = ld.search_s('cn=config', ldap.SCOPE_BASE, attrlist=['nsslapd-refresh-certificates',]) |
| 556 |
log.info(f'cn=config result: {result}') |
| 557 |
attrs = result[0][1] |
| 558 |
vals = attrs['nsslapd-refresh-certificates'] |
| 559 |
if vals[0].decode("utf-8").lower() == "off": |
| 560 |
ld.unbind() |
| 561 |
return |
| 562 |
time.sleep(1) |
| 563 |
raise TimeoutError(f"Certificate not changed after {timeout} secopnds") |
| 564 |
|
| 565 |
# Generate Server Certifcate and Root CA and install them |
| 566 |
@pytest.fixture(scope="module") |
| 567 |
def ecdsa_certs(topo, request): |
| 568 |
dir = '/tmp/ecdsa_certs' |
| 569 |
def fin(): |
| 570 |
if not DEBUGGING: |
| 571 |
with suppress(FileNotFoundError): |
| 572 |
shutil.rmtree(dir) |
| 573 |
request.addfinalizer(fin) |
| 574 |
with suppress(FileNotFoundError): |
| 575 |
shutil.rmtree(dir) |
| 576 |
os.makedirs(dir, 0o700) |
| 577 |
inst=topo.standalone |
| 578 |
global tls_enabled |
| 579 |
if not tls_enabled: |
| 580 |
inst.enable_tls() |
| 581 |
tls_enabled = True |
| 582 |
ca = ECDSA_Certificate.generateRootCA("CA") |
| 583 |
cert = ca.generateCertificate("Cert") |
| 584 |
cert.setSslPersonality(inst) |
| 585 |
ca.clear_nss_db(inst) |
| 586 |
ca.showAll(inst) |
| 587 |
ca.save(dir) |
| 588 |
cert.save(dir) |
| 589 |
cert.offline_install(inst) |
| 590 |
cert.show(inst) |
| 591 |
ca.offline_install(inst) |
| 592 |
ca.show(inst) |
| 593 |
ca.showAll(inst) |
| 594 |
inst.restart(post_open=False) |
| 595 |
return (cert, ca, dir) |
| 596 |
|
| 597 |
|
| 598 |
def test_ecdsa(topo, ecdsa_certs): |
| 599 |
"""Setup instance with ecdsa certificates |
| 600 |
|
| 601 |
:id: 7902f37c-01d3-11ed-b65c-482ae39447e5 |
| 602 |
:setup: Standalone Instance with ecdsa certificates |
| 603 |
:steps: |
| 604 |
1. Open ldaps connection with server CA certificate and search root entry |
| 605 |
:expectedresults: |
| 606 |
1. No error |
| 607 |
""" |
| 608 |
|
| 609 |
inst=topo.standalone |
| 610 |
cert, ca, dir = ecdsa_certs |
| 611 |
tls_search(inst, ca) |
| 612 |
|
| 613 |
|
| 614 |
def test_dynamic(topo, ecdsa_certs): |
| 615 |
"""Check that certificates can be managed dynamically |
| 616 |
|
| 617 |
:id: 20615484-db69-11f0-aad9-c85309d5c3e3 |
| 618 |
:setup: Standalone Instance with ecdsa certificates |
| 619 |
:steps: |
| 620 |
1. Create Test-DynCert-1 certificate |
| 621 |
2. Add it dynamically |
| 622 |
3. Search for Test-DynCert-1 |
| 623 |
4. Rename Test-DynCert-1 as Test-DynCert-2 |
| 624 |
5. Search for Test-DynCert-1 |
| 625 |
6. Search for Test-DynCert-2 |
| 626 |
7. Delete dynamically Test-DynCert-2 |
| 627 |
8. Search for Test-DynCert-2 |
| 628 |
:expectedresults: |
| 629 |
1. No error |
| 630 |
2. No error |
| 631 |
3. Entry should exists |
| 632 |
4. No error |
| 633 |
5. Entry should not exists |
| 634 |
6. Entry should exists |
| 635 |
7. No error |
| 636 |
8. Entry should not exists |
| 637 |
""" |
| 638 |
|
| 639 |
inst=topo.standalone |
| 640 |
cert, ca, dir = ecdsa_certs |
| 641 |
cert1 = ca.generateCertificate("Test-DynCert-1") |
| 642 |
cert1.save(dir) |
| 643 |
cert1.online_install(inst) |
| 644 |
assert cert1.read_cert(inst) |
| 645 |
cert2 = cert1.rename(inst, "Test-DynCert-2") |
| 646 |
assert not cert1.read_cert(inst) |
| 647 |
assert cert2.read_cert(inst) |
| 648 |
cert2.delete(inst) |
| 649 |
assert not cert2.read_cert(inst) |
| 650 |
|
| 651 |
|
| 652 |
def test_refresh_ecdsa_1ca(topo, ecdsa_certs): |
| 653 |
"""Test dynamic refresh of server certificate |
| 654 |
|
| 655 |
:id: 96039bce-5370-11f0-9de5-c85309d5c3e3 |
| 656 |
:setup: Standalone Instance with ecdsa certificates |
| 657 |
:steps: |
| 658 |
1. Open ldaps connection with server CA certificate and search root entry |
| 659 |
2. Open a second ldaps connection with server CA certificate and keep it open |
| 660 |
3. Generate a new server certificate (signed by original CA) |
| 661 |
4. Change nsSSLPersonalitySSL to the new certificate nickname |
| 662 |
5. Add the new server cert (using add operation on dynamic certificates) |
| 663 |
6. Open ldaps connection with server CA certificate and search root entry |
| 664 |
7. Perform a search on the second open ldaps connection |
| 665 |
:expectedresults: |
| 666 |
1. No error |
| 667 |
2. No error |
| 668 |
3. No error |
| 669 |
4. No error |
| 670 |
5. No error |
| 671 |
6. No error |
| 672 |
7. No error |
| 673 |
""" |
| 674 |
|
| 675 |
inst=topo.standalone |
| 676 |
cert, ca, dir = ecdsa_certs |
| 677 |
tls_search(inst, ca) |
| 678 |
ld = open_ldaps_conn(inst, ca) |
| 679 |
cert2 = ca.generateCertificate("New-Cert-1CA") |
| 680 |
cert2.save(dir) |
| 681 |
cert2.setSslPersonality(inst) |
| 682 |
cert2.online_install(inst) |
| 683 |
tls_search(inst, ca) |
| 684 |
with redirect_stdio(f"Search using already open connection with CA: {ca}"): |
| 685 |
results = ld.search_s('', ldap.SCOPE_BASE) |
| 686 |
assert len(results) == 1 |
| 687 |
ld.unbind() |
| 688 |
|
| 689 |
|
| 690 |
def test_refresh_ecdsa_2ca(topo, ecdsa_certs): |
| 691 |
"""Test dynamic refresh of server certificate and CA |
| 692 |
|
| 693 |
:id: f77ae9b0-db70-11f0-a059-c85309d5c3e3 |
| 694 |
:setup: Standalone Instance |
| 695 |
:steps: |
| 696 |
1. Open ldaps connection with server CA certificate and search root entry |
| 697 |
2. Open a second ldaps connection with server CA certificate and keep it open |
| 698 |
3. Generate a new Self Signed CA |
| 699 |
4. Generate a new server certificate (signed by the new CA) |
| 700 |
5. Add the new CA (using add operation on dynamic certificates) |
| 701 |
6. Add the new server cert (using add operation on dynamic certificates) |
| 702 |
7. Open ldaps connection with old server CA certificate and search root entry |
| 703 |
8. Open ldaps connection with new server CA certificate and search root entry |
| 704 |
9. Perform a search on the second open ldaps connection |
| 705 |
:expectedresults: |
| 706 |
1. No error |
| 707 |
2. No error |
| 708 |
3. No error |
| 709 |
4. No error |
| 710 |
5. No error |
| 711 |
6. No error |
| 712 |
7. ldap.SERVER_DOWN because the old CA does not match the server one |
| 713 |
8. No error |
| 714 |
9. ldap.SERVER_DOWN because the old CA does not match the server one |
| 715 |
""" |
| 716 |
|
| 717 |
inst=topo.standalone |
| 718 |
cert, ca, dir = ecdsa_certs |
| 719 |
tls_search(inst, ca) |
| 720 |
ld = open_ldaps_conn(inst, ca) |
| 721 |
ca2 = ECDSA_Certificate.generateRootCA("New-CA-2CA") |
| 722 |
cert2 = ca2.generateCertificate("New-Cert-2CA") |
| 723 |
ca2.save(dir) |
| 724 |
cert2.save(dir) |
| 725 |
cert2.setSslPersonality(inst) |
| 726 |
ca2.online_install(inst) |
| 727 |
cert2.online_install(inst) |
| 728 |
with pytest.raises(ldap.SERVER_DOWN): |
| 729 |
tls_search(inst, ca) |
| 730 |
tls_search(inst, ca2) |
| 731 |
with redirect_stdio(f"Search using already open connection with CA: {ca}"): |
| 732 |
with pytest.raises(ldap.SERVER_DOWN): |
| 733 |
results = ld.search_s('', ldap.SCOPE_BASE) |
| 734 |
assert len(results) == 1 |
| 735 |
ld.unbind() |
| 736 |
|
| 737 |
|
| 738 |
if __name__ == '__main__': |
| 739 |
# Run isolated |
| 740 |
# -s for DEBUG mode |
| 741 |
CURRENT_FILE = os.path.realpath(__file__) |
| 742 |
pytest.main(["-s", CURRENT_FILE]) |