1use 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
19const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct SslReport {
25 pub domain: String,
27 pub chain: Vec<CertDetail>,
29 pub protocol_version: Option<String>,
31 pub san_names: Vec<String>,
33 pub is_valid: bool,
35 pub days_until_expiry: i64,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct CertDetail {
42 pub subject: String,
44 pub issuer: String,
46 pub valid_from: DateTime<Utc>,
48 pub valid_until: DateTime<Utc>,
50 pub serial_number: String,
52 pub signature_algorithm: Option<String>,
54 pub is_ca: bool,
56 pub key_type: Option<String>,
58 pub key_bits: Option<u32>,
60}
61
62pub struct SslChecker;
64
65impl Default for SslChecker {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71impl SslChecker {
72 pub fn new() -> Self {
74 Self
75 }
76
77 #[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 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 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 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 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 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 let (_, x509) = X509Certificate::from_der(&der)
154 .map_err(|e| SeerError::SslError(format!("Failed to parse certificate: {}", e)))?;
155
156 let san_names = extract_sans(&x509);
158
159 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
178fn 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 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 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
213fn 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 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
244fn 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
257fn 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
275fn 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
287fn 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 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}