use super::tls_common::{self, TlsParseOptions};
use crate::network::types::{HttpsInfo, TlsInfo};
use log::debug;
pub(super) fn is_tls_handshake(payload: &[u8]) -> bool {
if payload.len() < 5 {
return false;
}
payload[0] == 0x16 && payload[1] == 0x03 && (payload[2] >= 0x01 && payload[2] <= 0x04) }
pub(super) fn analyze_https(payload: &[u8]) -> Option<HttpsInfo> {
if payload.len() < 5 {
return None;
}
let mut info = TlsInfo::new();
info.version = tls_common::version_from_bytes(payload[1], payload[2]);
if payload[0] != 0x16 {
return Some(HttpsInfo {
tls_info: Some(info),
});
}
let record_length = u16::from_be_bytes([payload[3], payload[4]]) as usize;
if record_length > 16384 + 2048 {
return Some(HttpsInfo {
tls_info: Some(info),
});
}
let available_data = (payload.len() - 5).min(record_length);
tls_common::parse_handshake(
&payload[5..5 + available_data],
&mut info,
TlsParseOptions::tcp(),
);
if info.sni.is_some() || !info.alpn.is_empty() {
debug!("TLS: Found SNI={:?}, ALPN={:?}", info.sni, info.alpn);
}
Some(HttpsInfo {
tls_info: Some(info),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::network::dpi::tls_common::test_fixtures::{
RFC9001_CLIENT_HELLO, build_server_hello, from_hex,
};
use crate::network::types::TlsVersion;
fn rfc9001_client_hello() -> Vec<u8> {
from_hex(RFC9001_CLIENT_HELLO)
}
fn tls_record(handshake: &[u8]) -> Vec<u8> {
let mut record = vec![0x16, 0x03, 0x01];
record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
record.extend_from_slice(handshake);
record
}
#[test]
fn test_analyze_https_client_hello_end_to_end() {
let payload = tls_record(&rfc9001_client_hello());
assert!(is_tls_handshake(&payload));
let info = analyze_https(&payload).unwrap().tls_info.unwrap();
assert_eq!(info.sni, Some("example.com".to_string()));
assert_eq!(info.alpn, vec!["alpn".to_string()]);
assert_eq!(info.version, Some(TlsVersion::Tls13));
}
#[test]
fn test_analyze_https_server_hello_end_to_end() {
let handshake = build_server_hello(&from_hex("002b00020304"));
let info = analyze_https(&tls_record(&handshake))
.unwrap()
.tls_info
.unwrap();
assert_eq!(info.cipher_suite, Some(0x1301));
assert_eq!(info.version, Some(TlsVersion::Tls13));
}
#[test]
fn test_analyze_https_truncated_client_hello() {
let handshake = rfc9001_client_hello();
let sni_pos = handshake
.windows(11)
.position(|w| w == b"example.com")
.unwrap();
let truncated = &handshake[..sni_pos + 6];
let info = analyze_https(&tls_record(truncated))
.unwrap()
.tls_info
.unwrap();
let sni = info.sni.expect("partial SNI should be extracted");
assert!(sni.starts_with("exampl"));
assert!(sni.contains("PARTIAL"));
}
#[test]
fn test_analyze_https_non_handshake_record() {
let payload = [0x17, 0x03, 0x03, 0x00, 0x05, 1, 2, 3, 4, 5];
let info = analyze_https(&payload).unwrap().tls_info.unwrap();
assert_eq!(info.version, Some(TlsVersion::Tls12));
assert_eq!(info.sni, None);
assert!(info.alpn.is_empty());
}
}