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| {
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 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 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 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 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 let (_, x509) = X509Certificate::from_der(&der)
160 .map_err(|e| SeerError::SslError(format!("Failed to parse certificate: {}", e)))?;
161
162 let san_names = extract_sans(&x509);
164
165 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
184fn 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 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 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
219fn 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 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
250fn 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
263fn 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
281fn 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
293fn 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 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}