Analysis of the Certificate Authorities accessible within AWS Lambda.
- Install python version similar to one installed on aws lambda (eg: 3.12)
- Download
cryptography
package intopython
subfolder using command listed at https://docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-create-update - Zip
python
folder and upload to layers. - Create python function with below code
- Assign cryptography layer to python function.
import json
import ssl
from cryptography import x509
from cryptography.hazmat.backends import default_backend
def list_root_ca_names():
names = []
logs = [] # Collect all log messages here
cafile = ssl.get_default_verify_paths().cafile
logs.append(f"Default CA file path: {cafile}")
try:
with open(cafile, 'rb') as f:
cert_data = f.read()
logs.append("Successfully read CA file.")
# Split each certificate in PEM format
pem_certs = cert_data.split(b"-----END CERTIFICATE-----")
logs.append(f"Number of certificates found: {len(pem_certs) - 1}")
for pem_cert in pem_certs:
if pem_cert.strip(): # Ignore empty splits
pem_cert = pem_cert.strip() + b"\n-----END CERTIFICATE-----\n"
try:
# Load the certificate
cert = x509.load_pem_x509_certificate(pem_cert, default_backend())
# Extract the Common Name (CN)
cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value
logs.append(f"Found CN: {cn}")
names.append(cn)
except Exception as cert_error:
logs.append(f"Error processing certificate: {cert_error}")
except Exception as e:
error_message = f"Error reading {cafile}: {e}"
logs.append(error_message)
names.append(error_message)
logs.append(f"Total CN names found: {len(names)}")
# Join all logs into a single string
full_log = "\n".join(logs)
print(full_log) # Log the full output once
return names
def lambda_handler(event, context):
# Retrieve root CA certificate names
root_certificate_names = list_root_ca_names()
return {
'statusCode': 200,
'rootCertificateNames': root_certificate_names # Return the list directly
}
Response as of 2024-10-31