Skip to main content

unkernel_rs/
tls_inspect.rs

1//! Host-side HTTPS forensic inspection for `unkernel-rs`.
2//!
3//! Provides two complementary, pure-Rust decryption engines:
4//!
5//! 1. **Method 1 — Zero-Touch Host-Side VMI TLS Key Extraction ([`VmiTlsInspector`]):**
6//!    Extracts live TLS 1.3 and TLS 1.2 session keys directly from `wasmtime::SharedMemory`
7//!    without injecting any CA certificate, modifying the guest filesystem, or breaking
8//!    certificate pinning.
9//!    - **Pass 1 (`client_random` anchor):** Scans `SharedMemory` for the exact 32-byte
10//!      `ClientHello.random` observed on the wire, then verifies candidate `traffic_secret`
11//!      (TLS 1.3) or `master_secret` (TLS 1.2) windows in the surrounding struct memory
12//!      mathematically against the captured encrypted AEAD record (zero false positives).
13//!      Optionally writes standard Wireshark `SSLKEYLOGFILE` lines on the host.
14//!    - **Pass 2 (*FindAES* round-key schedule fallback):** For runtimes that wipe
15//!      `client_random` after handshake, scans `SharedMemory` for algebraically valid
16//!      AES-128 (176 B) / AES-256 (240 B) expanded round-key schedules and verifies nearby
17//!      IV candidates against the captured GCM record.
18//!
19//! 2. **Method 2 — Opt-In Transparent Host TLS MITM Proxy ([`MitmCa`] + [`MitmSession`]):**
20//!    Generates an ephemeral per-VM ECDSA P-256 Root CA (`rcgen`) and dynamically signs per-SNI
21//!    leaf certificates, terminating guest TLS and re-encrypting upstream via Sans-I/O
22//!    `rustls::ServerConnection` + `rustls::ClientConnection`. Works across every cipher and
23//!    runtime (OpenSSL, Go, Rust, Python, Node) with zero scanning overhead.
24
25use crate::monitor::extract_http_request;
26use rcgen::{BasicConstraints, Certificate, CertificateParams, DnType, IsCa, KeyPair, SanType};
27use ring::aead::{
28    AES_128_GCM, AES_256_GCM, Aad, CHACHA20_POLY1305, LessSafeKey, Nonce, UnboundKey,
29};
30use ring::hmac;
31use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
32use rustls::crypto::CryptoProvider;
33use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
34use rustls::{
35    ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,
36    ServerConnection, SignatureScheme,
37};
38use std::collections::HashMap;
39use std::fs::File;
40use std::io::{Cursor, Read, Write};
41use std::net::IpAddr;
42use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
43use std::sync::{Arc, Mutex};
44use wasmtime::{Result, SharedMemory, format_err};
45
46// ---------------------------------------------------------------------------
47// Shared plaintext summary helpers
48// ---------------------------------------------------------------------------
49
50/// Maximum plaintext preview bytes stored in a single `net.tls_decrypted` audit event.
51const MAX_PREVIEW_BYTES: usize = 2048;
52
53/// Format a compact HTTP summary (request line or status line) and sanitized lossy preview.
54pub fn summarize_tls_plaintext(data: &[u8]) -> (Option<String>, String) {
55    let http_summary = if let Some((method, path, host)) = extract_http_request(data) {
56        Some(match host {
57            Some(h) => format!("{method} {path} (Host: {h})"),
58            None => format!("{method} {path}"),
59        })
60    } else if data.starts_with(b"HTTP/1.") || data.starts_with(b"HTTP/2") {
61        let end = data
62            .iter()
63            .position(|&b| b == b'\r' || b == b'\n')
64            .unwrap_or(data.len().min(120));
65        std::str::from_utf8(&data[..end])
66            .ok()
67            .map(|s| s.trim().to_string())
68            .filter(|s| !s.is_empty())
69    } else {
70        None
71    };
72
73    let take = data.len().min(MAX_PREVIEW_BYTES);
74    let preview = String::from_utf8_lossy(&data[..take]).into_owned();
75    (http_summary, preview)
76}
77
78/// Check whether `data` starts with a TLS Handshake (`0x16`) `ClientHello` (`0x01`) record.
79pub fn looks_like_tls_client_hello(data: &[u8]) -> bool {
80    data.len() >= 6 && data[0] == 0x16 && data[1] == 0x03 && data[5] == 0x01
81}
82
83/// Extract the 32-byte `ClientHello.random` from a TLS ClientHello record.
84pub fn extract_client_random(data: &[u8]) -> Option<[u8; 32]> {
85    if data.len() < 43 || data[0] != 0x16 || data[1] != 0x03 || data[5] != 0x01 {
86        return None;
87    }
88    let mut rnd = [0u8; 32];
89    rnd.copy_from_slice(&data[11..43]);
90    Some(rnd)
91}
92
93/// Parsed fields from a TLS `ServerHello` handshake message.
94#[derive(Debug, Clone, Copy)]
95pub struct ServerHelloInfo {
96    pub server_random: [u8; 32],
97    pub cipher_suite: u16,
98    pub is_tls13: bool,
99}
100
101/// Extract `server_random`, `cipher_suite`, and TLS 1.3 version indicator from a `ServerHello`
102/// handshake message payload (starting at handshake header byte `0x02`).
103pub fn parse_server_hello_handshake(hs: &[u8]) -> Option<ServerHelloInfo> {
104    if hs.len() < 40 || hs[0] != 0x02 {
105        return None;
106    }
107    let msg_len = ((hs[1] as usize) << 16) | ((hs[2] as usize) << 8) | (hs[3] as usize);
108    let end = (4 + msg_len).min(hs.len());
109    if end < 40 {
110        return None;
111    }
112    let mut server_random = [0u8; 32];
113    server_random.copy_from_slice(&hs[6..38]);
114    let mut p = 38;
115    if p >= end {
116        return None;
117    }
118    let sid_len = hs[p] as usize;
119    p += 1 + sid_len;
120    if p + 3 > end {
121        return None;
122    }
123    let cipher_suite = u16::from_be_bytes([hs[p], hs[p + 1]]);
124    p += 3; // cipher_suite (2) + compression_method (1)
125
126    let mut is_tls13 = matches!(cipher_suite, 0x1301..=0x1305);
127    if p + 2 <= end {
128        let ext_len = u16::from_be_bytes([hs[p], hs[p + 1]]) as usize;
129        p += 2;
130        let ext_end = (p + ext_len).min(end);
131        while p + 4 <= ext_end {
132            let etype = u16::from_be_bytes([hs[p], hs[p + 1]]);
133            let elen = u16::from_be_bytes([hs[p + 2], hs[p + 3]]) as usize;
134            p += 4;
135            if p + elen > ext_end {
136                break;
137            }
138            // supported_versions (0x002b): 2-byte selected version 0x0304 == TLS 1.3
139            if etype == 0x002b && elen == 2 && hs[p] == 0x03 && hs[p + 1] == 0x04 {
140                is_tls13 = true;
141            }
142            p += elen;
143        }
144    }
145
146    Some(ServerHelloInfo {
147        server_random,
148        cipher_suite,
149        is_tls13,
150    })
151}
152
153// ---------------------------------------------------------------------------
154// Method 1: Zero-Touch Host-Side VMI SharedMemory TLS Key Extraction
155// ---------------------------------------------------------------------------
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158enum CipherKind {
159    Aes128GcmSha256,
160    Aes256GcmSha384,
161    ChaCha20Poly1305Sha256,
162}
163
164impl CipherKind {
165    fn from_suite(suite: u16) -> Option<Self> {
166        match suite {
167            0x1301 | 0xc02f | 0xc02b | 0x009c => Some(Self::Aes128GcmSha256),
168            0x1302 | 0xc030 | 0xc02c | 0x009d => Some(Self::Aes256GcmSha384),
169            0x1303 | 0xcca8 | 0xcca9 => Some(Self::ChaCha20Poly1305Sha256),
170            _ => None,
171        }
172    }
173
174    fn key_len(self) -> usize {
175        match self {
176            Self::Aes128GcmSha256 => 16,
177            Self::Aes256GcmSha384 | Self::ChaCha20Poly1305Sha256 => 32,
178        }
179    }
180
181    fn hash_len(self) -> usize {
182        match self {
183            Self::Aes128GcmSha256 | Self::ChaCha20Poly1305Sha256 => 32,
184            Self::Aes256GcmSha384 => 48,
185        }
186    }
187
188    fn hmac_alg(self) -> hmac::Algorithm {
189        match self {
190            Self::Aes128GcmSha256 | Self::ChaCha20Poly1305Sha256 => hmac::HMAC_SHA256,
191            Self::Aes256GcmSha384 => hmac::HMAC_SHA384,
192        }
193    }
194
195    fn aead_alg(self) -> &'static ring::aead::Algorithm {
196        match self {
197            Self::Aes128GcmSha256 => &AES_128_GCM,
198            Self::Aes256GcmSha384 => &AES_256_GCM,
199            Self::ChaCha20Poly1305Sha256 => &CHACHA20_POLY1305,
200        }
201    }
202}
203
204/// RFC 8446 Section 7.1 `HKDF-Expand-Label(Secret, Label, "", Length)` for `Length <= hash_len`.
205fn tls13_hkdf_expand_label(
206    cipher: CipherKind,
207    secret: &[u8],
208    label: &[u8],
209    out_len: usize,
210) -> Vec<u8> {
211    let full_label_len = 6 + label.len();
212    let mut info = Vec::with_capacity(2 + 1 + full_label_len + 1 + 1);
213    info.extend_from_slice(&(out_len as u16).to_be_bytes());
214    info.push(full_label_len as u8);
215    info.extend_from_slice(b"tls13 ");
216    info.extend_from_slice(label);
217    info.push(0); // empty transcript context
218    info.push(1); // HKDF counter = 0x01 (out_len <= 32 <= hash_len)
219    let key = hmac::Key::new(cipher.hmac_alg(), secret);
220    let tag = hmac::sign(&key, &info);
221    tag.as_ref()[..out_len].to_vec()
222}
223
224/// RFC 5246 Section 5 TLS 1.2 `P_hash` PRF expansion.
225fn tls12_prf(
226    cipher: CipherKind,
227    secret: &[u8],
228    label: &[u8],
229    seed: &[u8],
230    out_len: usize,
231) -> Vec<u8> {
232    let key = hmac::Key::new(cipher.hmac_alg(), secret);
233    let mut label_seed = Vec::with_capacity(label.len() + seed.len());
234    label_seed.extend_from_slice(label);
235    label_seed.extend_from_slice(seed);
236
237    let mut out = Vec::with_capacity(out_len);
238    let mut a = hmac::sign(&key, &label_seed).as_ref().to_vec();
239    while out.len() < out_len {
240        let mut ctx = hmac::Context::with_key(&key);
241        ctx.update(&a);
242        ctx.update(&label_seed);
243        let block = ctx.sign();
244        let need = (out_len - out.len()).min(block.as_ref().len());
245        out.extend_from_slice(&block.as_ref()[..need]);
246        a = hmac::sign(&key, &a).as_ref().to_vec();
247    }
248    out
249}
250
251fn xor_iv_seq(iv: &[u8; 12], seq: u64) -> [u8; 12] {
252    let mut nonce = *iv;
253    let sb = seq.to_be_bytes();
254    for i in 0..8 {
255        nonce[4 + i] ^= sb[i];
256    }
257    nonce
258}
259
260#[derive(Clone)]
261struct TrafficKey {
262    cipher: CipherKind,
263    is_tls13: bool,
264    key_bytes: Vec<u8>,
265    /// 12-byte IV for TLS 1.3 & TLS 1.2 ChaCha20; 4-byte fixed IV (padded) for TLS 1.2 AES-GCM.
266    iv: [u8; 12],
267    seq: u64,
268}
269
270impl TrafficKey {
271    fn from_tls13_secret(cipher: CipherKind, secret: &[u8]) -> Self {
272        let key_bytes = tls13_hkdf_expand_label(cipher, secret, b"key", cipher.key_len());
273        let iv_vec = tls13_hkdf_expand_label(cipher, secret, b"iv", 12);
274        let mut iv = [0u8; 12];
275        iv.copy_from_slice(&iv_vec[..12]);
276        Self {
277            cipher,
278            is_tls13: true,
279            key_bytes,
280            iv,
281            seq: 0,
282        }
283    }
284
285    fn from_tls12_master(
286        cipher: CipherKind,
287        master_secret: &[u8],
288        client_random: &[u8; 32],
289        server_random: &[u8; 32],
290    ) -> (Self, Self) {
291        let key_len = cipher.key_len();
292        let iv_len = if cipher == CipherKind::ChaCha20Poly1305Sha256 {
293            12
294        } else {
295            4
296        };
297        let mut seed = [0u8; 64];
298        seed[..32].copy_from_slice(server_random);
299        seed[32..].copy_from_slice(client_random);
300        let block = tls12_prf(
301            cipher,
302            master_secret,
303            b"key expansion",
304            &seed,
305            2 * key_len + 2 * iv_len,
306        );
307        let c_key = block[0..key_len].to_vec();
308        let s_key = block[key_len..2 * key_len].to_vec();
309        let mut c_iv = [0u8; 12];
310        let mut s_iv = [0u8; 12];
311        c_iv[..iv_len].copy_from_slice(&block[2 * key_len..2 * key_len + iv_len]);
312        s_iv[..iv_len].copy_from_slice(&block[2 * key_len + iv_len..2 * key_len + 2 * iv_len]);
313        (
314            Self {
315                cipher,
316                is_tls13: false,
317                key_bytes: c_key,
318                iv: c_iv,
319                seq: 0,
320            },
321            Self {
322                cipher,
323                is_tls13: false,
324                key_bytes: s_key,
325                iv: s_iv,
326                seq: 0,
327            },
328        )
329    }
330
331    /// Decrypt one TLS record `(header[5], payload)` at explicit sequence number `seq`.
332    /// Returns `(inner_content_type, plaintext)`.
333    fn decrypt_record_at(
334        &self,
335        header: &[u8; 5],
336        payload: &[u8],
337        seq: u64,
338    ) -> Option<(u8, Vec<u8>)> {
339        let unbound = UnboundKey::new(self.cipher.aead_alg(), &self.key_bytes).ok()?;
340        let aead_key = LessSafeKey::new(unbound);
341
342        if self.is_tls13 {
343            if payload.len() < 17 {
344                return None;
345            }
346            let nonce_bytes = xor_iv_seq(&self.iv, seq);
347            let mut buf = payload.to_vec();
348            let plain = aead_key
349                .open_in_place(
350                    Nonce::assume_unique_for_key(nonce_bytes),
351                    Aad::from(&header[..]),
352                    &mut buf,
353                )
354                .ok()?;
355            // Strip trailing zero padding per RFC 8446 Section 5.4
356            let mut end = plain.len();
357            while end > 0 && plain[end - 1] == 0 {
358                end -= 1;
359            }
360            if end == 0 {
361                return None;
362            }
363            let inner_type = plain[end - 1];
364            Some((inner_type, plain[..end - 1].to_vec()))
365        } else if self.cipher == CipherKind::ChaCha20Poly1305Sha256 {
366            if payload.len() < 16 {
367                return None;
368            }
369            let plain_len = (payload.len() - 16) as u16;
370            let mut aad = [0u8; 13];
371            aad[0..8].copy_from_slice(&seq.to_be_bytes());
372            aad[8] = header[0];
373            aad[9] = header[1];
374            aad[10] = header[2];
375            aad[11..13].copy_from_slice(&plain_len.to_be_bytes());
376            let nonce_bytes = xor_iv_seq(&self.iv, seq);
377            let mut buf = payload.to_vec();
378            let plain = aead_key
379                .open_in_place(
380                    Nonce::assume_unique_for_key(nonce_bytes),
381                    Aad::from(&aad[..]),
382                    &mut buf,
383                )
384                .ok()?;
385            Some((header[0], plain.to_vec()))
386        } else {
387            // TLS 1.2 AES-GCM: 8-byte explicit nonce prefix + ciphertext + 16-byte tag
388            if payload.len() < 24 {
389                return None;
390            }
391            let plain_len = (payload.len() - 24) as u16;
392            let mut aad = [0u8; 13];
393            aad[0..8].copy_from_slice(&seq.to_be_bytes());
394            aad[8] = header[0];
395            aad[9] = header[1];
396            aad[10] = header[2];
397            aad[11..13].copy_from_slice(&plain_len.to_be_bytes());
398            let mut nonce_bytes = [0u8; 12];
399            nonce_bytes[0..4].copy_from_slice(&self.iv[0..4]);
400            nonce_bytes[4..12].copy_from_slice(&payload[0..8]);
401            let mut buf = payload[8..].to_vec();
402            let plain = aead_key
403                .open_in_place(
404                    Nonce::assume_unique_for_key(nonce_bytes),
405                    Aad::from(&aad[..]),
406                    &mut buf,
407                )
408                .ok()?;
409            Some((header[0], plain.to_vec()))
410        }
411    }
412
413    fn decrypt_next(&mut self, header: &[u8; 5], payload: &[u8]) -> Option<(u8, Vec<u8>)> {
414        let res = self.decrypt_record_at(header, payload, self.seq)?;
415        self.seq = self.seq.wrapping_add(1);
416        Some(res)
417    }
418}
419
420/// Reassembles framed TLS records from arbitrary TCP stream chunks.
421#[derive(Default)]
422struct TlsRecordFramer {
423    buf: Vec<u8>,
424}
425
426impl TlsRecordFramer {
427    fn push(&mut self, data: &[u8]) -> Vec<([u8; 5], Vec<u8>)> {
428        self.buf.extend_from_slice(data);
429        let mut records = Vec::new();
430        while self.buf.len() >= 5 {
431            let ct = self.buf[0];
432            if !matches!(ct, 0x14..=0x17) || self.buf[1] != 0x03 {
433                // Not valid TLS framing; drop buffer to stop wasting memory
434                self.buf.clear();
435                break;
436            }
437            let len = u16::from_be_bytes([self.buf[3], self.buf[4]]) as usize;
438            if len > 18_432 {
439                self.buf.clear();
440                break;
441            }
442            if self.buf.len() < 5 + len {
443                break;
444            }
445            let mut hdr = [0u8; 5];
446            hdr.copy_from_slice(&self.buf[0..5]);
447            let payload = self.buf[5..5 + len].to_vec();
448            self.buf.drain(..5 + len);
449            records.push((hdr, payload));
450        }
451        records
452    }
453}
454
455/// Shared host context for Method 1 VMI `SharedMemory` TLS key extraction.
456pub struct VmiTlsContext {
457    memory: SharedMemory,
458    memory_bytes: usize,
459    keylog_file: Option<Arc<Mutex<File>>>,
460}
461
462impl VmiTlsContext {
463    pub fn new(
464        memory: SharedMemory,
465        memory_bytes: usize,
466        keylog_file: Option<Arc<Mutex<File>>>,
467    ) -> Arc<Self> {
468        Arc::new(Self {
469            memory,
470            memory_bytes,
471            keylog_file,
472        })
473    }
474
475    fn snapshot_memory(&self) -> Vec<u8> {
476        let data = self.memory.data();
477        let len = self.memory_bytes.min(data.len());
478        let mut out = vec![0u8; len];
479        for (i, b) in out.iter_mut().enumerate() {
480            unsafe {
481                *b = AtomicU8::from_ptr(data[i].get()).load(Ordering::Relaxed);
482            }
483        }
484        out
485    }
486
487    fn read_slice(&self, addr: usize, len: usize) -> Option<Vec<u8>> {
488        let data = self.memory.data();
489        let limit = self.memory_bytes.min(data.len());
490        if addr >= limit || len == 0 {
491            return None;
492        }
493        let end = addr.saturating_add(len).min(limit);
494        let mut out = vec![0u8; end - addr];
495        for (i, b) in out.iter_mut().enumerate() {
496            unsafe {
497                *b = AtomicU8::from_ptr(data[addr + i].get()).load(Ordering::Relaxed);
498            }
499        }
500        Some(out)
501    }
502
503    fn write_keylog(&self, label: &str, client_random: &[u8; 32], secret: &[u8]) {
504        let Some(f) = &self.keylog_file else { return };
505        let line = format!(
506            "{label} {} {}\n",
507            hex_lower(client_random),
508            hex_lower(secret)
509        );
510        if let Ok(mut guard) = f.lock() {
511            let _ = guard.write_all(line.as_bytes());
512            let _ = guard.flush();
513        }
514    }
515}
516
517fn hex_lower(bytes: &[u8]) -> String {
518    let mut s = String::with_capacity(bytes.len() * 2);
519    for &b in bytes {
520        use std::fmt::Write as _;
521        let _ = write!(&mut s, "{b:02x}");
522    }
523    s
524}
525
526/// Find all byte offsets in `haystack` equal to the 32-byte `needle` using a fast 8-byte prefilter.
527pub fn find_32byte_matches(haystack: &[u8], needle: &[u8; 32]) -> Vec<usize> {
528    let mut hits = Vec::new();
529    if haystack.len() < 32 {
530        return hits;
531    }
532    let first8 = u64::from_ne_bytes(needle[0..8].try_into().unwrap());
533    let b0 = needle[0];
534    let limit = haystack.len() - 32;
535    let mut i = 0;
536    while i <= limit {
537        if haystack[i] == b0 {
538            let cand8 = u64::from_ne_bytes(haystack[i..i + 8].try_into().unwrap());
539            if cand8 == first8 && &haystack[i..i + 32] == needle {
540                hits.push(i);
541                i += 32;
542                continue;
543            }
544        }
545        i += 1;
546    }
547    hits
548}
549
550// Standard AES S-Box & Rcon for Pass 2 (*FindAES*) key-schedule scanning.
551const AES_SBOX: [u8; 256] = [
552    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
553    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
554    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
555    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
556    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
557    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
558    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
559    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
560    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
561    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
562    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
563    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
564    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
565    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
566    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
567    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
568];
569
570const AES_RCON: [u32; 10] = [
571    0x0100_0000,
572    0x0200_0000,
573    0x0400_0000,
574    0x0800_0000,
575    0x1000_0000,
576    0x2000_0000,
577    0x4000_0000,
578    0x8000_0000,
579    0x1b00_0000,
580    0x3600_0000,
581];
582
583#[inline]
584fn aes_sub_word(w: u32) -> u32 {
585    let b = w.to_be_bytes();
586    u32::from_be_bytes([
587        AES_SBOX[b[0] as usize],
588        AES_SBOX[b[1] as usize],
589        AES_SBOX[b[2] as usize],
590        AES_SBOX[b[3] as usize],
591    ])
592}
593
594/// Scan a memory image for algebraically valid AES-128 (176-byte) or AES-256 (240-byte)
595/// expanded round-key schedules (both big-endian and little-endian `u32` word layouts, as used
596/// by OpenSSL, Go, and `ring`). Returns `(offset_in_mem, raw_key_bytes)`.
597pub fn scan_aes_key_schedules(mem: &[u8], key_len: usize) -> Vec<(usize, Vec<u8>)> {
598    let mut found = Vec::new();
599    let sched_bytes = if key_len == 16 { 176 } else { 240 };
600    if mem.len() < sched_bytes {
601        return found;
602    }
603    let nk = key_len / 4; // 4 or 8
604    let total_words = sched_bytes / 4; // 44 or 60
605    let limit = mem.len() - sched_bytes;
606
607    for off in (0..=limit).step_by(4) {
608        for &le_words in &[true, false] {
609            let read_w = |idx: usize| -> u32 {
610                let p = off + idx * 4;
611                let bytes: [u8; 4] = mem[p..p + 4].try_into().unwrap();
612                if le_words {
613                    u32::from_le_bytes(bytes)
614                } else {
615                    u32::from_be_bytes(bytes)
616                }
617            };
618            let w0 = read_w(0);
619            let w1 = read_w(1);
620            let w_last = read_w(nk - 1);
621            if w0 == 0 && w1 == 0 && w_last == 0 {
622                continue;
623            }
624            // Fast 2-word algebraic prefilter eliminates >99.99999% of RAM immediately
625            let exp_nk = w0 ^ aes_sub_word(w_last.rotate_left(8)) ^ AES_RCON[0];
626            if read_w(nk) != exp_nk {
627                continue;
628            }
629            if read_w(nk + 1) != (w1 ^ exp_nk) {
630                continue;
631            }
632            // Verify full remaining round-key schedule
633            let mut prev = read_w(nk + 1);
634            let mut ok = true;
635            for i in (nk + 2)..total_words {
636                let mut temp = prev;
637                if i % nk == 0 {
638                    temp = aes_sub_word(temp.rotate_left(8)) ^ AES_RCON[(i / nk) - 1];
639                } else if nk == 8 && i % nk == 4 {
640                    temp = aes_sub_word(temp);
641                }
642                let expected = read_w(i - nk) ^ temp;
643                let actual = read_w(i);
644                if actual != expected {
645                    ok = false;
646                    break;
647                }
648                prev = actual;
649            }
650            if ok {
651                let mut key = Vec::with_capacity(key_len);
652                for idx in 0..nk {
653                    key.extend_from_slice(&read_w(idx).to_be_bytes());
654                }
655                found.push((off, key));
656                break;
657            }
658        }
659    }
660    found
661}
662
663/// Per-connection zero-touch VMI TLS passive decryptor.
664pub struct VmiTlsInspector {
665    ctx: Arc<VmiTlsContext>,
666    tx_framer: TlsRecordFramer,
667    rx_framer: TlsRecordFramer,
668    client_random: Option<[u8; 32]>,
669    server_info: Option<ServerHelloInfo>,
670    tx_key: Option<TrafficKey>,
671    rx_key: Option<TrafficKey>,
672    /// Memory addresses where `client_random` and the verified TX secret were located (speeds up RX key lookup to <0.1 ms).
673    client_random_addrs: Vec<usize>,
674    tx_secret_addr: Option<usize>,
675    /// Encrypted TX `0x17` records queued until we lock onto `client_application_traffic_secret_0`.
676    pending_tx_app: Vec<([u8; 5], Vec<u8>)>,
677    /// Encrypted RX `0x17` records queued until we lock onto `server_application_traffic_secret_0`.
678    pending_rx_app: Vec<([u8; 5], Vec<u8>)>,
679    /// Index in `pending_rx_app` marking records received after client TX Application Data started.
680    rx_post_tx_start: Option<usize>,
681    tx_scan_attempts: u8,
682    rx_scan_attempts: u8,
683}
684
685impl VmiTlsInspector {
686    pub fn new(ctx: Arc<VmiTlsContext>) -> Self {
687        Self {
688            ctx,
689            tx_framer: TlsRecordFramer::default(),
690            rx_framer: TlsRecordFramer::default(),
691            client_random: None,
692            server_info: None,
693            tx_key: None,
694            rx_key: None,
695            client_random_addrs: Vec::new(),
696            tx_secret_addr: None,
697            pending_tx_app: Vec::new(),
698            pending_rx_app: Vec::new(),
699            rx_post_tx_start: None,
700            tx_scan_attempts: 0,
701            rx_scan_attempts: 0,
702        }
703    }
704
705    /// Observe outbound guest -> remote TCP bytes. Returns any newly decrypted Application Data chunks.
706    pub fn observe_tx(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
707        let mut decrypted = Vec::new();
708        for (hdr, payload) in self.tx_framer.push(data) {
709            match hdr[0] {
710                0x16 if self.client_random.is_none()
711                    && payload.len() >= 38
712                    && payload[0] == 0x01 =>
713                {
714                    let mut rnd = [0u8; 32];
715                    rnd.copy_from_slice(&payload[6..38]);
716                    self.client_random = Some(rnd);
717                }
718                0x17 => {
719                    if let Some(key) = &mut self.tx_key {
720                        if let Some((ct, plain)) = key.decrypt_next(&hdr, &payload)
721                            && ct == 0x17
722                            && !plain.is_empty()
723                        {
724                            decrypted.push(plain);
725                        }
726                    } else if self.client_random.is_some()
727                        && let Some(sinfo) = self.server_info
728                        && self.pending_tx_app.len() < 8
729                    {
730                        self.pending_tx_app.push((hdr, payload));
731                        // In TLS 1.3, the client's very first 0x17 record is `Client Finished`
732                        // (36+1+16=53 B for SHA-256 or 52+1+16=69 B for SHA-384), encrypted with
733                        // `client_handshake_traffic_secret` rather than `client_app_traffic_secret`.
734                        // Wait until a real Application Data record arrives so we don't waste a scan.
735                        let fin_len = CipherKind::from_suite(sinfo.cipher_suite)
736                            .map(|c| 4 + c.hash_len() + 1 + 16)
737                            .unwrap_or(53);
738                        let only_finished = sinfo.is_tls13
739                            && self.pending_tx_app.len() == 1
740                            && self.pending_tx_app[0].1.len() == fin_len;
741                        if !only_finished {
742                            self.try_extract_tx_key(&mut decrypted);
743                            if self.tx_key.is_some() && self.rx_post_tx_start.is_none() {
744                                self.rx_post_tx_start = Some(self.pending_rx_app.len());
745                            }
746                        }
747                    }
748                }
749                _ => {}
750            }
751        }
752        decrypted
753    }
754
755    /// Observe inbound remote -> guest TCP bytes. Returns any newly decrypted Application Data chunks.
756    pub fn observe_rx(&mut self, data: &[u8]) -> Vec<Vec<u8>> {
757        let mut decrypted = Vec::new();
758        for (hdr, payload) in self.rx_framer.push(data) {
759            match hdr[0] {
760                0x16 if self.server_info.is_none() => {
761                    if let Some(info) = parse_server_hello_handshake(&payload) {
762                        self.server_info = Some(info);
763                    }
764                }
765                0x17 => {
766                    if let Some(key) = &mut self.rx_key {
767                        if let Some((ct, plain)) = key.decrypt_next(&hdr, &payload)
768                            && ct == 0x17
769                            && !plain.is_empty()
770                        {
771                            decrypted.push(plain);
772                        }
773                    } else if self.client_random.is_some()
774                        && self.server_info.is_some()
775                        && self.pending_rx_app.len() < 16
776                    {
777                        self.pending_rx_app.push((hdr, payload));
778                        // Wait until client TX Application Data has started so we don't burn RX
779                        // scans on Server EncryptedExtensions / Certificate / Finished records.
780                        if self.tx_key.is_some() {
781                            self.try_extract_rx_key(&mut decrypted);
782                        }
783                    }
784                }
785                _ => {}
786            }
787        }
788        decrypted
789    }
790
791    fn try_extract_tx_key(&mut self, out_plain: &mut Vec<Vec<u8>>) {
792        if self.tx_key.is_some() || self.tx_scan_attempts >= 4 {
793            return;
794        }
795        let (Some(client_random), Some(sinfo)) = (self.client_random, self.server_info) else {
796            return;
797        };
798        let Some(cipher) = CipherKind::from_suite(sinfo.cipher_suite) else {
799            return;
800        };
801        self.tx_scan_attempts += 1;
802
803        let mem = self.ctx.snapshot_memory();
804        let hits = find_32byte_matches(&mem, &client_random);
805        if !hits.is_empty() {
806            self.client_random_addrs = hits.clone();
807        }
808
809        // Pass 1: Search around every `client_random` match for TLS 1.3 client_app_traffic_secret
810        // or TLS 1.2 master_secret
811        for &cr_addr in &hits {
812            let win_start = cr_addr.saturating_sub(4096) & !3;
813            let win_end = (cr_addr + 16_384).min(mem.len());
814            if sinfo.is_tls13 {
815                let sec_len = cipher.hash_len();
816                if win_end < win_start + sec_len {
817                    continue;
818                }
819                for pos in (win_start..=(win_end - sec_len)).step_by(4) {
820                    let cand = &mem[pos..pos + sec_len];
821                    if is_trivial_slice(cand) {
822                        continue;
823                    }
824                    let tk = TrafficKey::from_tls13_secret(cipher, cand);
825                    for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
826                        if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, 0)
827                            && ct == 0x17
828                        {
829                            self.ctx
830                                .write_keylog("CLIENT_TRAFFIC_SECRET_0", &client_random, cand);
831                            self.tx_secret_addr = Some(pos);
832                            let mut active = tk;
833                            active.seq = 1;
834                            if !plain.is_empty() {
835                                out_plain.push(plain);
836                            }
837                            for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
838                                if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
839                                    && ct2 == 0x17
840                                    && !pl2.is_empty()
841                                {
842                                    out_plain.push(pl2);
843                                }
844                            }
845                            self.tx_key = Some(active);
846                            self.pending_tx_app.clear();
847                            return;
848                        }
849                    }
850                }
851            } else {
852                // TLS 1.2: 48-byte master_secret derives BOTH client and server keys at once!
853                if win_end < win_start + 48 {
854                    continue;
855                }
856                for pos in (win_start..=(win_end - 48)).step_by(4) {
857                    let cand = &mem[pos..pos + 48];
858                    if is_trivial_slice(cand) {
859                        continue;
860                    }
861                    let (c_tk, s_tk) = TrafficKey::from_tls12_master(
862                        cipher,
863                        cand,
864                        &client_random,
865                        &sinfo.server_random,
866                    );
867                    for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
868                        // In TLS 1.2, sequence 0 is Client Finished (0x16), so first AppData (0x17) is seq 1 (or 0 if renegotiated)
869                        for try_seq in [1u64, 0u64, 2u64] {
870                            if let Some((_, plain)) = c_tk.decrypt_record_at(hdr, payload, try_seq)
871                            {
872                                self.ctx.write_keylog("CLIENT_RANDOM", &client_random, cand);
873                                self.tx_secret_addr = Some(pos);
874                                let mut active_tx = c_tk;
875                                active_tx.seq = try_seq + 1;
876                                if !plain.is_empty() {
877                                    out_plain.push(plain);
878                                }
879                                for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
880                                    if let Some((_, pl2)) = active_tx.decrypt_next(h2, p2)
881                                        && !pl2.is_empty()
882                                    {
883                                        out_plain.push(pl2);
884                                    }
885                                }
886                                self.tx_key = Some(active_tx);
887                                let mut active_rx = s_tk;
888                                active_rx.seq = 1; // seq 0 is Server Finished
889                                self.rx_key = Some(active_rx);
890                                self.pending_tx_app.clear();
891                                return;
892                            }
893                        }
894                    }
895                }
896            }
897        }
898
899        // Pass 2: Fallback FindAES expanded round-key schedule scanner (for Go/rustls wiping client_random)
900        if matches!(
901            cipher,
902            CipherKind::Aes128GcmSha256 | CipherKind::Aes256GcmSha384
903        ) {
904            let key_len = cipher.key_len();
905            let schedules = scan_aes_key_schedules(&mem, key_len);
906            let iv_len = if sinfo.is_tls13 { 12 } else { 4 };
907            for (k_off, key_bytes) in schedules {
908                let win_start = k_off.saturating_sub(1024) & !3;
909                let win_end = (k_off + 1024).min(mem.len());
910                if win_end < win_start + iv_len {
911                    continue;
912                }
913                for iv_pos in (win_start..=(win_end - iv_len)).step_by(4) {
914                    let mut iv = [0u8; 12];
915                    iv[..iv_len].copy_from_slice(&mem[iv_pos..iv_pos + iv_len]);
916                    if is_trivial_slice(&iv[..iv_len]) {
917                        continue;
918                    }
919                    let tk = TrafficKey {
920                        cipher,
921                        is_tls13: sinfo.is_tls13,
922                        key_bytes: key_bytes.clone(),
923                        iv,
924                        seq: 0,
925                    };
926                    for (rec_idx, (hdr, payload)) in self.pending_tx_app.iter().enumerate() {
927                        let seqs: &[u64] = if sinfo.is_tls13 { &[0] } else { &[1, 0] };
928                        for &try_seq in seqs {
929                            if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, try_seq)
930                                && ct == 0x17
931                            {
932                                self.tx_secret_addr = Some(k_off);
933                                let mut active = tk;
934                                active.seq = try_seq + 1;
935                                if !plain.is_empty() {
936                                    out_plain.push(plain);
937                                }
938                                for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
939                                    if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
940                                        && ct2 == 0x17
941                                        && !pl2.is_empty()
942                                    {
943                                        out_plain.push(pl2);
944                                    }
945                                }
946                                self.tx_key = Some(active);
947                                self.pending_tx_app.clear();
948                                return;
949                            }
950                        }
951                    }
952                }
953            }
954        }
955        // Pass 3: Parallel high-entropy TLS 1.3 `traffic_secret` full-RAM fallback scanner.
956        // Recovers `client_application_traffic_secret_0` even when the runtime's allocator places
957        // `traffic_secret` far from `client_random` (e.g. Go `crypto/tls` size-class `mspan`s,
958        // `rustls`) — works for AES-128-GCM, AES-256-GCM, AND ChaCha20-Poly1305!
959        if sinfo.is_tls13 {
960            let fin_len = 4 + cipher.hash_len() + 1 + 16;
961            let targets: Vec<RecordRef<'_>> = {
962                let non_fin: Vec<_> = self
963                    .pending_tx_app
964                    .iter()
965                    .enumerate()
966                    .filter(|(_, (_, p))| p.len() != fin_len)
967                    .collect();
968                if non_fin.is_empty() {
969                    self.pending_tx_app.iter().enumerate().collect()
970                } else {
971                    non_fin
972                }
973            };
974            if let Some((pos, rec_idx, seq_hit, secret, tk, plain)) =
975                scan_high_entropy_tls13_secret(&mem, cipher, &targets, &[0])
976            {
977                self.ctx
978                    .write_keylog("CLIENT_TRAFFIC_SECRET_0", &client_random, &secret);
979                self.tx_secret_addr = Some(pos);
980                let mut active = tk;
981                active.seq = seq_hit + 1;
982                if !plain.is_empty() {
983                    out_plain.push(plain);
984                }
985                for (h2, p2) in &self.pending_tx_app[rec_idx + 1..] {
986                    if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
987                        && ct2 == 0x17
988                        && !pl2.is_empty()
989                    {
990                        out_plain.push(pl2);
991                    }
992                }
993                self.tx_key = Some(active);
994                self.pending_tx_app.clear();
995            }
996        }
997    }
998
999    fn try_extract_rx_key(&mut self, out_plain: &mut Vec<Vec<u8>>) {
1000        if self.rx_key.is_some() || self.rx_scan_attempts >= 6 {
1001            return;
1002        }
1003        let (Some(client_random), Some(sinfo)) = (self.client_random, self.server_info) else {
1004            return;
1005        };
1006        if !sinfo.is_tls13 {
1007            return; // TLS 1.2 already derives rx_key from master_secret in try_extract_tx_key
1008        }
1009        let Some(cipher) = CipherKind::from_suite(sinfo.cipher_suite) else {
1010            return;
1011        };
1012        self.rx_scan_attempts += 1;
1013
1014        let sec_len = cipher.hash_len();
1015        let rx_start = self
1016            .rx_post_tx_start
1017            .unwrap_or(0)
1018            .min(self.pending_rx_app.len());
1019        let rx_targets: Vec<RecordRef<'_>> = if rx_start < self.pending_rx_app.len() {
1020            self.pending_rx_app
1021                .iter()
1022                .enumerate()
1023                .skip(rx_start)
1024                .collect()
1025        } else {
1026            self.pending_rx_app.iter().enumerate().collect()
1027        };
1028        if rx_targets.is_empty() {
1029            return;
1030        }
1031
1032        // Fast targeted scan right around tx_secret_addr (±16 KiB covers Go's 8 KiB mspan +
1033        // adjacent pages in <0.5 ms!) and client_random_addrs.
1034        let mut windows: Vec<(usize, Vec<u8>)> = Vec::new();
1035        if let Some(addr) = self.tx_secret_addr {
1036            let start = addr.saturating_sub(16_384) & !3;
1037            if let Some(slice) = self.ctx.read_slice(start, 32_768) {
1038                windows.push((start, slice));
1039            }
1040        }
1041        for &cr_addr in &self.client_random_addrs {
1042            let start = cr_addr.saturating_sub(4096) & !3;
1043            if let Some(slice) = self.ctx.read_slice(start, 20_480) {
1044                windows.push((start, slice));
1045            }
1046        }
1047
1048        for (_base, buf) in &windows {
1049            if buf.len() < sec_len {
1050                continue;
1051            }
1052            for pos in (0..=(buf.len() - sec_len)).step_by(4) {
1053                let cand = &buf[pos..pos + sec_len];
1054                if is_trivial_slice(cand) {
1055                    continue;
1056                }
1057                let tk = TrafficKey::from_tls13_secret(cipher, cand);
1058                // Server TLS 1.3 handshake records precede application records; once application
1059                // traffic starts, the server may send 0..=3 NewSessionTicket (inner ct 0x16)
1060                // records using server_app_traffic_secret before HTTP AppData (inner ct 0x17).
1061                for &(rec_idx, (hdr, payload)) in &rx_targets {
1062                    for try_seq in 0u64..=4 {
1063                        if let Some((ct, plain)) = tk.decrypt_record_at(hdr, payload, try_seq)
1064                            && ct == 0x17
1065                        {
1066                            self.ctx
1067                                .write_keylog("SERVER_TRAFFIC_SECRET_0", &client_random, cand);
1068                            let mut active = tk;
1069                            active.seq = try_seq + 1;
1070                            if !plain.is_empty() {
1071                                out_plain.push(plain);
1072                            }
1073                            for (h2, p2) in &self.pending_rx_app[rec_idx + 1..] {
1074                                if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
1075                                    && ct2 == 0x17
1076                                    && !pl2.is_empty()
1077                                {
1078                                    out_plain.push(pl2);
1079                                }
1080                            }
1081                            self.rx_key = Some(active);
1082                            self.pending_rx_app.clear();
1083                            return;
1084                        }
1085                    }
1086                }
1087            }
1088        }
1089
1090        // Pass 3 fallback for RX if server_app_traffic_secret landed on a distant Go/Rust heap page
1091        if self.rx_scan_attempts <= 2 {
1092            let mem = self.ctx.snapshot_memory();
1093            if let Some((_pos, rec_idx, seq_hit, secret, tk, plain)) =
1094                scan_high_entropy_tls13_secret(&mem, cipher, &rx_targets, &[0, 1, 2, 3, 4])
1095            {
1096                self.ctx
1097                    .write_keylog("SERVER_TRAFFIC_SECRET_0", &client_random, &secret);
1098                let mut active = tk;
1099                active.seq = seq_hit + 1;
1100                if !plain.is_empty() {
1101                    out_plain.push(plain);
1102                }
1103                for (h2, p2) in &self.pending_rx_app[rec_idx + 1..] {
1104                    if let Some((ct2, pl2)) = active.decrypt_next(h2, p2)
1105                        && ct2 == 0x17
1106                        && !pl2.is_empty()
1107                    {
1108                        out_plain.push(pl2);
1109                    }
1110                }
1111                self.rx_key = Some(active);
1112                self.pending_rx_app.clear();
1113            }
1114        }
1115    }
1116}
1117
1118fn is_trivial_slice(s: &[u8]) -> bool {
1119    let first = s[0];
1120    if s.iter().all(|&b| b == first) {
1121        return true;
1122    }
1123    let zeros = s.iter().filter(|&&b| b == 0).count();
1124    zeros > s.len() / 2
1125}
1126
1127/// Fast high-entropy prefilter for 32-byte or 48-byte cryptographic HKDF secrets.
1128/// Eliminates >98% of Linux/Go/Rust guest RAM (zero pages, pointers, ASCII, structs) in ~10 ns
1129/// while passing >99.9999% of uniform random secrets.
1130#[inline]
1131fn is_high_entropy_secret(s: &[u8]) -> bool {
1132    if s.len() < 32 {
1133        return false;
1134    }
1135    let mut prev_w = 0u64;
1136    let mut ptr_like = 0u8;
1137    for (idx, chunk) in s.as_chunks::<8>().0.iter().enumerate() {
1138        let w = u64::from_le_bytes(*chunk);
1139        if w == 0 || w == u64::MAX || (idx > 0 && w == prev_w) {
1140            return false;
1141        }
1142        // User-space 64-bit pointers (0x0000_0040_xxxx_xxxx) or kernel pointers (0xffff_xxxx_...)
1143        let top16 = (w >> 48) as u16;
1144        if top16 == 0x0000 || top16 == 0xffff {
1145            ptr_like += 1;
1146        }
1147        prev_w = w;
1148    }
1149    if ptr_like >= 2 {
1150        return false;
1151    }
1152    let ascii = s
1153        .iter()
1154        .filter(|&&b| b.is_ascii_graphic() || b == b' ')
1155        .count();
1156    if ascii > (s.len() * 3) / 4 {
1157        return false;
1158    }
1159    let mut bits = [0u64; 4];
1160    for &b in &s[..32] {
1161        bits[(b >> 6) as usize] |= 1u64 << (b & 63);
1162    }
1163    let distinct =
1164        bits[0].count_ones() + bits[1].count_ones() + bits[2].count_ones() + bits[3].count_ones();
1165    distinct >= 22
1166}
1167
1168type FramedRecord = ([u8; 5], Vec<u8>);
1169type RecordRef<'a> = (usize, &'a FramedRecord);
1170type SecretScanHit = (usize, usize, u64, Vec<u8>, TrafficKey, Vec<u8>);
1171
1172/// Parallel full-RAM fallback scanner for TLS 1.3 `application_traffic_secret_0`.
1173/// Searches 32-byte aligned slots first (Go 32B `mspan`s), then +16 (Go 48B `mspan`s & 16B allocs),
1174/// then +8 (8B-aligned struct fields), stopping immediately across all worker threads on first match.
1175fn scan_high_entropy_tls13_secret(
1176    mem: &[u8],
1177    cipher: CipherKind,
1178    targets: &[RecordRef<'_>],
1179    seqs: &[u64],
1180) -> Option<SecretScanHit> {
1181    let sec_len = cipher.hash_len();
1182    if mem.len() < sec_len || targets.is_empty() {
1183        return None;
1184    }
1185    let n_threads = std::thread::available_parallelism()
1186        .map(|n| n.get().clamp(1, 4))
1187        .unwrap_or(2);
1188    let max_pos = mem.len() - sec_len;
1189    let chunk_size = (max_pos / n_threads).max(4096) & !31;
1190
1191    for &(phase_off, stride) in &[(0usize, 32usize), (16, 32), (8, 16)] {
1192        let found = AtomicBool::new(false);
1193        let hit: Mutex<Option<SecretScanHit>> = Mutex::new(None);
1194
1195        std::thread::scope(|scope| {
1196            for t in 0..n_threads {
1197                let start = t * chunk_size;
1198                if start > max_pos {
1199                    break;
1200                }
1201                let end = if t + 1 == n_threads {
1202                    max_pos
1203                } else {
1204                    ((t + 1) * chunk_size).min(max_pos)
1205                };
1206                let found_ref = &found;
1207                let hit_ref = &hit;
1208                scope.spawn(move || {
1209                    let mut pos = start.div_ceil(stride) * stride + phase_off;
1210                    if pos < start {
1211                        pos += stride;
1212                    }
1213                    let mut iter_count = 0u32;
1214                    while pos <= end {
1215                        iter_count = iter_count.wrapping_add(1);
1216                        if (iter_count & 1023) == 0 && found_ref.load(Ordering::Relaxed) {
1217                            return;
1218                        }
1219                        let cand = &mem[pos..pos + sec_len];
1220                        if is_high_entropy_secret(cand) {
1221                            let tk = TrafficKey::from_tls13_secret(cipher, cand);
1222                            for &(rec_idx, (hdr, payload)) in targets {
1223                                for &try_seq in seqs {
1224                                    if let Some((ct, plain)) =
1225                                        tk.decrypt_record_at(hdr, payload, try_seq)
1226                                        && ct == 0x17
1227                                    {
1228                                        found_ref.store(true, Ordering::Relaxed);
1229                                        let mut guard = hit_ref.lock().unwrap();
1230                                        if guard.is_none() {
1231                                            *guard = Some((
1232                                                pos,
1233                                                rec_idx,
1234                                                try_seq,
1235                                                cand.to_vec(),
1236                                                tk,
1237                                                plain,
1238                                            ));
1239                                        }
1240                                        return;
1241                                    }
1242                                }
1243                            }
1244                        }
1245                        pos += stride;
1246                    }
1247                });
1248            }
1249        });
1250
1251        if let Some(res) = hit.into_inner().unwrap() {
1252            return Some(res);
1253        }
1254    }
1255    None
1256}
1257
1258// ---------------------------------------------------------------------------
1259// Method 2: Opt-In Transparent Host TLS MITM Proxy (`--mitm-tls`)
1260// ---------------------------------------------------------------------------
1261
1262#[derive(Debug)]
1263struct InsecureLabCertVerifier;
1264
1265impl ServerCertVerifier for InsecureLabCertVerifier {
1266    fn verify_server_cert(
1267        &self,
1268        _end_entity: &CertificateDer<'_>,
1269        _intermediates: &[CertificateDer<'_>],
1270        _server_name: &ServerName<'_>,
1271        _ocsp_response: &[u8],
1272        _now: UnixTime,
1273    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
1274        Ok(ServerCertVerified::assertion())
1275    }
1276
1277    fn verify_tls12_signature(
1278        &self,
1279        _message: &[u8],
1280        _cert: &CertificateDer<'_>,
1281        _dss: &DigitallySignedStruct,
1282    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
1283        Ok(HandshakeSignatureValid::assertion())
1284    }
1285
1286    fn verify_tls13_signature(
1287        &self,
1288        _message: &[u8],
1289        _cert: &CertificateDer<'_>,
1290        _dss: &DigitallySignedStruct,
1291    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
1292        Ok(HandshakeSignatureValid::assertion())
1293    }
1294
1295    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
1296        rustls::crypto::ring::default_provider()
1297            .signature_verification_algorithms
1298            .supported_schemes()
1299    }
1300}
1301
1302/// Ephemeral per-VM Root CA and leaf certificate cache for transparent host-side `--mitm-tls`.
1303pub struct MitmCa {
1304    ca_cert_pem: String,
1305    ca_cert_der: CertificateDer<'static>,
1306    ca_cert: Certificate,
1307    ca_key: KeyPair,
1308    leaf_cache: Mutex<HashMap<String, Arc<ServerConfig>>>,
1309    upstream_client_config: Arc<ClientConfig>,
1310    crypto_provider: Arc<CryptoProvider>,
1311}
1312
1313impl MitmCa {
1314    /// Generate a fresh ephemeral ECDSA P-256 Root CA for this VM session.
1315    pub fn generate(insecure_upstream: bool) -> Result<Arc<Self>> {
1316        let provider = Arc::new(rustls::crypto::ring::default_provider());
1317        let ca_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1318            .map_err(|e| format_err!("generate MITM CA key: {e}"))?;
1319        let mut params = CertificateParams::default();
1320        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1321        params
1322            .distinguished_name
1323            .push(DnType::CommonName, "unkernel-rs Forensic Lab CA");
1324        params
1325            .distinguished_name
1326            .push(DnType::OrganizationName, "unkernel-rs");
1327        let ca_cert = params
1328            .self_signed(&ca_key)
1329            .map_err(|e| format_err!("self-sign MITM CA cert: {e}"))?;
1330        let ca_cert_pem = ca_cert.pem();
1331        let ca_cert_der = CertificateDer::from(ca_cert.der().to_vec());
1332
1333        let mut client_cfg = if insecure_upstream {
1334            ClientConfig::builder_with_provider(provider.clone())
1335                .with_safe_default_protocol_versions()
1336                .map_err(|e| format_err!("rustls client builder: {e}"))?
1337                .dangerous()
1338                .with_custom_certificate_verifier(Arc::new(InsecureLabCertVerifier))
1339                .with_no_client_auth()
1340        } else {
1341            let mut roots = RootCertStore::empty();
1342            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1343            ClientConfig::builder_with_provider(provider.clone())
1344                .with_safe_default_protocol_versions()
1345                .map_err(|e| format_err!("rustls client builder: {e}"))?
1346                .with_root_certificates(roots)
1347                .with_no_client_auth()
1348        };
1349        client_cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
1350
1351        Ok(Arc::new(Self {
1352            ca_cert_pem,
1353            ca_cert_der,
1354            ca_cert,
1355            ca_key,
1356            leaf_cache: Mutex::new(HashMap::new()),
1357            upstream_client_config: Arc::new(client_cfg),
1358            crypto_provider: provider,
1359        }))
1360    }
1361
1362    /// Root CA certificate in PEM format (installed into the disposable guest trust store).
1363    pub fn ca_cert_pem(&self) -> &str {
1364        &self.ca_cert_pem
1365    }
1366
1367    pub fn server_config_for(&self, host_or_ip: &str) -> Result<Arc<ServerConfig>> {
1368        {
1369            let cache = self.leaf_cache.lock().unwrap();
1370            if let Some(cfg) = cache.get(host_or_ip) {
1371                return Ok(cfg.clone());
1372            }
1373        }
1374
1375        let leaf_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
1376            .map_err(|e| format_err!("generate leaf key for {host_or_ip}: {e}"))?;
1377        let mut params = CertificateParams::default();
1378        params
1379            .distinguished_name
1380            .push(DnType::CommonName, host_or_ip);
1381        if let Ok(ip) = host_or_ip.parse::<IpAddr>() {
1382            params.subject_alt_names.push(SanType::IpAddress(ip));
1383        } else if let Ok(dns) = host_or_ip.try_into() {
1384            params.subject_alt_names.push(SanType::DnsName(dns));
1385        }
1386        let leaf_cert = params
1387            .signed_by(&leaf_key, &self.ca_cert, &self.ca_key)
1388            .map_err(|e| format_err!("sign leaf cert for {host_or_ip}: {e}"))?;
1389
1390        let chain = vec![
1391            CertificateDer::from(leaf_cert.der().to_vec()),
1392            self.ca_cert_der.clone(),
1393        ];
1394        let key_der = PrivateKeyDer::try_from(leaf_key.serialize_der())
1395            .map_err(|e| format_err!("leaf key DER: {e}"))?;
1396
1397        let mut srv_cfg = ServerConfig::builder_with_provider(self.crypto_provider.clone())
1398            .with_safe_default_protocol_versions()
1399            .map_err(|e| format_err!("rustls server builder: {e}"))?
1400            .with_no_client_auth()
1401            .with_single_cert(chain, key_der)
1402            .map_err(|e| format_err!("rustls leaf cert config: {e}"))?;
1403        srv_cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
1404        let srv_cfg = Arc::new(srv_cfg);
1405
1406        self.leaf_cache
1407            .lock()
1408            .unwrap()
1409            .insert(host_or_ip.to_string(), srv_cfg.clone());
1410        Ok(srv_cfg)
1411    }
1412
1413    /// Create a Sans-I/O duplex [`MitmSession`] for a new guest TLS connection.
1414    pub fn start_session(&self, sni_or_ip: &str) -> Result<MitmSession> {
1415        let srv_cfg = self.server_config_for(sni_or_ip)?;
1416        let server = ServerConnection::new(srv_cfg)
1417            .map_err(|e| format_err!("rustls ServerConnection: {e}"))?;
1418        let server_name = ServerName::try_from(sni_or_ip.to_string())
1419            .or_else(|_| ServerName::try_from("localhost".to_string()))
1420            .map_err(|e| format_err!("rustls ServerName: {e}"))?;
1421        let client = ClientConnection::new(self.upstream_client_config.clone(), server_name)
1422            .map_err(|e| format_err!("rustls ClientConnection: {e}"))?;
1423        Ok(MitmSession { server, client })
1424    }
1425}
1426
1427/// Output produced by feeding one side of a [`MitmSession`].
1428pub struct MitmStep {
1429    pub to_guest: Vec<u8>,
1430    pub to_upstream: Vec<u8>,
1431    pub decrypted: Vec<u8>,
1432}
1433
1434/// Sans-I/O transparent TLS MITM bridge (`guest <-> ServerConnection <-> ClientConnection <-> upstream`).
1435pub struct MitmSession {
1436    server: ServerConnection,
1437    client: ClientConnection,
1438}
1439
1440impl MitmSession {
1441    /// Feed encrypted bytes arriving from the guest VM.
1442    pub fn on_guest_tx(&mut self, data: &[u8]) -> Result<MitmStep> {
1443        let mut cursor = Cursor::new(data);
1444        while (cursor.position() as usize) < data.len() {
1445            let n = self
1446                .server
1447                .read_tls(&mut cursor)
1448                .map_err(|e| format_err!("mitm server read_tls: {e}"))?;
1449            if n == 0 {
1450                break;
1451            }
1452            self.server
1453                .process_new_packets()
1454                .map_err(|e| format_err!("mitm server process: {e}"))?;
1455        }
1456
1457        let mut decrypted = Vec::new();
1458        let mut tmp = [0u8; 8192];
1459        loop {
1460            match self.server.reader().read(&mut tmp) {
1461                Ok(0) => break,
1462                Ok(n) => decrypted.extend_from_slice(&tmp[..n]),
1463                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
1464                Err(_) => break,
1465            }
1466        }
1467        if !decrypted.is_empty() {
1468            let _ = self.client.writer().write_all(&decrypted);
1469        }
1470
1471        let mut to_guest = Vec::new();
1472        while self.server.wants_write() {
1473            let _ = self.server.write_tls(&mut to_guest);
1474        }
1475        let mut to_upstream = Vec::new();
1476        while self.client.wants_write() {
1477            let _ = self.client.write_tls(&mut to_upstream);
1478        }
1479
1480        Ok(MitmStep {
1481            to_guest,
1482            to_upstream,
1483            decrypted,
1484        })
1485    }
1486
1487    /// Feed encrypted bytes arriving from the remote upstream server.
1488    pub fn on_upstream_rx(&mut self, data: &[u8]) -> Result<MitmStep> {
1489        let mut cursor = Cursor::new(data);
1490        while (cursor.position() as usize) < data.len() {
1491            let n = self
1492                .client
1493                .read_tls(&mut cursor)
1494                .map_err(|e| format_err!("mitm client read_tls: {e}"))?;
1495            if n == 0 {
1496                break;
1497            }
1498            self.client
1499                .process_new_packets()
1500                .map_err(|e| format_err!("mitm client process: {e}"))?;
1501        }
1502
1503        let mut decrypted = Vec::new();
1504        let mut tmp = [0u8; 8192];
1505        loop {
1506            match self.client.reader().read(&mut tmp) {
1507                Ok(0) => break,
1508                Ok(n) => decrypted.extend_from_slice(&tmp[..n]),
1509                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
1510                Err(_) => break,
1511            }
1512        }
1513        if !decrypted.is_empty() {
1514            let _ = self.server.writer().write_all(&decrypted);
1515        }
1516
1517        let mut to_upstream = Vec::new();
1518        while self.client.wants_write() {
1519            let _ = self.client.write_tls(&mut to_upstream);
1520        }
1521        let mut to_guest = Vec::new();
1522        while self.server.wants_write() {
1523            let _ = self.server.write_tls(&mut to_guest);
1524        }
1525
1526        Ok(MitmStep {
1527            to_guest,
1528            to_upstream,
1529            decrypted,
1530        })
1531    }
1532
1533    /// Flush TLS close_notify when the guest closes write half.
1534    pub fn on_guest_eof(&mut self) -> Vec<u8> {
1535        self.client.send_close_notify();
1536        let mut to_upstream = Vec::new();
1537        while self.client.wants_write() {
1538            let _ = self.client.write_tls(&mut to_upstream);
1539        }
1540        to_upstream
1541    }
1542
1543    /// Flush TLS close_notify when upstream closes.
1544    pub fn on_upstream_eof(&mut self) -> Vec<u8> {
1545        self.server.send_close_notify();
1546        let mut to_guest = Vec::new();
1547        while self.server.wants_write() {
1548            let _ = self.server.write_tls(&mut to_guest);
1549        }
1550        to_guest
1551    }
1552}
1553
1554#[cfg(test)]
1555mod tests {
1556    use super::*;
1557    use wasmtime::{Config, Engine, MemoryType};
1558
1559    fn make_tls13_record(
1560        cipher: CipherKind,
1561        secret: &[u8],
1562        seq: u64,
1563        inner_ct: u8,
1564        pt: &[u8],
1565    ) -> Vec<u8> {
1566        let key_bytes = tls13_hkdf_expand_label(cipher, secret, b"key", cipher.key_len());
1567        let iv_vec = tls13_hkdf_expand_label(cipher, secret, b"iv", 12);
1568        let mut iv = [0u8; 12];
1569        iv.copy_from_slice(&iv_vec[..12]);
1570        let mut body = pt.to_vec();
1571        body.push(inner_ct);
1572        let total_len = (body.len() + 16) as u16;
1573        let hdr = [0x17, 0x03, 0x03, (total_len >> 8) as u8, total_len as u8];
1574        let unbound = UnboundKey::new(cipher.aead_alg(), &key_bytes).unwrap();
1575        let aead_key = LessSafeKey::new(unbound);
1576        aead_key
1577            .seal_in_place_append_tag(
1578                Nonce::assume_unique_for_key(xor_iv_seq(&iv, seq)),
1579                Aad::from(&hdr[..]),
1580                &mut body,
1581            )
1582            .unwrap();
1583        let mut rec = Vec::with_capacity(5 + body.len());
1584        rec.extend_from_slice(&hdr);
1585        rec.extend_from_slice(&body);
1586        rec
1587    }
1588
1589    #[test]
1590    fn vmi_tls13_recovers_client_and_server_secrets_from_shared_memory() {
1591        let mut wt_cfg = Config::new();
1592        wt_cfg.wasm_threads(true);
1593        wt_cfg.shared_memory(true);
1594        let engine = Engine::new(&wt_cfg).unwrap();
1595        let mem = SharedMemory::new(&engine, MemoryType::shared(2, 2)).unwrap();
1596
1597        let client_random: [u8; 32] =
1598            std::array::from_fn(|i| (i as u8).wrapping_mul(7).wrapping_add(1));
1599        let client_secret: [u8; 32] =
1600            std::array::from_fn(|i| (i as u8).wrapping_mul(13).wrapping_add(3));
1601        let server_secret: [u8; 32] =
1602            std::array::from_fn(|i| (i as u8).wrapping_mul(17).wrapping_add(9));
1603
1604        // Simulate an OpenSSL SSL_CONNECTION struct in guest RAM holding client_random + traffic secrets
1605        let data = mem.data();
1606        let write_mem = |addr: usize, src: &[u8]| {
1607            for (i, &b) in src.iter().enumerate() {
1608                unsafe { AtomicU8::from_ptr(data[addr + i].get()).store(b, Ordering::Relaxed) };
1609            }
1610        };
1611        write_mem(0x4000, &client_random);
1612        write_mem(0x4120, &client_secret);
1613        write_mem(0x4160, &server_secret);
1614
1615        let ctx = VmiTlsContext::new(mem, 2 * 65536, None);
1616        let mut insp = VmiTlsInspector::new(ctx);
1617
1618        // Feed synthetic ClientHello + ServerHello (TLS 1.3 AES-128-GCM)
1619        let mut ch = vec![
1620            0x16, 0x03, 0x01, 0x00, 0x2a, 0x01, 0x00, 0x00, 0x26, 0x03, 0x03,
1621        ];
1622        ch.extend_from_slice(&client_random);
1623        ch.extend_from_slice(&[0, 0, 2, 0x13, 0x01, 1, 0]);
1624        let ch_len = (ch.len() - 5) as u16;
1625        ch[3..5].copy_from_slice(&ch_len.to_be_bytes());
1626        assert!(insp.observe_tx(&ch).is_empty());
1627
1628        let mut sh = vec![
1629            0x16, 0x03, 0x03, 0x00, 0x30, 0x02, 0x00, 0x00, 0x2c, 0x03, 0x03,
1630        ];
1631        sh.extend_from_slice(&[0xaa; 32]); // server_random
1632        sh.push(0); // sid_len
1633        sh.extend_from_slice(&0x1301u16.to_be_bytes()); // TLS_AES_128_GCM_SHA256
1634        sh.push(0); // compression
1635        sh.extend_from_slice(&[0x00, 0x06, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04]); // supported_versions=TLS1.3
1636        let sh_len = (sh.len() - 5) as u16;
1637        sh[3..5].copy_from_slice(&sh_len.to_be_bytes());
1638        assert!(insp.observe_rx(&sh).is_empty());
1639
1640        // Feed encrypted client HTTP GET + encrypted server HTTP 200 OK
1641        let tx_rec = make_tls13_record(
1642            CipherKind::Aes128GcmSha256,
1643            &client_secret,
1644            0,
1645            0x17,
1646            b"GET /secret?tok=canary HTTP/1.1\r\nHost: exfil.test\r\n\r\n",
1647        );
1648        let tx_plain = insp.observe_tx(&tx_rec);
1649        assert_eq!(tx_plain.len(), 1);
1650        assert!(String::from_utf8_lossy(&tx_plain[0]).contains("GET /secret?tok=canary"));
1651
1652        let rx_rec = make_tls13_record(
1653            CipherKind::Aes128GcmSha256,
1654            &server_secret,
1655            0,
1656            0x17,
1657            b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nPONG",
1658        );
1659        let rx_plain = insp.observe_rx(&rx_rec);
1660        assert_eq!(rx_plain.len(), 1);
1661        assert!(String::from_utf8_lossy(&rx_plain[0]).contains("PONG"));
1662    }
1663
1664    #[test]
1665    fn find_aes_detects_valid_aes128_schedule() {
1666        // FIPS-197 Appendix A.1 AES-128 test key
1667        let key: [u8; 16] = [
1668            0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
1669            0x4f, 0x3c,
1670        ];
1671        let mut w = [0u32; 44];
1672        for i in 0..4 {
1673            w[i] = u32::from_be_bytes(key[4 * i..4 * (i + 1)].try_into().unwrap());
1674        }
1675        for i in 4..44 {
1676            let mut t = w[i - 1];
1677            if i % 4 == 0 {
1678                t = aes_sub_word(t.rotate_left(8)) ^ AES_RCON[(i / 4) - 1];
1679            }
1680            w[i] = w[i - 4] ^ t;
1681        }
1682        let mut mem = vec![0u8; 4096];
1683        for (i, word) in w.iter().enumerate() {
1684            mem[512 + i * 4..512 + (i + 1) * 4].copy_from_slice(&word.to_le_bytes());
1685        }
1686        let found = scan_aes_key_schedules(&mem, 16);
1687        assert_eq!(found.len(), 1);
1688        assert_eq!(found[0].0, 512);
1689        assert_eq!(found[0].1.as_slice(), &key);
1690    }
1691
1692    #[test]
1693    fn mitm_ca_and_sans_io_handshake_decrypts_traffic() {
1694        let ca = MitmCa::generate(true).expect("generate MITM CA");
1695        assert!(ca.ca_cert_pem().contains("BEGIN CERTIFICATE"));
1696
1697        // Build a guest client trusting the ephemeral MITM CA
1698        let mut guest_roots = RootCertStore::empty();
1699        guest_roots.add(ca.ca_cert_der.clone()).unwrap();
1700        let provider = Arc::new(rustls::crypto::ring::default_provider());
1701        let guest_cfg = Arc::new(
1702            ClientConfig::builder_with_provider(provider.clone())
1703                .with_safe_default_protocol_versions()
1704                .unwrap()
1705                .with_root_certificates(guest_roots)
1706                .with_no_client_auth(),
1707        );
1708        let mut guest = ClientConnection::new(
1709            guest_cfg,
1710            ServerName::try_from("demo.lab.local".to_string()).unwrap(),
1711        )
1712        .unwrap();
1713
1714        // Build an upstream TLS server with its own independent self-signed cert
1715        let up_key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1716        let up_cert = CertificateParams::new(vec!["demo.lab.local".to_string()])
1717            .unwrap()
1718            .self_signed(&up_key)
1719            .unwrap();
1720        let up_srv_cfg = Arc::new(
1721            ServerConfig::builder_with_provider(provider)
1722                .with_safe_default_protocol_versions()
1723                .unwrap()
1724                .with_no_client_auth()
1725                .with_single_cert(
1726                    vec![CertificateDer::from(up_cert.der().to_vec())],
1727                    PrivateKeyDer::try_from(up_key.serialize_der()).unwrap(),
1728                )
1729                .unwrap(),
1730        );
1731        let mut upstream = ServerConnection::new(up_srv_cfg).unwrap();
1732
1733        let mut mitm = ca.start_session("demo.lab.local").unwrap();
1734
1735        guest
1736            .writer()
1737            .write_all(b"POST /exfil HTTP/1.1\r\nHost: demo.lab.local\r\n\r\nSECRET=abc")
1738            .unwrap();
1739
1740        let mut seen_tx = Vec::new();
1741        let mut seen_rx = Vec::new();
1742        let mut upstream_replied = false;
1743
1744        for _ in 0..16 {
1745            let mut g2m = Vec::new();
1746            while guest.wants_write() {
1747                guest.write_tls(&mut g2m).unwrap();
1748            }
1749            if !g2m.is_empty() {
1750                let step = mitm.on_guest_tx(&g2m).unwrap();
1751                seen_tx.extend_from_slice(&step.decrypted);
1752                if !step.to_guest.is_empty() {
1753                    let mut c = Cursor::new(&step.to_guest);
1754                    while (c.position() as usize) < step.to_guest.len() {
1755                        guest.read_tls(&mut c).unwrap();
1756                        guest.process_new_packets().unwrap();
1757                    }
1758                }
1759                if !step.to_upstream.is_empty() {
1760                    let mut c = Cursor::new(&step.to_upstream);
1761                    while (c.position() as usize) < step.to_upstream.len() {
1762                        upstream.read_tls(&mut c).unwrap();
1763                        upstream.process_new_packets().unwrap();
1764                    }
1765                }
1766            }
1767
1768            let mut up_plain = Vec::new();
1769            let mut tmp = [0u8; 1024];
1770            while let Ok(n) = upstream.reader().read(&mut tmp) {
1771                if n == 0 {
1772                    break;
1773                }
1774                up_plain.extend_from_slice(&tmp[..n]);
1775            }
1776            if !up_plain.is_empty() && !upstream_replied {
1777                upstream_replied = true;
1778                upstream
1779                    .writer()
1780                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
1781                    .unwrap();
1782            }
1783
1784            let mut u2m = Vec::new();
1785            while upstream.wants_write() {
1786                upstream.write_tls(&mut u2m).unwrap();
1787            }
1788            if !u2m.is_empty() {
1789                let step = mitm.on_upstream_rx(&u2m).unwrap();
1790                seen_rx.extend_from_slice(&step.decrypted);
1791                if !step.to_upstream.is_empty() {
1792                    let mut c = Cursor::new(&step.to_upstream);
1793                    while (c.position() as usize) < step.to_upstream.len() {
1794                        upstream.read_tls(&mut c).unwrap();
1795                        upstream.process_new_packets().unwrap();
1796                    }
1797                }
1798                if !step.to_guest.is_empty() {
1799                    let mut c = Cursor::new(&step.to_guest);
1800                    while (c.position() as usize) < step.to_guest.len() {
1801                        guest.read_tls(&mut c).unwrap();
1802                        guest.process_new_packets().unwrap();
1803                    }
1804                }
1805            }
1806        }
1807
1808        assert!(String::from_utf8_lossy(&seen_tx).contains("SECRET=abc"));
1809        assert!(String::from_utf8_lossy(&seen_rx).contains("HTTP/1.1 200 OK"));
1810    }
1811
1812    #[test]
1813    fn vmi_tls13_pass3_recovers_split_heap_secrets_without_client_random_for_chacha20() {
1814        let mut wt_cfg = Config::new();
1815        wt_cfg.wasm_threads(true);
1816        wt_cfg.shared_memory(true);
1817        let engine = Engine::new(&wt_cfg).unwrap();
1818        let mem = SharedMemory::new(&engine, MemoryType::shared(4, 4)).unwrap();
1819
1820        let client_random: [u8; 32] =
1821            std::array::from_fn(|i| (i as u8).wrapping_mul(11).wrapping_add(5));
1822        // High-entropy secrets placed on separate Go-style 32-byte aligned pages, with NO client_random in RAM!
1823        let client_secret: [u8; 32] =
1824            std::array::from_fn(|i| (i as u8).wrapping_mul(37).wrapping_add(0x83));
1825        let server_secret: [u8; 32] =
1826            std::array::from_fn(|i| (i as u8).wrapping_mul(53).wrapping_add(0x41));
1827
1828        let data = mem.data();
1829        let write_mem = |addr: usize, src: &[u8]| {
1830            for (i, &b) in src.iter().enumerate() {
1831                unsafe { AtomicU8::from_ptr(data[addr + i].get()).store(b, Ordering::Relaxed) };
1832            }
1833        };
1834        write_mem(0x1_2040, &client_secret); // 32B-aligned
1835        write_mem(0x3_4080, &server_secret); // distant 32B-aligned page (>128 KiB away!)
1836
1837        let ctx = VmiTlsContext::new(mem, 4 * 65536, None);
1838        let mut insp = VmiTlsInspector::new(ctx);
1839
1840        let mut ch = vec![
1841            0x16, 0x03, 0x01, 0x00, 0x2a, 0x01, 0x00, 0x00, 0x26, 0x03, 0x03,
1842        ];
1843        ch.extend_from_slice(&client_random);
1844        ch.extend_from_slice(&[0, 0, 2, 0x13, 0x03, 1, 0]);
1845        let ch_len = (ch.len() - 5) as u16;
1846        ch[3..5].copy_from_slice(&ch_len.to_be_bytes());
1847        insp.observe_tx(&ch);
1848
1849        let mut sh = vec![
1850            0x16, 0x03, 0x03, 0x00, 0x30, 0x02, 0x00, 0x00, 0x2c, 0x03, 0x03,
1851        ];
1852        sh.extend_from_slice(&[0xbb; 32]);
1853        sh.push(0);
1854        sh.extend_from_slice(&0x1303u16.to_be_bytes()); // TLS_CHACHA20_POLY1305_SHA256
1855        sh.push(0);
1856        sh.extend_from_slice(&[0x00, 0x06, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04]);
1857        let sh_len = (sh.len() - 5) as u16;
1858        sh[3..5].copy_from_slice(&sh_len.to_be_bytes());
1859        insp.observe_rx(&sh);
1860
1861        let tx_rec = make_tls13_record(
1862            CipherKind::ChaCha20Poly1305Sha256,
1863            &client_secret,
1864            0,
1865            0x17,
1866            b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n",
1867        );
1868        let tx_plain = insp.observe_tx(&tx_rec);
1869        assert_eq!(tx_plain.len(), 1);
1870        assert_eq!(tx_plain[0], b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
1871
1872        let rx_rec = make_tls13_record(
1873            CipherKind::ChaCha20Poly1305Sha256,
1874            &server_secret,
1875            1, // simulate 1 NewSessionTicket before AppData
1876            0x17,
1877            b"GO_CHACHA20_RX_OK",
1878        );
1879        let rx_plain = insp.observe_rx(&rx_rec);
1880        assert_eq!(rx_plain.len(), 1);
1881        assert_eq!(rx_plain[0], b"GO_CHACHA20_RX_OK");
1882    }
1883}