2023-06-06 15:51:54 -07:00
|
|
|
from typing import List
|
|
|
|
|
2023-06-07 15:40:02 -07:00
|
|
|
import tldextract
|
2023-06-06 15:51:54 -07:00
|
|
|
from cryptography import x509
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
2023-06-07 14:35:48 -07:00
|
|
|
from cryptography.hazmat.primitives import serialization
|
|
|
|
from fastapi import HTTPException
|
2023-06-06 15:51:54 -07:00
|
|
|
|
2023-06-07 14:35:48 -07:00
|
|
|
from crowdtls.logs import logger
|
|
|
|
from crowdtls.models import Certificate
|
|
|
|
from crowdtls.models import Domain
|
2023-06-06 15:51:54 -07:00
|
|
|
|
|
|
|
|
2023-06-07 14:35:48 -07:00
|
|
|
def decode_der(fingerprint: str, raw_der_certificate: List[int]) -> Certificate:
|
2023-06-06 15:51:54 -07:00
|
|
|
der_cert_bytes = bytes(raw_der_certificate)
|
|
|
|
cert = x509.load_der_x509_certificate(der_cert_bytes, default_backend())
|
|
|
|
|
2023-06-07 14:35:48 -07:00
|
|
|
public_key_bytes = cert.public_key().public_bytes(
|
|
|
|
encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
|
)
|
|
|
|
|
|
|
|
return Certificate(
|
|
|
|
fingerprint=fingerprint,
|
2023-06-06 15:51:54 -07:00
|
|
|
version=cert.version.value,
|
|
|
|
serial_number=cert.serial_number,
|
|
|
|
signature=cert.signature,
|
|
|
|
issuer=cert.issuer.rfc4514_string(),
|
2023-06-07 14:35:48 -07:00
|
|
|
not_valid_before=cert.not_valid_before,
|
|
|
|
not_valid_after=cert.not_valid_after,
|
2023-06-06 15:51:54 -07:00
|
|
|
subject=cert.subject.rfc4514_string(),
|
2023-06-07 14:35:48 -07:00
|
|
|
subject_public_key_info=public_key_bytes,
|
|
|
|
raw_der_certificate=der_cert_bytes,
|
2023-06-06 15:51:54 -07:00
|
|
|
)
|
|
|
|
|
2023-06-07 14:35:48 -07:00
|
|
|
|
|
|
|
def parse_hostname(hostname: str) -> Domain:
|
|
|
|
try:
|
2023-06-07 15:40:02 -07:00
|
|
|
parsed_domain = tldextract.extract(hostname)
|
|
|
|
return Domain(fqdn=hostname, root=parsed_domain.domain, tld=parsed_domain.suffix)
|
2023-06-07 14:35:48 -07:00
|
|
|
except Exception:
|
|
|
|
logger.error(f"Failed to parse hostname: {hostname}")
|
|
|
|
|
|
|
|
|
|
|
|
def raise_HTTPException(
|
|
|
|
status_code: int = 500, detail: str = "Error encountered and reported. Please try again later."
|
|
|
|
) -> None:
|
|
|
|
raise HTTPException(status_code=status_code, detail=detail)
|