python_signed_mail/functions/get_certificate_ldap.py

67 lines
1.7 KiB
Python

import ldap3 # type: ignore
import base64
import re
import asn1crypto # type:ignore
from asn1crypto import x509
def get_certificate_ldap(
recipient_email: str, config_dict: dict
) -> asn1crypto.x509.Certificate | None:
server: ldap3.core.server.Server = ldap3.Server(
config_dict["ldap_host"], get_info=ldap3.ALL
)
results: list[str] = []
try:
with ldap3.Connection(
server,
auto_bind=True,
) as conn:
conn.search(
search_base=config_dict["people_dn"],
search_filter=f"(mail={recipient_email})",
attributes=["userSMIMECertificate"],
)
for entry in conn.entries:
temp_value = entry["userSMIMECertificate"].values
if len(temp_value) == 1:
results.append(temp_value[0])
except Exception as e:
print(f"Error creating user: {e}")
return None
if len(results) != 1:
return None
certificate_pem = base64.b64decode(results[0])
try:
# Extract the certificate data using regular expressions
cert_data = (
re.search( # type: ignore
rb"-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----",
certificate_pem,
re.DOTALL,
)
.group(1)
.strip()
)
# Decode the base64-encoded certificate data
cert_bytes = base64.b64decode(cert_data)
# Load the certificate into an ASN.1 object
asn1_cert = x509.Certificate.load(cert_bytes)
return asn1_cert
except (re.error, ValueError):
return None
return None