

Author: ICARAX AI Engineering Team
Topic: Security Engineering & Certificate Lifecycle Management
Context: When TLS certificates are compromised (e.g., through private key leakage or CA breaches), they expose critical security flaws in signing infrastructures like eMudhra's keys. This guide teaches you how to build an automated monitoring system to detect revoked or suspicious certificates.
Before implementing certificate monitoring, ensure you have the following:
*.emudhra.com) to monitor.openssl installed on your local machine for manual verification.Run the following commands to set up your development environment.
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install necessary security and networking libraries
pip install cryptography requests pyopenssl
# Initialize project
npm init -y
# Install dependencies
# cryptography: for parsing certs, axios: for HTTP requests
npm install cryptography axios x509-parser
npm install --save-dev typescript @types/node
We will build a "Certificate Integrity Checker" that verifies if a certificate is valid, not expired, and checks its revocation status.
This script uses the cryptography library to inspect certificate metadata and simulate an OCSP check.
import ssl
import socket
from datetime import datetime
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import requests
class CertificateSecurityMonitor:
def __init__(self, hostname: str, port: int = 443):
self.hostname = hostname
self.port = port
def fetch_certificate(self) -> x509.Certificate:
"""Fetches the TLS certificate from the remote host."""
context = ssl.create_default_context()
try:
with socket.create_connection((self.hostname, self.port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=self.hostname) as ssock:
cert_der = ssock.getpeercert(binary_form=True)
return x509.load_der_x509_certificate(cert_der, default_backend())
except Exception as e:
print(f"[!] Error fetching certificate for {self.hostname}: {e}")
raise
def validate_certificate(self, cert: x509.Certificate):
"""Performs security checks on the certificate."""
print(f"--- Security Report for {self.hostname} ---")
# 1. Check Expiration
now = datetime.utcnow()
if cert.not_valid_after < now:
print("[CRITICAL] Certificate has EXPIRED!")
else:
print(f"[OK] Certificate valid until: {cert.not_valid_after}")
# 2. Check Subject/Issuer (Integrity Check)
subject = cert.subject.rfc4514_string()
issuer = cert.issuer.rfc4514_string()
print(f"[INFO] Subject: {subject}")
print(f"[INFO] Issuer: {issuer}")
# 3. Simulated Revocation Check (In production, use OCSP)
# This is where you would call an OCSP responder to check if the key was compromised
print("[INFO] Performing OCSP revocation check...")
is_revoked = self._simulate_ocsp_check(cert)
if is_revoked:
print("[CRITICAL] ALERT: Certificate is REVOKED! Potential compromise detected.")
else:
print("[OK] Certificate revocation status: GOOD")
def _simulate_ocsp_check(self, cert: x509.Certificate) -> bool:
"""
Placeholder for actual OCSP logic.
In a real scenario, you'd parse cert.extensions for the OCSP URL.
"""
# Logic: If the certificate serial number matches a known compromised list
compromised_serials = ["123456789"]
return str(cert.serial_number) in compromised_serials
if __name__ == "__main__":
# Example usage
monitor = CertificateSecurityMonitor("google.com")
try:
cert = monitor.fetch_certificate()
monitor.validate_certificate(cert)
except Exception as e:
print(f"Failed to complete security audit: {e}")
Using axios and tls to inspect certificate chains.
import * as tls from 'tls';
import * as net from 'net';
interface CertSecurityReport {
hostname: string;
valid: boolean;
expiryDate: Date;
subject: string;
error?: string;
}
class CertChecker {
/**
* Connects to a host and retrieves certificate details
*/
public async checkCertificate(hostname: string, port: number = 443): Promise<CertSecurityReport> {
return new Promise((resolve) => {
const options: tls.TLSOptions = {
host: hostname,
port: port,
rejectUnauthorized: false, // We want to inspect even invalid certs
};
const socket = tls.connect(port, hostname, options, () => {
const cert = socket.getPeerCertificate();
if (!cert || Object.keys(cert).length === 0) {
resolve({
hostname,
valid: false,
expiryDate: new Date(),
subject: 'Unknown',
error: 'No certificate found'
});
return;
}
resolve({
hostname,
valid: socket.authorized,
expiryDate: new Date(cert.valid_to!),
subject: cert.subject.CN || 'Unknown'
});
socket.end();
});
socket.on('error', (err) => {
resolve({
hostname,
valid: false,
expiryDate: new Date(),
subject: 'Error',
error: err.message
});
});
socket.setTimeout(5000, () => {
socket.destroy();
resolve({
hostname,
valid: false,
expiryDate: new Date(),
subject: 'Timeout',
error: 'Connection timed out'
});
});
});
}
}
// --- Execution ---
const checker = new CertChecker();
checker.checkCertificate('google.com').then(report => {
console.log("--- TLS Security Report ---");
console.log(JSON.stringify(report, null, 2));
if (!report.valid) {
console.error("⚠️ SECURITY WARNING: Certificate is not trusted or invalid!");
} else {
console.log("✅ Certificate appears secure.");
}
});
Never hardcode sensitive monitoring targets or alert endpoints. Use environment variables.
Create a .env file:
# Domains to monitor for compromise
MONITOR_DOMAINS=api.emudhra.com,portal.emudhra.com,auth.emudhra.com
# Alerting Webhook (e.g., Slack or PagerDuty)
SECURITY_ALERT_WEBHOOK_URL=https://hooks.slack.com/services/T000/B000/XXXX
# Threshold for expiration warning (in days)
EXPIRY_WARNING_THRESHOLD=30
Instead of checking on-demand, developers run a cron job or a background worker that iterates through a database of active certificates and logs results to a SIEM (Security Information and Event Management) system.
# Pseudo-code for a Watchdog pattern
def watchdog_loop():
domains = load_domains_from_db()
for domain in domains:
report = monitor.check_certificate(domain)
if report.is_compromised():
send_to_pagerduty(report)
save_to_audit_log(report)
| Error | Cause | Solution |
|---|---|---|
SSLError: hostname mismatch | The certificate was issued for a different domain. | Check if your load balancer is serving the wrong SNI (Server Name Indication). |
Connection Timeout | Firewall is blocking port 443 or the OCSP responder is down. | Ensure outbound traffic to CA responders is permitted. |
Certificate Expired | Automated renewal (e.g., Let's Encrypt) failed. | Check ACME client logs and DNS challenge status. |
Handshake Failure | Incompatible TLS versions (e.g., trying to use TLS 1.0). | Upgrade your client library to support TLS 1.2/1.3. |
Before deploying this to monitor critical infrastructure like eMudhra's keys:
Source: Schneier on Security
Follow ICARAX for more AI insights and tutorials.
