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| {
99                SeerError::SslError(format!(
100                    "could not resolve {} to an IP address for SSL inspection \
101                     (no A or AAAA record?): {}",
102                    domain, e
103                ))
104            })?
105            .collect();
106
107        if socket_addrs.is_empty() {
108            return Err(SeerError::SslError(format!(
109                "{} has no A or AAAA records — nothing to connect to for SSL inspection",
110                domain
111            )));
112        }
113
114        for socket_addr in &socket_addrs {
115            if let Some(reason) = describe_reserved_ip(&socket_addr.ip()) {
116                return Err(SeerError::SslError(format!(
117                    "cannot connect to {}: {} — {}",
118                    domain,
119                    socket_addr.ip(),
120                    reason
121                )));
122            }
123        }
124
125        // Build TLS connector - accept invalid certs so we can inspect them
126        let connector = native_tls::TlsConnector::builder()
127            .danger_accept_invalid_certs(true)
128            .build()
129            .map_err(|e| SeerError::SslError(format!("Failed to create TLS connector: {}", e)))?;
130        let connector = TlsConnector::from(connector);
131
132        // TCP connect with timeout — connect to pre-resolved address to prevent DNS rebinding
133        let stream =
134            tokio::time::timeout(DEFAULT_TIMEOUT, TcpStream::connect(socket_addrs.as_slice()))
135                .await
136                .map_err(|_| SeerError::Timeout("SSL connection timed out".to_string()))?
137                .map_err(|e| {
138                    SeerError::SslError(format!("Failed to connect to {}: {}", addr, e))
139                })?;
140
141        // TLS handshake with timeout
142        let tls_stream = tokio::time::timeout(DEFAULT_TIMEOUT, connector.connect(&domain, stream))
143            .await
144            .map_err(|_| SeerError::Timeout("TLS handshake timed out".to_string()))?
145            .map_err(|e| SeerError::SslError(format!("TLS handshake failed: {}", e)))?;
146
147        // Get the peer certificate (leaf)
148        let cert = tls_stream
149            .get_ref()
150            .peer_certificate()
151            .map_err(|e| SeerError::SslError(format!("Failed to get certificate: {}", e)))?
152            .ok_or_else(|| SeerError::SslError("No certificate presented".to_string()))?;
153
154        let der = cert
155            .to_der()
156            .map_err(|e| SeerError::SslError(format!("Failed to encode certificate: {}", e)))?;
157
158        // Parse leaf certificate with x509-parser
159        let (_, x509) = X509Certificate::from_der(&der)
160            .map_err(|e| SeerError::SslError(format!("Failed to parse certificate: {}", e)))?;
161
162        // Extract SANs from the leaf certificate
163        let san_names = extract_sans(&x509);
164
165        // Build the certificate chain
166        // native-tls only exposes the leaf cert directly; we parse what we have
167        let leaf_detail = parse_cert_detail(&x509)?;
168
169        let now = Utc::now();
170        let days_until_expiry = (leaf_detail.valid_until - now).num_days();
171        let is_valid = now >= leaf_detail.valid_from && now <= leaf_detail.valid_until;
172
173        Ok(SslReport {
174            domain,
175            chain: vec![leaf_detail],
176            protocol_version: None,
177            san_names,
178            is_valid,
179            days_until_expiry,
180        })
181    }
182}
183
184/// Extracts Subject Alternative Names from a certificate.
185fn extract_sans(cert: &X509Certificate) -> Vec<String> {
186    let mut sans = Vec::new();
187    if let Ok(Some(ext)) = cert.subject_alternative_name() {
188        for name in &ext.value.general_names {
189            match name {
190                GeneralName::DNSName(dns) => {
191                    sans.push(dns.to_string());
192                }
193                GeneralName::IPAddress(ip_bytes) => {
194                    // IP addresses are encoded as bytes
195                    let ip_str = match ip_bytes.len() {
196                        4 => format!(
197                            "{}.{}.{}.{}",
198                            ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]
199                        ),
200                        16 => {
201                            // IPv6
202                            let mut parts = Vec::new();
203                            for chunk in ip_bytes.chunks(2) {
204                                parts.push(format!("{:02x}{:02x}", chunk[0], chunk[1]));
205                            }
206                            parts.join(":")
207                        }
208                        _ => format!("{:?}", ip_bytes),
209                    };
210                    sans.push(ip_str);
211                }
212                _ => {}
213            }
214        }
215    }
216    sans
217}
218
219/// Parses detailed information from an X.509 certificate.
220fn parse_cert_detail(cert: &X509Certificate) -> Result<CertDetail> {
221    let subject = cert.subject().to_string();
222    let issuer = cert.issuer().to_string();
223
224    let valid_from = asn1_time_to_chrono(cert.validity().not_before)?;
225    let valid_until = asn1_time_to_chrono(cert.validity().not_after)?;
226
227    let serial_number = cert.serial.to_str_radix(16);
228
229    let signature_algorithm = oid_to_name(&cert.signature_algorithm.algorithm);
230
231    let is_ca = cert.is_ca();
232
233    // Extract public key info
234    let spki = cert.public_key();
235    let (key_type, key_bits) = extract_key_info(spki);
236
237    Ok(CertDetail {
238        subject,
239        issuer,
240        valid_from,
241        valid_until,
242        serial_number,
243        signature_algorithm,
244        is_ca,
245        key_type,
246        key_bits,
247    })
248}
249
250/// Extracts key type and size from a SubjectPublicKeyInfo.
251fn extract_key_info(spki: &SubjectPublicKeyInfo) -> (Option<String>, Option<u32>) {
252    use x509_parser::public_key::PublicKey;
253    let oid = &spki.algorithm.algorithm;
254    let key_type = oid_to_key_type(oid);
255    let key_bits = match spki.parsed() {
256        Ok(PublicKey::RSA(rsa)) => Some(rsa.key_size() as u32),
257        Ok(PublicKey::EC(ec)) => Some(ec.key_size() as u32),
258        _ => None,
259    };
260    (key_type, key_bits)
261}
262
263/// Maps common OIDs to human-readable algorithm names.
264fn oid_to_name(oid: &Oid) -> Option<String> {
265    let oid_str = format!("{}", oid);
266    match oid_str.as_str() {
267        "1.2.840.113549.1.1.11" => Some("SHA-256 with RSA".to_string()),
268        "1.2.840.113549.1.1.12" => Some("SHA-384 with RSA".to_string()),
269        "1.2.840.113549.1.1.13" => Some("SHA-512 with RSA".to_string()),
270        "1.2.840.113549.1.1.5" => Some("SHA-1 with RSA".to_string()),
271        "1.2.840.113549.1.1.14" => Some("SHA-224 with RSA".to_string()),
272        "1.2.840.10045.4.3.2" => Some("ECDSA with SHA-256".to_string()),
273        "1.2.840.10045.4.3.3" => Some("ECDSA with SHA-384".to_string()),
274        "1.2.840.10045.4.3.4" => Some("ECDSA with SHA-512".to_string()),
275        "1.3.101.112" => Some("Ed25519".to_string()),
276        "1.3.101.113" => Some("Ed448".to_string()),
277        _ => Some(oid_str),
278    }
279}
280
281/// Maps public key algorithm OIDs to human-readable key type names.
282fn oid_to_key_type(oid: &Oid) -> Option<String> {
283    let oid_str = format!("{}", oid);
284    match oid_str.as_str() {
285        "1.2.840.113549.1.1.1" => Some("RSA".to_string()),
286        "1.2.840.10045.2.1" => Some("EC".to_string()),
287        "1.3.101.112" => Some("Ed25519".to_string()),
288        "1.3.101.113" => Some("Ed448".to_string()),
289        _ => Some(oid_str),
290    }
291}
292
293/// Converts an x509-parser ASN1Time to a chrono DateTime.
294fn asn1_time_to_chrono(time: ASN1Time) -> Result<DateTime<Utc>> {
295    let timestamp = time.timestamp();
296    DateTime::from_timestamp(timestamp, 0)
297        .ok_or_else(|| SeerError::SslError("invalid certificate timestamp".to_string()))
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn test_ssl_checker_creation() {
306        let checker = SslChecker::new();
307        let _default_checker = SslChecker::default();
308        // Just verify construction works
309        drop(checker);
310    }
311
312    #[test]
313    fn test_oid_to_name() {
314        let oid = Oid::from(&[1, 2, 840, 113549, 1, 1, 11][..]).unwrap();
315        assert_eq!(oid_to_name(&oid), Some("SHA-256 with RSA".to_string()));
316    }
317
318    #[test]
319    fn test_oid_to_key_type() {
320        let oid = Oid::from(&[1, 2, 840, 113549, 1, 1, 1][..]).unwrap();
321        assert_eq!(oid_to_key_type(&oid), Some("RSA".to_string()));
322    }
323
324    #[test]
325    fn test_ssl_report_serialization() {
326        let report = SslReport {
327            domain: "example.com".to_string(),
328            chain: vec![CertDetail {
329                subject: "CN=example.com".to_string(),
330                issuer: "CN=R3, O=Let's Encrypt".to_string(),
331                valid_from: Utc::now(),
332                valid_until: Utc::now(),
333                serial_number: "abc123".to_string(),
334                signature_algorithm: Some("SHA-256 with RSA".to_string()),
335                is_ca: false,
336                key_type: Some("RSA".to_string()),
337                key_bits: Some(2048),
338            }],
339            protocol_version: None,
340            san_names: vec!["example.com".to_string(), "*.example.com".to_string()],
341            is_valid: true,
342            days_until_expiry: 90,
343        };
344        let json = serde_json::to_string(&report).unwrap();
345        assert!(json.contains("example.com"));
346        assert!(json.contains("SHA-256 with RSA"));
347        assert!(json.contains("\"is_valid\":true"));
348    }
349}