use crate::monitor::extract_http_request;
use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa, KeyPair, SanType};
use ring::aead::{
AES_128_GCM, AES_256_GCM, Aad, CHACHA20_POLY1305, LessSafeKey, Nonce, UnboundKey,
};
use ring::hmac;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{
ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,
ServerConnection, SignatureScheme,
};
use std::collections::HashMap;
use std::fs::File;
use std::io::{Cursor, Read, Write};
use std::net::IpAddr;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use wasmtime::{Result, SharedMemory, format_err};
const MAX_PREVIEW_BYTES: usize = 2048;
pub fn summarize_tls_plaintext(data: &[u8]) -> (Option<String>, String) {
let http_summary = if let Some((method, path, host)) = extract_http_request(data) {
Some(match host {
Some(h) => format!("{method} {path} (Host: {h})"),
None => format!("{method} {path}"),
})
} else if data.starts_with(b"HTTP/1.") || data.starts_with(b"HTTP/2") {
let end = data
.iter()
.position(|&b| b == b'\r' || b == b'\n')
.unwrap_or(data.len().min(120));
std::str::from_utf8(&data[..end])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
} else {
None
};
let take = data.len().min(MAX_PREVIEW_BYTES);
let preview = String::from_utf8_lossy(&data[..take]).into_owned();
(http_summary, preview)
}
pub fn looks_like_tls_client_hello(data: &[u8]) -> bool {
data.len() >= 6 && data[0] == 0x16 && data[1] == 0x03 && data[5] == 0x01
}
pub fn extract_client_random(data: &[u8]) -> Option<[u8; 32]> {
if data.len() < 43 || data[0] != 0x16 || data[1] != 0x03 || data[5] != 0x01 {
return None;
}
let mut rnd = [0u8; 32];
rnd.copy_from_slice(&data[11..43]);
Some(rnd)
}
#[derive(Debug, Clone, Copy)]
pub struct ServerHelloInfo {
pub server_random: [u8; 32],
pub cipher_suite: u16,
pub is_tls13: bool,
}
pub fn parse_server_hello_handshake(hs: &[u8]) -> Option<ServerHelloInfo> {
if hs.len() < 40 || hs[0] != 0x02 {
return None;
}
let msg_len = ((hs[1] as usize) << 16) | ((hs[2] as usize) << 8) | (hs[3] as usize);
let end = (4 + msg_len).min(hs.len());
if end < 40 {
return None;
}
let mut server_random = [0u8; 32];
server_random.copy_from_slice(&hs[6..38]);
let mut p = 38;
if p >= end {
return None;
}
let sid_len = hs[p] as usize;
p += 1 + sid_len;
if p + 3 > end {
return None;
}
let cipher_suite = u16::from_be_bytes([hs[p], hs[p + 1]]);
p += 3;
let mut is_tls13 = matches!(cipher_suite, 0x1301..=0x1305);
if p + 2 <= end {
let ext_len = u16::from_be_bytes([hs[p], hs[p + 1]]) as usize;
p += 2;
let ext_end = (p + ext_len).min(end);
while p + 4 <= ext_end {
let etype = u16::from_be_bytes([hs[p], hs[p + 1]]);
let elen = u16::from_be_bytes([hs[p + 2], hs[p + 3]]) as usize;
p += 4;
if p + elen > ext_end {
break;
}
if etype == 0x002b && elen == 2 && hs[p] == 0x03 && hs[p + 1] == 0x04 {
is_tls13 = true;
}
p += elen;
}
}
Some(ServerHelloInfo {
server_random,
cipher_suite,
is_tls13,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CipherKind {
Aes128GcmSha256,
Aes256GcmSha384,
ChaCha20Poly1305Sha256,
}
impl CipherKind {
fn from_suite(suite: u16) -> Option<Self> {
match suite {
0x1301 | 0xc02f | 0xc02b | 0x009c => Some(Self::Aes128GcmSha256),
0x1302 | 0xc030 | 0xc02c | 0x009d => Some(Self::Aes256GcmSha384),
0x1303 | 0xcca8 | 0xcca9 => Some(Self::ChaCha20Poly1305Sha256),
_ => None,
}
}
fn key_len(self) -> usize {
match self {
Self::Aes128GcmSha256 => 16,
Self::Aes256GcmSha384 | Self::ChaCha20Poly1305Sha256 => 32,
}
}
fn hash_len(self) -> usize {
match self {
Self::Aes128GcmSha256 | Self::ChaCha20Poly1305Sha256 => 32,
Self::Aes256GcmSha384 => 48,
}
}
fn hmac_alg(self) -> hmac::Algorithm {
match self {
Self::Aes128GcmSha256 | Self::ChaCha20Poly1305Sha256 => hmac::HMAC_SHA256,
Self::Aes256GcmSha384 => hmac::HMAC_SHA384,
}
}
fn aead_alg(self) -> &'static ring::aead::Algorithm {
match self {
Self::Aes128GcmSha256 => &AES_128_GCM,
Self::Aes256GcmSha384 => &AES_256_GCM,
Self::ChaCha20Poly1305Sha256 => &CHACHA20_POLY1305,
}
}
}
fn tls13_hkdf_expand_label(
cipher: CipherKind,
secret: &[u8],
label: &[u8],
out_len: usize,
) -> Vec<u8> {
let full_label_len = 6 + label.len();
let mut info = Vec::with_capacity(2 + 1 + full_label_len + 1 + 1);
info.extend_from_slice(&(out_len as u16).to_be_bytes());
info.push(full_label_len as u8);
info.extend_from_slice(b"tls13 ");
info.extend_from_slice(label);
info.push(0); info.push(1); let key = hmac::Key::new(cipher.hmac_alg(), secret);
let tag = hmac::sign(&key, &info);
tag.as_ref()[..out_len].to_vec()
}
fn tls12_prf(
cipher: CipherKind,
secret: &[u8],
label: &[u8],
seed: &[u8],
out_len: usize,
) -> Vec<u8> {
let key = hmac::Key::new(cipher.hmac_alg(), secret);
let mut label_seed = Vec::with_capacity(label.len() + seed.len());
label_seed.extend_from_slice(label);
label_seed.extend_from_slice(seed);
let mut out = Vec::with_capacity(out_len);
let mut a = hmac::sign(&key, &label_seed).as_ref().to_vec();
while out.len() < out_len {
let mut ctx = hmac::Context::with_key(&key);
ctx.update(&a);
ctx.update(&label_seed);
let block = ctx.sign();
let need = (out_len - out.len()).min(block.as_ref().len());
out.extend_from_slice(&block.as_ref()[..need]);
a = hmac::sign(&key, &a).as_ref().to_vec();
}
out
}
fn xor_iv_seq(iv: &[u8; 12], seq: u64) -> [u8; 12] {
let mut nonce = *iv;
let sb = seq.to_be_bytes();
for i in 0..8 {
nonce[4 + i] ^= sb[i];
}
nonce
}
#[derive(Clone)]
struct TrafficKey {
cipher: CipherKind,
is_tls13: bool,
key_bytes: Vec<u8>,
iv: [u8; 12],
seq: u64,
}
impl TrafficKey {
fn from_tls13_secret(cipher: CipherKind, secret: &[u8]) -> Self {
let key_bytes = tls13_hkdf_expand_label(cipher, secret, b"key", cipher.key_len());
let iv_vec = tls13_hkdf_expand_label(cipher, secret, b"iv", 12);
let mut iv = [0u8; 12];
iv.copy_from_slice(&iv_vec[..12]);
Self {
cipher,
is_tls13: true,
key_bytes,
iv,
seq: 0,
}
}
fn from_tls12_master(
cipher: CipherKind,
master_secret: &[u8],
client_random: &[u8; 32],
server_random: &[u8; 32],
) -> (Self, Self) {
let key_len = cipher.key_len();
let iv_len = if cipher == CipherKind::ChaCha20Poly1305Sha256 {
12
} else {
4
};
let mut seed = [0u8; 64];
seed[..32].copy_from_slice(server_random);
seed[32..].copy_from_slice(client_random);
let block = tls12_prf(
cipher,
master_secret,
b"key expansion",
&seed,
2 * key_len + 2 * iv_len,
);
let c_key = block[0..key_len].to_vec();
let s_key = block[key_len..2 * key_len].to_vec();
let mut c_iv = [0u8; 12];
let mut s_iv = [0u8; 12];
c_iv[..iv_len].copy_from_slice(&block[2 * key_len..2 * key_len + iv_len]);
s_iv[..iv_len].copy_from_slice(&block[2 * key_len + iv_len..2 * key_len + 2 * iv_len]);
(
Self {
cipher,
is_tls13: false,
key_bytes: c_key,
iv: c_iv,
seq: 0,
},
Self {
cipher,
is_tls13: false,
key_bytes: s_key,
iv: s_iv,
seq: 0,
},
)
}
fn decrypt_record_at(
&self,
header: &[u8; 5],
payload: &[u8],
seq: u64,
) -> Option<(u8, Vec<u8>)> {
let unbound = UnboundKey::new(self.cipher.aead_alg(), &self.key_bytes).ok()?;
let aead_key = LessSafeKey::new(unbound);
if self.is_tls13 {
if payload.len() < 17 {
return None;
}
let nonce_bytes = xor_iv_seq(&self.iv, seq);
let mut buf = payload.to_vec();
let plain = aead_key
.open_in_place(
Nonce::assume_unique_for_key(nonce_bytes),
Aad::from(&header[..]),
&mut buf,
)
.ok()?;
let mut end = plain.len();
while end > 0 && plain[end - 1] == 0 {
end -= 1;
}
if end == 0 {
return None;
}
let inner_type = plain[end - 1];
Some((inner_type, plain[..end - 1].to_vec()))
} else if self.cipher == CipherKind::ChaCha20Poly1305Sha256 {
if payload.len() < 16 {
return None;
}
let plain_len = (payload.len() - 16) as u16;
let mut aad = [0u8; 13];
aad[0..8].copy_from_slice(&seq.to_be_bytes());
aad[8] = header[0];
aad[9] = header[1];
aad[10] = header[2];
aad[11..13].copy_from_slice(&plain_len.to_be_bytes());
let nonce_bytes = xor_iv_seq(&self.iv, seq);
let mut buf = payload.to_vec();
let plain = aead_key
.open_in_place(
Nonce::assume_unique_for_key(nonce_bytes),
Aad::from(&aad[..]),
&mut buf,
)
.ok()?;
Some((header[0], plain.to_vec()))
} else {
if payload.len() < 24 {
return None;
}
let plain_len = (payload.len() - 24) as u16;
let mut aad = [0u8; 13];
aad[0..8].copy_from_slice(&seq.to_be_bytes());
aad[8] = header[0];
aad[9] = header[1];
aad[10] = header[2];
aad[11..13].copy_from_slice(&plain_len.to_be_bytes());
let mut nonce_bytes = [0u8; 12];
nonce_bytes[0..4].copy_from_slice(&self.iv[0..4]);
nonce_bytes[4..12].copy_from_slice(&payload[0..8]);
let mut buf = payload[8..].to_vec();
let plain = aead_key
.open_in_place(
Nonce::assume_unique_for_key(nonce_bytes),
Aad::from(&aad[..]),
&mut buf,
)
.ok()?;
Some((header[0], plain.to_vec()))
}
}
fn decrypt_next(&mut self, header: &[u8; 5], payload: &[u8]) -> Option<(u8, Vec<u8>)> {
let res = self.decrypt_record_at(header, payload, self.seq)?;
self.seq = self.seq.wrapping_add(1);
Some(res)
}
}
#[derive(Default)]
struct TlsRecordFramer {
buf: Vec<u8>,
}
impl TlsRecordFramer {
fn push(&mut self, data: &[u8]) -> Vec<([u8; 5], Vec<u8>)> {
self.buf.extend_from_slice(data);
let mut records = Vec::new();
while self.buf.len() >= 5 {
let ct = self.buf[0];
if !matches!(ct, 0x14..=0x17) || self.buf[1] != 0x03 {
self.buf.clear();
break;
}
let len = u16::from_be_bytes([self.buf[3], self.buf[4]]) as usize;
if len > 18_432 {
self.buf.clear();
break;
}
if self.buf.len() < 5 + len {
break;
}
let mut hdr = [0u8; 5];
hdr.copy_from_slice(&self.buf[0..5]);
let payload = self.buf[5..5 + len].to_vec();
self.buf.drain(..5 + len);
records.push((hdr, payload));
}
records
}
}
pub struct VmiTlsContext {
memory: SharedMemory,
memory_bytes: usize,
keylog_file: Option<Arc<Mutex<File>>>,
}
impl VmiTlsContext {
pub fn new(
memory: SharedMemory,
memory_bytes: usize,
keylog_file: Option<Arc<Mutex<File>>>,
) -> Arc<Self> {
Arc::new(Self {
memory,
memory_bytes,
keylog_file,
})
}
fn snapshot_memory(&self) -> Vec<u8> {
let data = self.memory.data();
let len = self.memory_bytes.min(data.len());
let mut out = vec![0u8; len];
for (i, b) in out.iter_mut().enumerate() {
unsafe {
*b = AtomicU8::from_ptr(data[i].get()).load(Ordering::Relaxed);
}
}
out
}
fn read_slice(&self, addr: usize, len: usize) -> Option<Vec<u8>> {
let data = self.memory.data();
let limit = self.memory_bytes.min(data.len());
if addr >= limit || len == 0 {
return None;
}
let end = addr.saturating_add(len).min(limit);
let mut out = vec![0u8; end - addr];
for (i, b) in out.iter_mut().enumerate() {
unsafe {
*b = AtomicU8::from_ptr(data[addr + i].get()).load(Ordering::Relaxed);
}
}
Some(out)
}
fn write_keylog(&self, label: &str, client_random: &[u8; 32], secret: &[u8]) {
let Some(f) = &self.keylog_file else { return };
let line = format!(
"{label} {} {}\n",
hex_lower(client_random),
hex_lower(secret)
);
if let Ok(mut guard) = f.lock() {
let _ = guard.write_all(line.as_bytes());
let _ = guard.flush();
}
}
}
fn hex_lower(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for &b in bytes {
use std::fmt::Write as _;
let _ = write!(&mut s, "{b:02x}");
}
s
}
pub fn find_32byte_matches(haystack: &[u8], needle: &[u8; 32]) -> Vec<usize> {
let mut hits = Vec::new();
if haystack.len() < 32 {
return hits;
}
let first8 = u64::from_ne_bytes(needle[0..8].try_into().unwrap());
let b0 = needle[0];
let limit = haystack.len() - 32;
let mut i = 0;
while i <= limit {
if haystack[i] == b0 {
let cand8 = u64::from_ne_bytes(haystack[i..i + 8].try_into().unwrap());
if cand8 == first8 && &haystack[i..i + 32] == needle {
hits.push(i);
i += 32;
continue;
}
}
i += 1;
}
hits
}
const AES_SBOX: [u8; 256] = [
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
];
const AES_RCON: [u32; 10] = [
0x0100_0000,
0x0200_0000,
0x0400_0000,
0x0800_0000,
0x1000_0000,
0x2000_0000,
0x4000_0000,
0x8000_0000,
0x1b00_0000,
0x3600_0000,
];
#[inline]
fn aes_sub_word(w: u32) -> u32 {
let b = w.to_be_bytes();
u32::from_be_bytes([
AES_SBOX[b[0] as usize],
AES_SBOX[b[1] as usize],
AES_SBOX[b[2] as usize],
AES_SBOX[b[3] as usize],
])
}
pub fn scan_aes_key_schedules(mem: &[u8], key_len: usize) -> Vec<(usize, Vec<u8>)> {
let mut found = Vec::new();
let sched_bytes = if key_len == 16 { 176 } else { 240 };
if mem.len() < sched_bytes {
return found;
}
let nk = key_len / 4; let total_words = sched_bytes / 4; let limit = mem.len() - sched_bytes;
for off in (0..=limit).step_by(4) {
for &le_words in &[true, false] {
let read_w = |idx: usize| -> u32 {
let p = off + idx * 4;
let bytes: [u8; 4] = mem[p..p + 4].try_into().unwrap();
if le_words {
u32::from_le_bytes(bytes)
} else {
u32::from_be_bytes(bytes)
}
};
let w0 = read_w(0);
let w1 = read_w(1);
let w_last = read_w(nk - 1);
if w0 == 0 && w1 == 0 && w_last == 0 {
continue;
}
let exp_nk = w0 ^ aes_sub_word(w_last.rotate_left(8)) ^ AES_RCON[0];
if read_w(nk) != exp_nk {
continue;
}
if read_w(nk + 1) != (w1 ^ exp_nk) {
continue;
}
let mut prev = read_w(nk + 1);
let mut ok = true;
for i in (nk + 2)..total_words {
let mut temp = prev;
if i % nk == 0 {
temp = aes_sub_word(temp.rotate_left(8)) ^ AES_RCON[(i / nk) - 1];
} else if nk == 8 && i % nk == 4 {
temp = aes_sub_word(temp);
}
let expected = read_w(i - nk) ^ temp;
let actual = read_w(i);
if actual != expected {
ok = false;
break;
}
prev = actual;
}
if ok {
let mut key = Vec::with_capacity(key_len);
for idx in 0..nk {
key.extend_from_slice(&read_w(idx).to_be_bytes());
}
found.push((off, key));
break;
}
}
}
found
}
pub struct VmiTlsInspector {
ctx: Arc<VmiTlsContext>,
tx_framer: TlsRecordFramer,
rx_framer: TlsRecordFramer,
client_random: Option<[u8; 32]>,
server_info: Option<ServerHelloInfo>,
tx_key: Option<TrafficKey>,
rx_key: Option<TrafficKey>,
client_random_addrs: Vec<usize>,
tx_secret_addr: Option<usize>,
pending_tx_app: Vec<([u8; 5], Vec<u8>)>,
pending_rx_app: Vec<([u8; 5], Vec<u8>)>,
rx_post_tx_start: Option<usize>,
tx_scan_attempts: u8,
rx_scan_attempts: u8,
}
impl VmiTlsInspector {
pub fn new(ctx: Arc<VmiTlsContext>) -> Self {
Self {
ctx,
tx_framer: TlsRecordFramer::default(),
rx_framer: TlsRecordFramer::default(),
client_random: None,
server_info: None,
tx_key: None,
rx_key: None,
client_random_addrs: Vec::new(),
tx_secret_addr: None,
pending_tx_app: Vec::new(),
pending_rx_app: Vec::new(),
rx_post_tx_start: None,
tx_scan_attempts: 0,
rx_scan_attempts: 0,
}
}
pub fn observe_tx(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
let mut decrypted = Vec::new();
for (hdr, payload) in self.tx_framer.push(data) {
match hdr[0] {
0x16 if self.client_random.is_none()
&& payload.len() >= 38
&& payload[0] == 0x01 =>
{
let mut rnd = [0u8; 32];
rnd.copy_from_slice(&payload[6..38]);
self.client_random = Some(rnd);
}
0x17 => {
if let Some(key) = &mut self.tx_key {
if let Some((ct, plain)) = key.decrypt_next(&hdr, &payload)
&& ct == 0x17
&& !plain.is_empty()
{
decrypted.push(plain);
}
} else if self.client_random.is_some()
&& let Some(sinfo) = self.server_info
&& self.pending_tx_app.len() < 8
{
self.pending_tx_app.push((hdr, payload));
let fin_len = CipherKind::from_suite(sinfo.cipher_suite)
.map(|c| 4 + c.hash_len() + 1 + 16)
.unwrap_or(53);
let only_finished = sinfo.is_tls13
&& self.pending_tx_app.len() == 1
&& self.pending_tx_app[0].1.len() == fin_len;
if !only_finished {
self.try_extract_tx_key(&mut decrypted);
if self.tx_key.is_some() && self.rx_post_tx_start.is_none() {
self.rx_post_tx_start = Some(self.pending_rx_app.len());
}
}
}
}
_ => {}
}
}
decrypted
}
pub fn observe_rx(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
let mut decrypted = Vec::new();
for (hdr, payload) in self.rx_framer.push(data) {
match hdr[0] {
0x16 if self.server_info.is_none() => {
if let Some(info) = parse_server_hello_handshake(&payload) {
self.server_info = Some(info);
}
}
0x17 => {
if let Some(key) = &mut self.rx_key {
if let Some((ct, plain)) = key.decrypt_next(&hdr, &payload)
&& ct == 0x17
&& !plain.is_empty()
{
decrypted.push(plain);
}
} else if self.client_random.is_some()
&& self.server_info.is_some()
&& self.pending_rx_app.len() < 16
{
self.pending_rx_app.push((hdr, payload));
if self.tx_key.is_some() {
self.try_extract_rx_key(&mut decrypted);
}
}
}
_ => {}
}
}
decrypted
}
fn try_extract_tx_key(&mut self, out_plain: &mut Vec<Vec<u8>>) {
if self.tx_key.is_some() || self.tx_scan_attempts >= 4 {
return;
}
let (Some(client_random), Some(sinfo)) = (self.client_random, self.server_info) else {
return;
};
let Some(cipher) = CipherKind::from_suite(sinfo.cipher_suite) else {
return;
};
self.tx_scan_attempts += 1;
let mem = self.ctx.snapshot_memory();
let hits = find_32byte_matches(&mem, &client_random);
if !hits.is_empty() {
self.client_random_addrs = hits.clone();
}
for &cr_addr in &hits {
let win_start = cr_addr.saturating_sub(4096) & !3;
let win_end = (cr_addr + 16_384).min(mem.len());
if sinfo.is_tls13 {
let sec_len = cipher.hash_len();
if win_end < win_start + sec_len {
continue;
}
for pos in (win_start..=(win_end - sec_len)).step_by(4) {
let cand = &mem[pos..pos + sec_len];
if is_trivial_slice(cand) {
continue;
}
let tk = TrafficKey::from_tls13_secret(cipher, cand);
for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, 0)
&& ct == 0x17
{
self.ctx
.write_keylog("CLIENT_TRAFFIC_SECRET_0", &client_random, cand);
self.tx_secret_addr = Some(pos);
let mut active = tk;
active.seq = 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
&& ct2 == 0x17
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.tx_key = Some(active);
self.pending_tx_app.clear();
return;
}
}
}
} else {
if win_end < win_start + 48 {
continue;
}
for pos in (win_start..=(win_end - 48)).step_by(4) {
let cand = &mem[pos..pos + 48];
if is_trivial_slice(cand) {
continue;
}
let (c_tk, s_tk) = TrafficKey::from_tls12_master(
cipher,
cand,
&client_random,
&sinfo.server_random,
);
for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
for try_seq in [1u64, 0u64, 2u64] {
if let Some((_, plain)) = c_tk.decrypt_record_at(hdr, payload, try_seq)
{
self.ctx.write_keylog("CLIENT_RANDOM", &client_random, cand);
self.tx_secret_addr = Some(pos);
let mut active_tx = c_tk;
active_tx.seq = try_seq + 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
if let Some((_, pl2)) = active_tx.decrypt_next(h2, p2)
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.tx_key = Some(active_tx);
let mut active_rx = s_tk;
active_rx.seq = 1; self.rx_key = Some(active_rx);
self.pending_tx_app.clear();
return;
}
}
}
}
}
}
if matches!(
cipher,
CipherKind::Aes128GcmSha256 | CipherKind::Aes256GcmSha384
) {
let key_len = cipher.key_len();
let schedules = scan_aes_key_schedules(&mem, key_len);
let iv_len = if sinfo.is_tls13 { 12 } else { 4 };
for (k_off, key_bytes) in schedules {
let win_start = k_off.saturating_sub(1024) & !3;
let win_end = (k_off + 1024).min(mem.len());
if win_end < win_start + iv_len {
continue;
}
for iv_pos in (win_start..=(win_end - iv_len)).step_by(4) {
let mut iv = [0u8; 12];
iv[..iv_len].copy_from_slice(&mem[iv_pos..iv_pos + iv_len]);
if is_trivial_slice(&iv[..iv_len]) {
continue;
}
let tk = TrafficKey {
cipher,
is_tls13: sinfo.is_tls13,
key_bytes: key_bytes.clone(),
iv,
seq: 0,
};
for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
let seqs: &[u64] = if sinfo.is_tls13 { &[0] } else { &[1, 0] };
for &try_seq in seqs {
if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, try_seq)
&& ct == 0x17
{
self.tx_secret_addr = Some(k_off);
let mut active = tk;
active.seq = try_seq + 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
&& ct2 == 0x17
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.tx_key = Some(active);
self.pending_tx_app.clear();
return;
}
}
}
}
}
}
if sinfo.is_tls13 {
let fin_len = 4 + cipher.hash_len() + 1 + 16;
let targets: Vec<RecordRef<'_>> = {
let non_fin: Vec<_> = self
.pending_tx_app
.iter()
.enumerate()
.filter(|(_, (_, p))| p.len() != fin_len)
.collect();
if non_fin.is_empty() {
self.pending_tx_app.iter().enumerate().collect()
} else {
non_fin
}
};
if let Some((pos, rec_idx, seq_hit, secret, tk, plain)) =
scan_high_entropy_tls13_secret(&mem, cipher, &targets, &[0])
{
self.ctx
.write_keylog("CLIENT_TRAFFIC_SECRET_0", &client_random, &secret);
self.tx_secret_addr = Some(pos);
let mut active = tk;
active.seq = seq_hit + 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
&& ct2 == 0x17
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.tx_key = Some(active);
self.pending_tx_app.clear();
}
}
}
fn try_extract_rx_key(&mut self, out_plain: &mut Vec<Vec<u8>>) {
if self.rx_key.is_some() || self.rx_scan_attempts >= 6 {
return;
}
let (Some(client_random), Some(sinfo)) = (self.client_random, self.server_info) else {
return;
};
if !sinfo.is_tls13 {
return; }
let Some(cipher) = CipherKind::from_suite(sinfo.cipher_suite) else {
return;
};
self.rx_scan_attempts += 1;
let sec_len = cipher.hash_len();
let rx_start = self
.rx_post_tx_start
.unwrap_or(0)
.min(self.pending_rx_app.len());
let rx_targets: Vec<RecordRef<'_>> = if rx_start < self.pending_rx_app.len() {
self.pending_rx_app
.iter()
.enumerate()
.skip(rx_start)
.collect()
} else {
self.pending_rx_app.iter().enumerate().collect()
};
if rx_targets.is_empty() {
return;
}
let mut windows: Vec<(usize, Vec<u8>)> = Vec::new();
if let Some(addr) = self.tx_secret_addr {
let start = addr.saturating_sub(16_384) & !3;
if let Some(slice) = self.ctx.read_slice(start, 32_768) {
windows.push((start, slice));
}
}
for &cr_addr in &self.client_random_addrs {
let start = cr_addr.saturating_sub(4096) & !3;
if let Some(slice) = self.ctx.read_slice(start, 20_480) {
windows.push((start, slice));
}
}
for (_base, buf) in &windows {
if buf.len() < sec_len {
continue;
}
for pos in (0..=(buf.len() - sec_len)).step_by(4) {
let cand = &buf[pos..pos + sec_len];
if is_trivial_slice(cand) {
continue;
}
let tk = TrafficKey::from_tls13_secret(cipher, cand);
for &(rec_idx, (hdr, payload)) in &rx_targets {
for try_seq in 0u64..=4 {
if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, try_seq)
&& ct == 0x17
{
self.ctx
.write_keylog("SERVER_TRAFFIC_SECRET_0", &client_random, cand);
let mut active = tk;
active.seq = try_seq + 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_rx_app[rec_idx + 1..] {
if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
&& ct2 == 0x17
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.rx_key = Some(active);
self.pending_rx_app.clear();
return;
}
}
}
}
}
if self.rx_scan_attempts <= 2 {
let mem = self.ctx.snapshot_memory();
if let Some((_pos, rec_idx, seq_hit, secret, tk, plain)) =
scan_high_entropy_tls13_secret(&mem, cipher, &rx_targets, &[0, 1, 2, 3, 4])
{
self.ctx
.write_keylog("SERVER_TRAFFIC_SECRET_0", &client_random, &secret);
let mut active = tk;
active.seq = seq_hit + 1;
if !plain.is_empty() {
out_plain.push(plain);
}
for (h2, p2) in &self.pending_rx_app[rec_idx + 1..] {
if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
&& ct2 == 0x17
&& !pl2.is_empty()
{
out_plain.push(pl2);
}
}
self.rx_key = Some(active);
self.pending_rx_app.clear();
}
}
}
}
fn is_trivial_slice(s: &[u8]) -> bool {
let first = s[0];
if s.iter().all(|&b| b == first) {
return true;
}
let zeros = s.iter().filter(|&&b| b == 0).count();
zeros > s.len() / 2
}
#[inline]
fn is_high_entropy_secret(s: &[u8]) -> bool {
if s.len() < 32 {
return false;
}
let mut prev_w = 0u64;
let mut ptr_like = 0u8;
for (idx, chunk) in s.chunks_exact(8).enumerate() {
let w = u64::from_le_bytes(chunk.try_into().unwrap());
if w == 0 || w == u64::MAX || (idx > 0 && w == prev_w) {
return false;
}
let top16 = (w >> 48) as u16;
if top16 == 0x0000 || top16 == 0xffff {
ptr_like += 1;
}
prev_w = w;
}
if ptr_like >= 2 {
return false;
}
let ascii = s
.iter()
.filter(|&&b| b.is_ascii_graphic() || b == b' ')
.count();
if ascii > (s.len() * 3) / 4 {
return false;
}
let mut bits = [0u64; 4];
for &b in &s[..32] {
bits[(b >> 6) as usize] |= 1u64 << (b & 63);
}
let distinct =
bits[0].count_ones() + bits[1].count_ones() + bits[2].count_ones() + bits[3].count_ones();
distinct >= 22
}
type FramedRecord = ([u8; 5], Vec<u8>);
type RecordRef<'a> = (usize, &'a FramedRecord);
type SecretScanHit = (usize, usize, u64, Vec<u8>, TrafficKey, Vec<u8>);
fn scan_high_entropy_tls13_secret(
mem: &[u8],
cipher: CipherKind,
targets: &[RecordRef<'_>],
seqs: &[u64],
) -> Option<SecretScanHit> {
let sec_len = cipher.hash_len();
if mem.len() < sec_len || targets.is_empty() {
return None;
}
let n_threads = std::thread::available_parallelism()
.map(|n| n.get().clamp(1, 4))
.unwrap_or(2);
let max_pos = mem.len() - sec_len;
let chunk_size = (max_pos / n_threads).max(4096) & !31;
for &(phase_off, stride) in &[(0usize, 32usize), (16, 32), (8, 16)] {
let found = AtomicBool::new(false);
let hit: Mutex<Option<SecretScanHit>> = Mutex::new(None);
std::thread::scope(|scope| {
for t in 0..n_threads {
let start = t * chunk_size;
if start > max_pos {
break;
}
let end = if t + 1 == n_threads {
max_pos
} else {
((t + 1) * chunk_size).min(max_pos)
};
let found_ref = &found;
let hit_ref = &hit;
scope.spawn(move || {
let mut pos = start.div_ceil(stride) * stride + phase_off;
if pos < start {
pos += stride;
}
let mut iter_count = 0u32;
while pos <= end {
iter_count = iter_count.wrapping_add(1);
if (iter_count & 1023) == 0 && found_ref.load(Ordering::Relaxed) {
return;
}
let cand = &mem[pos..pos + sec_len];
if is_high_entropy_secret(cand) {
let tk = TrafficKey::from_tls13_secret(cipher, cand);
for &(rec_idx, (hdr, payload)) in targets {
for &try_seq in seqs {
if let Some((ct, plain)) =
tk.decrypt_record_at(hdr, payload, try_seq)
&& ct == 0x17
{
found_ref.store(true, Ordering::Relaxed);
let mut guard = hit_ref.lock().unwrap();
if guard.is_none() {
*guard = Some((
pos,
rec_idx,
try_seq,
cand.to_vec(),
tk,
plain,
));
}
return;
}
}
}
}
pos += stride;
}
});
}
});
if let Some(res) = hit.into_inner().unwrap() {
return Some(res);
}
}
None
}
#[derive(Debug)]
struct InsecureLabCertVerifier;
impl ServerCertVerifier for InsecureLabCertVerifier {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
rustls::crypto::ring::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
pub struct MitmCa {
ca_cert_pem: String,
ca_cert_der: CertificateDer<'static>,
ca_cert: Certificate,
ca_key: KeyPair,
leaf_cache: Mutex<HashMap<String, Arc<ServerConfig>>>,
upstream_client_config: Arc<ClientConfig>,
crypto_provider: Arc<CryptoProvider>,
}
impl MitmCa {
pub fn generate(insecure_upstream: bool) -> Result<Arc<Self>> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let ca_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
.map_err(|e| format_err!("generate MITM CA key: {e}"))?;
let mut params = CertificateParams::default();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params
.distinguished_name
.push(DnType::CommonName, "unkernel-rs Forensic Lab CA");
params
.distinguished_name
.push(DnType::OrganizationName, "unkernel-rs");
let ca_cert = params
.self_signed(&ca_key)
.map_err(|e| format_err!("self-sign MITM CA cert: {e}"))?;
let ca_cert_pem = ca_cert.pem();
let ca_cert_der = CertificateDer::from(ca_cert.der().to_vec());
let mut client_cfg = if insecure_upstream {
ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.map_err(|e| format_err!("rustls client builder: {e}"))?
.dangerous()
.with_custom_certificate_verifier(Arc::new(InsecureLabCertVerifier))
.with_no_client_auth()
} else {
let mut roots = RootCertStore::empty();
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.map_err(|e| format_err!("rustls client builder: {e}"))?
.with_root_certificates(roots)
.with_no_client_auth()
};
client_cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
Ok(Arc::new(Self {
ca_cert_pem,
ca_cert_der,
ca_cert,
ca_key,
leaf_cache: Mutex::new(HashMap::new()),
upstream_client_config: Arc::new(client_cfg),
crypto_provider: provider,
}))
}
pub fn ca_cert_pem(&self) -> &str {
&self.ca_cert_pem
}
fn server_config_for(&self, host_or_ip: &str) -> Result<Arc<ServerConfig>> {
{
let cache = self.leaf_cache.lock().unwrap();
if let Some(cfg) = cache.get(host_or_ip) {
return Ok(cfg.clone());
}
}
let leaf_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
.map_err(|e| format_err!("generate leaf key for {host_or_ip}: {e}"))?;
let mut params = CertificateParams::default();
params
.distinguished_name
.push(DnType::CommonName, host_or_ip);
if let Ok(ip) = host_or_ip.parse::<IpAddr>() {
params.subject_alt_names.push(SanType::IpAddress(ip));
} else if let Ok(dns) = host_or_ip.try_into() {
params.subject_alt_names.push(SanType::DnsName(dns));
}
let leaf_cert = params
.signed_by(&leaf_key, &self.ca_cert, &self.ca_key)
.map_err(|e| format_err!("sign leaf cert for {host_or_ip}: {e}"))?;
let chain = vec![
CertificateDer::from(leaf_cert.der().to_vec()),
self.ca_cert_der.clone(),
];
let key_der = PrivateKeyDer::try_from(leaf_key.serialize_der())
.map_err(|e| format_err!("leaf key DER: {e}"))?;
let mut srv_cfg = ServerConfig::builder_with_provider(self.crypto_provider.clone())
.with_safe_default_protocol_versions()
.map_err(|e| format_err!("rustls server builder: {e}"))?
.with_no_client_auth()
.with_single_cert(chain, key_der)
.map_err(|e| format_err!("rustls leaf cert config: {e}"))?;
srv_cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
let srv_cfg = Arc::new(srv_cfg);
self.leaf_cache
.lock()
.unwrap()
.insert(host_or_ip.to_string(), srv_cfg.clone());
Ok(srv_cfg)
}
pub fn start_session(&self, sni_or_ip: &str) -> Result<MitmSession> {
let srv_cfg = self.server_config_for(sni_or_ip)?;
let server = ServerConnection::new(srv_cfg)
.map_err(|e| format_err!("rustls ServerConnection: {e}"))?;
let server_name = ServerName::try_from(sni_or_ip.to_string())
.or_else(|_| ServerName::try_from("localhost".to_string()))
.map_err(|e| format_err!("rustls ServerName: {e}"))?;
let client = ClientConnection::new(self.upstream_client_config.clone(), server_name)
.map_err(|e| format_err!("rustls ClientConnection: {e}"))?;
Ok(MitmSession { server, client })
}
}
pub struct MitmStep {
pub to_guest: Vec<u8>,
pub to_upstream: Vec<u8>,
pub decrypted: Vec<u8>,
}
pub struct MitmSession {
server: ServerConnection,
client: ClientConnection,
}
impl MitmSession {
pub fn on_guest_tx(&mut self, data: &[u8]) -> Result<MitmStep> {
let mut cursor = Cursor::new(data);
while (cursor.position() as usize) < data.len() {
let n = self
.server
.read_tls(&mut cursor)
.map_err(|e| format_err!("mitm server read_tls: {e}"))?;
if n == 0 {
break;
}
self.server
.process_new_packets()
.map_err(|e| format_err!("mitm server process: {e}"))?;
}
let mut decrypted = Vec::new();
let mut tmp = [0u8; 8192];
loop {
match self.server.reader().read(&mut tmp) {
Ok(0) => break,
Ok(n) => decrypted.extend_from_slice(&tmp[..n]),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(_) => break,
}
}
if !decrypted.is_empty() {
let _ = self.client.writer().write_all(&decrypted);
}
let mut to_guest = Vec::new();
while self.server.wants_write() {
let _ = self.server.write_tls(&mut to_guest);
}
let mut to_upstream = Vec::new();
while self.client.wants_write() {
let _ = self.client.write_tls(&mut to_upstream);
}
Ok(MitmStep {
to_guest,
to_upstream,
decrypted,
})
}
pub fn on_upstream_rx(&mut self, data: &[u8]) -> Result<MitmStep> {
let mut cursor = Cursor::new(data);
while (cursor.position() as usize) < data.len() {
let n = self
.client
.read_tls(&mut cursor)
.map_err(|e| format_err!("mitm client read_tls: {e}"))?;
if n == 0 {
break;
}
self.client
.process_new_packets()
.map_err(|e| format_err!("mitm client process: {e}"))?;
}
let mut decrypted = Vec::new();
let mut tmp = [0u8; 8192];
loop {
match self.client.reader().read(&mut tmp) {
Ok(0) => break,
Ok(n) => decrypted.extend_from_slice(&tmp[..n]),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
Err(_) => break,
}
}
if !decrypted.is_empty() {
let _ = self.server.writer().write_all(&decrypted);
}
let mut to_upstream = Vec::new();
while self.client.wants_write() {
let _ = self.client.write_tls(&mut to_upstream);
}
let mut to_guest = Vec::new();
while self.server.wants_write() {
let _ = self.server.write_tls(&mut to_guest);
}
Ok(MitmStep {
to_guest,
to_upstream,
decrypted,
})
}
pub fn on_guest_eof(&mut self) -> Vec<u8> {
self.client.send_close_notify();
let mut to_upstream = Vec::new();
while self.client.wants_write() {
let _ = self.client.write_tls(&mut to_upstream);
}
to_upstream
}
pub fn on_upstream_eof(&mut self) -> Vec<u8> {
self.server.send_close_notify();
let mut to_guest = Vec::new();
while self.server.wants_write() {
let _ = self.server.write_tls(&mut to_guest);
}
to_guest
}
}
#[cfg(test)]
mod tests {
use super::*;
use wasmtime::{Config, Engine, MemoryType};
fn make_tls13_record(
cipher: CipherKind,
secret: &[u8],
seq: u64,
inner_ct: u8,
pt: &[u8],
) -> Vec<u8> {
let key_bytes = tls13_hkdf_expand_label(cipher, secret, b"key", cipher.key_len());
let iv_vec = tls13_hkdf_expand_label(cipher, secret, b"iv", 12);
let mut iv = [0u8; 12];
iv.copy_from_slice(&iv_vec[..12]);
let mut body = pt.to_vec();
body.push(inner_ct);
let total_len = (body.len() + 16) as u16;
let hdr = [0x17, 0x03, 0x03, (total_len >> 8) as u8, total_len as u8];
let unbound = UnboundKey::new(cipher.aead_alg(), &key_bytes).unwrap();
let aead_key = LessSafeKey::new(unbound);
aead_key
.seal_in_place_append_tag(
Nonce::assume_unique_for_key(xor_iv_seq(&iv, seq)),
Aad::from(&hdr[..]),
&mut body,
)
.unwrap();
let mut rec = Vec::with_capacity(5 + body.len());
rec.extend_from_slice(&hdr);
rec.extend_from_slice(&body);
rec
}
#[test]
fn vmi_tls13_recovers_client_and_server_secrets_from_shared_memory() {
let mut wt_cfg = Config::new();
wt_cfg.wasm_threads(true);
wt_cfg.shared_memory(true);
let engine = Engine::new(&wt_cfg).unwrap();
let mem = SharedMemory::new(&engine, MemoryType::shared(2, 2)).unwrap();
let client_random: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1));
let client_secret: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(13).wrapping_add(3));
let server_secret: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(17).wrapping_add(9));
let data = mem.data();
let write_mem = |addr: usize, src: &[u8]| {
for (i, &b) in src.iter().enumerate() {
unsafe { AtomicU8::from_ptr(data[addr + i].get()).store(b, Ordering::Relaxed) };
}
};
write_mem(0x4000, &client_random);
write_mem(0x4120, &client_secret);
write_mem(0x4160, &server_secret);
let ctx = VmiTlsContext::new(mem, 2 * 65536, None);
let mut insp = VmiTlsInspector::new(ctx);
let mut ch = vec![
0x16, 0x03, 0x01, 0x00, 0x2a, 0x01, 0x00, 0x00, 0x26, 0x03, 0x03,
];
ch.extend_from_slice(&client_random);
ch.extend_from_slice(&[0, 0, 2, 0x13, 0x01, 1, 0]);
let ch_len = (ch.len() - 5) as u16;
ch[3..5].copy_from_slice(&ch_len.to_be_bytes());
assert!(insp.observe_tx(&ch).is_empty());
let mut sh = vec![
0x16, 0x03, 0x03, 0x00, 0x30, 0x02, 0x00, 0x00, 0x2c, 0x03, 0x03,
];
sh.extend_from_slice(&[0xaa; 32]); sh.push(0); sh.extend_from_slice(&0x1301u16.to_be_bytes()); sh.push(0); sh.extend_from_slice(&[0x00, 0x06, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04]); let sh_len = (sh.len() - 5) as u16;
sh[3..5].copy_from_slice(&sh_len.to_be_bytes());
assert!(insp.observe_rx(&sh).is_empty());
let tx_rec = make_tls13_record(
CipherKind::Aes128GcmSha256,
&client_secret,
0,
0x17,
b"GET /secret?tok=canary HTTP/1.1\r\nHost: exfil.test\r\n\r\n",
);
let tx_plain = insp.observe_tx(&tx_rec);
assert_eq!(tx_plain.len(), 1);
assert!(String::from_utf8_lossy(&tx_plain[0]).contains("GET /secret?tok=canary"));
let rx_rec = make_tls13_record(
CipherKind::Aes128GcmSha256,
&server_secret,
0,
0x17,
b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nPONG",
);
let rx_plain = insp.observe_rx(&rx_rec);
assert_eq!(rx_plain.len(), 1);
assert!(String::from_utf8_lossy(&rx_plain[0]).contains("PONG"));
}
#[test]
fn find_aes_detects_valid_aes128_schedule() {
let key: [u8; 16] = [
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
0x4f, 0x3c,
];
let mut w = [0u32; 44];
for i in 0..4 {
w[i] = u32::from_be_bytes(key[4 * i..4 * (i + 1)].try_into().unwrap());
}
for i in 4..44 {
let mut t = w[i - 1];
if i % 4 == 0 {
t = aes_sub_word(t.rotate_left(8)) ^ AES_RCON[(i / 4) - 1];
}
w[i] = w[i - 4] ^ t;
}
let mut mem = vec![0u8; 4096];
for (i, word) in w.iter().enumerate() {
mem[512 + i * 4..512 + (i + 1) * 4].copy_from_slice(&word.to_le_bytes());
}
let found = scan_aes_key_schedules(&mem, 16);
assert_eq!(found.len(), 1);
assert_eq!(found[0].0, 512);
assert_eq!(found[0].1.as_slice(), &key);
}
#[test]
fn mitm_ca_and_sans_io_handshake_decrypts_traffic() {
let ca = MitmCa::generate(true).expect("generate MITM CA");
assert!(ca.ca_cert_pem().contains("BEGIN CERTIFICATE"));
let mut guest_roots = RootCertStore::empty();
guest_roots.add(ca.ca_cert_der.clone()).unwrap();
let provider = Arc::new(rustls::crypto::ring::default_provider());
let guest_cfg = Arc::new(
ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(guest_roots)
.with_no_client_auth(),
);
let mut guest = ClientConnection::new(
guest_cfg,
ServerName::try_from("demo.lab.local".to_string()).unwrap(),
)
.unwrap();
let up_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
let up_cert = CertificateParams::new(vec!["demo.lab.local".to_string()])
.unwrap()
.self_signed(&up_key)
.unwrap();
let up_srv_cfg = Arc::new(
ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(
vec![CertificateDer::from(up_cert.der().to_vec())],
PrivateKeyDer::try_from(up_key.serialize_der()).unwrap(),
)
.unwrap(),
);
let mut upstream = ServerConnection::new(up_srv_cfg).unwrap();
let mut mitm = ca.start_session("demo.lab.local").unwrap();
guest
.writer()
.write_all(b"POST /exfil HTTP/1.1\r\nHost: demo.lab.local\r\n\r\nSECRET=abc")
.unwrap();
let mut seen_tx = Vec::new();
let mut seen_rx = Vec::new();
let mut upstream_replied = false;
for _ in 0..16 {
let mut g2m = Vec::new();
while guest.wants_write() {
guest.write_tls(&mut g2m).unwrap();
}
if !g2m.is_empty() {
let step = mitm.on_guest_tx(&g2m).unwrap();
seen_tx.extend_from_slice(&step.decrypted);
if !step.to_guest.is_empty() {
let mut c = Cursor::new(&step.to_guest);
while (c.position() as usize) < step.to_guest.len() {
guest.read_tls(&mut c).unwrap();
guest.process_new_packets().unwrap();
}
}
if !step.to_upstream.is_empty() {
let mut c = Cursor::new(&step.to_upstream);
while (c.position() as usize) < step.to_upstream.len() {
upstream.read_tls(&mut c).unwrap();
upstream.process_new_packets().unwrap();
}
}
}
let mut up_plain = Vec::new();
let mut tmp = [0u8; 1024];
while let Ok(n) = upstream.reader().read(&mut tmp) {
if n == 0 {
break;
}
up_plain.extend_from_slice(&tmp[..n]);
}
if !up_plain.is_empty() && !upstream_replied {
upstream_replied = true;
upstream
.writer()
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
.unwrap();
}
let mut u2m = Vec::new();
while upstream.wants_write() {
upstream.write_tls(&mut u2m).unwrap();
}
if !u2m.is_empty() {
let step = mitm.on_upstream_rx(&u2m).unwrap();
seen_rx.extend_from_slice(&step.decrypted);
if !step.to_upstream.is_empty() {
let mut c = Cursor::new(&step.to_upstream);
while (c.position() as usize) < step.to_upstream.len() {
upstream.read_tls(&mut c).unwrap();
upstream.process_new_packets().unwrap();
}
}
if !step.to_guest.is_empty() {
let mut c = Cursor::new(&step.to_guest);
while (c.position() as usize) < step.to_guest.len() {
guest.read_tls(&mut c).unwrap();
guest.process_new_packets().unwrap();
}
}
}
}
assert!(String::from_utf8_lossy(&seen_tx).contains("SECRET=abc"));
assert!(String::from_utf8_lossy(&seen_rx).contains("HTTP/1.1 200 OK"));
}
#[test]
fn vmi_tls13_pass3_recovers_split_heap_secrets_without_client_random_for_chacha20() {
let mut wt_cfg = Config::new();
wt_cfg.wasm_threads(true);
wt_cfg.shared_memory(true);
let engine = Engine::new(&wt_cfg).unwrap();
let mem = SharedMemory::new(&engine, MemoryType::shared(4, 4)).unwrap();
let client_random: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(11).wrapping_add(5));
let client_secret: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(37).wrapping_add(0x83));
let server_secret: [u8; 32] =
std::array::from_fn(|i| (i as u8).wrapping_mul(53).wrapping_add(0x41));
let data = mem.data();
let write_mem = |addr: usize, src: &[u8]| {
for (i, &b) in src.iter().enumerate() {
unsafe { AtomicU8::from_ptr(data[addr + i].get()).store(b, Ordering::Relaxed) };
}
};
write_mem(0x1_2040, &client_secret); write_mem(0x3_4080, &server_secret);
let ctx = VmiTlsContext::new(mem, 4 * 65536, None);
let mut insp = VmiTlsInspector::new(ctx);
let mut ch = vec![
0x16, 0x03, 0x01, 0x00, 0x2a, 0x01, 0x00, 0x00, 0x26, 0x03, 0x03,
];
ch.extend_from_slice(&client_random);
ch.extend_from_slice(&[0, 0, 2, 0x13, 0x03, 1, 0]);
let ch_len = (ch.len() - 5) as u16;
ch[3..5].copy_from_slice(&ch_len.to_be_bytes());
insp.observe_tx(&ch);
let mut sh = vec![
0x16, 0x03, 0x03, 0x00, 0x30, 0x02, 0x00, 0x00, 0x2c, 0x03, 0x03,
];
sh.extend_from_slice(&[0xbb; 32]);
sh.push(0);
sh.extend_from_slice(&0x1303u16.to_be_bytes()); sh.push(0);
sh.extend_from_slice(&[0x00, 0x06, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04]);
let sh_len = (sh.len() - 5) as u16;
sh[3..5].copy_from_slice(&sh_len.to_be_bytes());
insp.observe_rx(&sh);
let tx_rec = make_tls13_record(
CipherKind::ChaCha20Poly1305Sha256,
&client_secret,
0,
0x17,
b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n",
);
let tx_plain = insp.observe_tx(&tx_rec);
assert_eq!(tx_plain.len(), 1);
assert_eq!(tx_plain[0], b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
let rx_rec = make_tls13_record(
CipherKind::ChaCha20Poly1305Sha256,
&server_secret,
1, 0x17,
b"GO_CHACHA20_RX_OK",
);
let rx_plain = insp.observe_rx(&rx_rec);
assert_eq!(rx_plain.len(), 1);
assert_eq!(rx_plain[0], b"GO_CHACHA20_RX_OK");
}
}