Skip to main content

seer_core/
ssl.rs

1//! SSL certificate chain inspection.
2//!
3//! Provides detailed SSL/TLS certificate information including the certificate
4//! chain, Subject Alternative Names (SANs), key details, and validity status.
5
6use std::time::Duration;
7
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use tokio::net::TcpStream;
11use tokio_native_tls::TlsConnector;
12use tracing::{debug, instrument};
13use x509_parser::oid_registry::Oid;
14use x509_parser::prelude::*;
15
16use crate::error::{Result, SeerError};
17use crate::validation::{describe_reserved_ip, normalize_domain};
18
19/// Default timeout for SSL operations (10 seconds).
20const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
21
22/// Full SSL certificate report for a domain.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct SslReport {
25    /// The domain that was inspected
26    pub domain: String,
27    /// Certificate chain from leaf to root (as many as the server provides)
28    pub chain: Vec<CertDetail>,
29    /// TLS protocol version (best-effort detection)
30    pub protocol_version: Option<String>,
31    /// Subject Alternative Names from the leaf certificate
32    pub san_names: Vec<String>,
33    /// Whether the certificate chain is currently valid
34    pub is_valid: bool,
35    /// Days until the leaf certificate expires
36    pub days_until_expiry: i64,
37}
38
39/// Detailed information about a single certificate in the chain.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct CertDetail {
42    /// Certificate subject (e.g., "CN=example.com")
43    pub subject: String,
44    /// Certificate issuer (e.g., "CN=R3, O=Let's Encrypt")
45    pub issuer: String,
46    /// Certificate validity start date
47    pub valid_from: DateTime<Utc>,
48    /// Certificate expiration date
49    pub valid_until: DateTime<Utc>,
50    /// Serial number in hexadecimal
51    pub serial_number: String,
52    /// Signature algorithm (e.g., "sha256WithRSAEncryption")
53    pub signature_algorithm: Option<String>,
54    /// Whether this is a Certificate Authority certificate
55    pub is_ca: bool,
56    /// Public key type (e.g., "RSA", "EC")
57    pub key_type: Option<String>,
58    /// Public key size in bits
59    pub key_bits: Option<u32>,
60}
61
62/// Client for performing SSL certificate chain inspection.
63pub struct SslChecker;
64
65impl Default for SslChecker {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl SslChecker {
72    /// Creates a new SslChecker instance.
73    pub fn new() -> Self {
74        Self
75    }
76
77    /// Inspects the SSL certificate chain for the given domain.
78    ///
79    /// Connects to port 443, performs a TLS handshake, and extracts detailed
80    /// certificate information including the full chain, SANs, and key details.
81    ///
82    /// # Arguments
83    /// * `domain` - The domain name to inspect (e.g., "example.com")
84    ///
85    /// # Returns
86    /// * `Ok(SslReport)` - Detailed SSL certificate information
87    /// * `Err(SeerError)` - If connection or certificate parsing fails
88    #[instrument(skip(self), fields(domain = %domain))]
89    pub async fn check(&self, domain: &str) -> Result<SslReport> {
90        let domain = normalize_domain(domain)?;
91        let addr = format!("{}:443", domain);
92
93        debug!(domain = %domain, "Checking SSL certificate chain");
94
95        // SSRF protection: resolve domain and check IPs before connecting
96        let socket_addrs: Vec<_> = tokio::net::lookup_host(&addr)
97            .await
98            .map_err(|e| SeerError::SslError(format!("DNS lookup failed: {}", e)))?
99            .collect();
100
101        if socket_addrs.is_empty() {
102            return Err(SeerError::SslError(format!(
103                "Domain {} did not resolve to any addresses",
104                domain
105            )));
106        }
107
108        for socket_addr in &socket_addrs {
109            if let Some(reason) = describe_reserved_ip(&socket_addr.ip()) {
110                return Err(SeerError::SslError(format!(
111                    "cannot connect to {}: {} — {}",
112                    domain,
113                    socket_addr.ip(),
114                    reason
115                )));
116            }
117        }
118
119        // Build TLS connector - accept invalid certs so we can inspect them
120        let connector = native_tls::TlsConnector::builder()
121            .danger_accept_invalid_certs(true)
122            .build()
123            .map_err(|e| SeerError::SslError(format!("Failed to create TLS connector: {}", e)))?;
124        let connector = TlsConnector::from(connector);
125
126        // TCP connect with timeout — connect to pre-resolved address to prevent DNS rebinding
127        let stream =
128            tokio::time::timeout(DEFAULT_TIMEOUT, TcpStream::connect(socket_addrs.as_slice()))
129                .await
130                .map_err(|_| SeerError::Timeout("SSL connection timed out".to_string()))?
131                .map_err(|e| {
132                    SeerError::SslError(format!("Failed to connect to {}: {}", addr, e))
133                })?;
134
135        // TLS handshake with timeout
136        let tls_stream = tokio::time::timeout(DEFAULT_TIMEOUT, connector.connect(&domain, stream))
137            .await
138            .map_err(|_| SeerError::Timeout("TLS handshake timed out".to_string()))?
139            .map_err(|e| SeerError::SslError(format!("TLS handshake failed: {}", e)))?;
140
141        // Get the peer certificate (leaf)
142        let cert = tls_stream
143            .get_ref()
144            .peer_certificate()
145            .map_err(|e| SeerError::SslError(format!("Failed to get certificate: {}", e)))?
146            .ok_or_else(|| SeerError::SslError("No certificate presented".to_string()))?;
147
148        let der = cert
149            .to_der()
150            .map_err(|e| SeerError::SslError(format!("Failed to encode certificate: {}", e)))?;
151
152        // Parse leaf certificate with x509-parser
153        let (_, x509) = X509Certificate::from_der(&der)
154            .map_err(|e| SeerError::SslError(format!("Failed to parse certificate: {}", e)))?;
155
156        // Extract SANs from the leaf certificate
157        let san_names = extract_sans(&x509);
158
159        // Build the certificate chain
160        // native-tls only exposes the leaf cert directly; we parse what we have
161        let leaf_detail = parse_cert_detail(&x509)?;
162
163        let now = Utc::now();
164        let days_until_expiry = (leaf_detail.valid_until - now).num_days();
165        let is_valid = now >= leaf_detail.valid_from && now <= leaf_detail.valid_until;
166
167        Ok(SslReport {
168            domain,
169            chain: vec![leaf_detail],
170            protocol_version: None,
171            san_names,
172            is_valid,
173            days_until_expiry,
174        })
175    }
176}
177
178/// Extracts Subject Alternative Names from a certificate.
179fn extract_sans(cert: &X509Certificate) -> Vec<String> {
180    let mut sans = Vec::new();
181    if let Ok(Some(ext)) = cert.subject_alternative_name() {
182        for name in &ext.value.general_names {
183            match name {
184                GeneralName::DNSName(dns) => {
185                    sans.push(dns.to_string());
186                }
187                GeneralName::IPAddress(ip_bytes) => {
188                    // IP addresses are encoded as bytes
189                    let ip_str = match ip_bytes.len() {
190                        4 => format!(
191                            "{}.{}.{}.{}",
192                            ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]
193                        ),
194                        16 => {
195                            // IPv6
196                            let mut parts = Vec::new();
197                            for chunk in ip_bytes.chunks(2) {
198                                parts.push(format!("{:02x}{:02x}", chunk[0], chunk[1]));
199                            }
200                            parts.join(":")
201                        }
202                        _ => format!("{:?}", ip_bytes),
203                    };
204                    sans.push(ip_str);
205                }
206                _ => {}
207            }
208        }
209    }
210    sans
211}
212
213/// Parses detailed information from an X.509 certificate.
214fn parse_cert_detail(cert: &X509Certificate) -> Result<CertDetail> {
215    let subject = cert.subject().to_string();
216    let issuer = cert.issuer().to_string();
217
218    let valid_from = asn1_time_to_chrono(cert.validity().not_before)?;
219    let valid_until = asn1_time_to_chrono(cert.validity().not_after)?;
220
221    let serial_number = cert.serial.to_str_radix(16);
222
223    let signature_algorithm = oid_to_name(&cert.signature_algorithm.algorithm);
224
225    let is_ca = cert.is_ca();
226
227    // Extract public key info
228    let spki = cert.public_key();
229    let (key_type, key_bits) = extract_key_info(spki);
230
231    Ok(CertDetail {
232        subject,
233        issuer,
234        valid_from,
235        valid_until,
236        serial_number,
237        signature_algorithm,
238        is_ca,
239        key_type,
240        key_bits,
241    })
242}
243
244/// Extracts key type and size from a SubjectPublicKeyInfo.
245fn extract_key_info(spki: &SubjectPublicKeyInfo) -> (Option<String>, Option<u32>) {
246    use x509_parser::public_key::PublicKey;
247    let oid = &spki.algorithm.algorithm;
248    let key_type = oid_to_key_type(oid);
249    let key_bits = match spki.parsed() {
250        Ok(PublicKey::RSA(rsa)) => Some(rsa.key_size() as u32),
251        Ok(PublicKey::EC(ec)) => Some(ec.key_size() as u32),
252        _ => None,
253    };
254    (key_type, key_bits)
255}
256
257/// Maps common OIDs to human-readable algorithm names.
258fn oid_to_name(oid: &Oid) -> Option<String> {
259    let oid_str = format!("{}", oid);
260    match oid_str.as_str() {
261        "1.2.840.113549.1.1.11" => Some("SHA-256 with RSA".to_string()),
262        "1.2.840.113549.1.1.12" => Some("SHA-384 with RSA".to_string()),
263        "1.2.840.113549.1.1.13" => Some("SHA-512 with RSA".to_string()),
264        "1.2.840.113549.1.1.5" => Some("SHA-1 with RSA".to_string()),
265        "1.2.840.113549.1.1.14" => Some("SHA-224 with RSA".to_string()),
266        "1.2.840.10045.4.3.2" => Some("ECDSA with SHA-256".to_string()),
267        "1.2.840.10045.4.3.3" => Some("ECDSA with SHA-384".to_string()),
268        "1.2.840.10045.4.3.4" => Some("ECDSA with SHA-512".to_string()),
269        "1.3.101.112" => Some("Ed25519".to_string()),
270        "1.3.101.113" => Some("Ed448".to_string()),
271        _ => Some(oid_str),
272    }
273}
274
275/// Maps public key algorithm OIDs to human-readable key type names.
276fn oid_to_key_type(oid: &Oid) -> Option<String> {
277    let oid_str = format!("{}", oid);
278    match oid_str.as_str() {
279        "1.2.840.113549.1.1.1" => Some("RSA".to_string()),
280        "1.2.840.10045.2.1" => Some("EC".to_string()),
281        "1.3.101.112" => Some("Ed25519".to_string()),
282        "1.3.101.113" => Some("Ed448".to_string()),
283        _ => Some(oid_str),
284    }
285}
286
287/// Converts an x509-parser ASN1Time to a chrono DateTime.
288fn asn1_time_to_chrono(time: ASN1Time) -> Result<DateTime<Utc>> {
289    let timestamp = time.timestamp();
290    DateTime::from_timestamp(timestamp, 0)
291        .ok_or_else(|| SeerError::SslError("invalid certificate timestamp".to_string()))
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn test_ssl_checker_creation() {
300        let checker = SslChecker::new();
301        let _default_checker = SslChecker::default();
302        // Just verify construction works
303        drop(checker);
304    }
305
306    #[test]
307    fn test_oid_to_name() {
308        let oid = Oid::from(&[1, 2, 840, 113549, 1, 1, 11][..]).unwrap();
309        assert_eq!(oid_to_name(&oid), Some("SHA-256 with RSA".to_string()));
310    }
311
312    #[test]
313    fn test_oid_to_key_type() {
314        let oid = Oid::from(&[1, 2, 840, 113549, 1, 1, 1][..]).unwrap();
315        assert_eq!(oid_to_key_type(&oid), Some("RSA".to_string()));
316    }
317
318    #[test]
319    fn test_ssl_report_serialization() {
320        let report = SslReport {
321            domain: "example.com".to_string(),
322            chain: vec![CertDetail {
323                subject: "CN=example.com".to_string(),
324                issuer: "CN=R3, O=Let's Encrypt".to_string(),
325                valid_from: Utc::now(),
326                valid_until: Utc::now(),
327                serial_number: "abc123".to_string(),
328                signature_algorithm: Some("SHA-256 with RSA".to_string()),
329                is_ca: false,
330                key_type: Some("RSA".to_string()),
331                key_bits: Some(2048),
332            }],
333            protocol_version: None,
334            san_names: vec!["example.com".to_string(), "*.example.com".to_string()],
335            is_valid: true,
336            days_until_expiry: 90,
337        };
338        let json = serde_json::to_string(&report).unwrap();
339        assert!(json.contains("example.com"));
340        assert!(json.contains("SHA-256 with RSA"));
341        assert!(json.contains("\"is_valid\":true"));
342    }
343}