Skip to main content

guise_echo/
lib.rs

1//! Local TLS echo service for inspecting our own wire fingerprints.
2//!
3//! `guise-echo` terminates TLS 1.3 locally, parses the client's raw ClientHello
4//! with `tls-parser`, computes JA3/JA4 via `guise::fingerprint::ja3`, and
5//! returns the result as JSON over HTTP/1.1. It exists so the stealth stack can
6//! inspect its own Layer-2 bytes without relying on third-party reflectors.
7//!
8//! Layers:
9//!   * TLS ClientHello capture (JA3/JA4, ALPN, SNI, extensions)
10//!   * HTTP/2 preface + SETTINGS/WINDOW_UPDATE/PRIORITY frame capture
11//!   * TCP TTL/options read (`tcp::read_host_tcp_info`)
12//!
13//! The service intentionally does not implement a full HTTP/2 server; it only
14//! reads the connection preface and the first control frames so the stealth
15//! stack can verify that its emitted H2 fingerprint matches a real browser.
16
17use std::net::SocketAddr;
18use std::pin::Pin;
19use std::sync::Arc;
20use std::task::{Context, Poll};
21
22use anyhow::{bail, Context as _};
23use rustls::pki_types::pem::PemObject;
24use rustls::pki_types::{CertificateDer, PrivateKeyDer};
25use rustls::ServerConfig;
26use serde::{Deserialize, Serialize};
27use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
28use tokio::net::{TcpListener, TcpStream};
29use tokio_rustls::TlsAcceptor;
30
31pub mod tcp;
32pub use tcp::{read_host_tcp_info, TcpConnectionInfo};
33
34pub use serde_json::Value as JsonValue;
35
36/// Parsed TLS ClientHello metadata + computed fingerprints.
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct ClientHelloInfo {
39    /// TLS legacy version field.
40    pub legacy_version: u16,
41    /// Cipher suites, in client order.
42    pub cipher_suites: Vec<u16>,
43    /// TLS extension type ids, in client order.
44    pub extensions: Vec<u16>,
45    /// Supported elliptic-curve / named groups.
46    pub supported_groups: Vec<u16>,
47    /// EC point formats.
48    pub ec_point_formats: Vec<u8>,
49    /// ALPN protocols, in client order (raw wire bytes).
50    pub alpn: Vec<Vec<u8>>,
51    /// Signature algorithms, in client order.
52    pub signature_algorithms: Vec<u16>,
53    /// TLS versions from the `supported_versions` extension (0x002b).
54    pub supported_versions: Vec<u16>,
55    /// Computed JA3 string.
56    pub ja3: String,
57    /// Computed JA4 string.
58    pub ja4: String,
59    /// SNI hostname, if present (raw wire bytes).
60    pub sni: Option<Vec<u8>>,
61}
62
63/// Captured HTTP/2 connection-level information from the client preface and
64/// first control frames.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct H2ConnectionInfo {
67    /// Whether the client sent the magic `PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n` preface.
68    pub preface_seen: bool,
69    /// SETTINGS id/value pairs, in arrival order.
70    pub settings: Vec<H2Setting>,
71    /// WINDOW_INCREMENT values from WINDOW_UPDATE frames on the connection
72    /// stream (stream id 0).
73    pub window_updates: Vec<u32>,
74    /// PRIORITY frames captured before the first request.
75    pub priorities: Vec<H2Priority>,
76    /// The negotiated ALPN protocol that triggered H2 frame reading (raw bytes).
77    pub negotiated_protocol: Option<Vec<u8>>,
78    /// Capture error string if reading preface/frames stopped due to a protocol error.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub error: Option<String>,
81}
82
83/// A single HTTP/2 SETTINGS parameter.
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct H2Setting {
86    pub id: u16,
87    pub value: u32,
88}
89
90/// A single HTTP/2 PRIORITY frame.
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct H2Priority {
93    pub stream_id: u32,
94    pub exclusive: bool,
95    pub dependency: u32,
96    pub weight: u8,
97}
98
99/// Combined fingerprint info returned by the echo endpoint.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct ConnectionInfo {
102    pub tls: ClientHelloInfo,
103    pub h2: Option<H2ConnectionInfo>,
104    pub tcp: TcpConnectionInfo,
105}
106
107/// Run the echo server on `bind` until the process is killed.
108pub async fn serve(bind: SocketAddr) -> anyhow::Result<()> {
109    let tls_config = Arc::new(server_config()?);
110    let listener = TcpListener::bind(bind).await?;
111    tracing::info!("guise-echo listening on {bind}");
112
113    loop {
114        let (stream, peer) = listener.accept().await?;
115        let cfg = tls_config.clone();
116        tokio::spawn(async move {
117            if let Err(e) = handle_connection(stream, cfg).await {
118                tracing::debug!(%peer, "connection closed with error: {e:#}");
119            }
120        });
121    }
122}
123
124/// Accept a single TCP connection, parse its TLS ClientHello, complete the
125/// handshake, and echo the parsed fingerprint as JSON. Exposed for tests that
126/// want to drive the server side without binding a listening socket.
127pub async fn accept_one_for_test(stream: TcpStream) -> anyhow::Result<ConnectionInfo> {
128    let tls_config = Arc::new(server_config()?);
129    handle_connection(stream, tls_config).await
130}
131
132async fn handle_connection(
133    stream: TcpStream,
134    tls_config: Arc<ServerConfig>,
135) -> anyhow::Result<ConnectionInfo> {
136    let (tls_info, buffered) = read_and_parse_client_hello(stream).await?;
137
138    let acceptor = TlsAcceptor::from(tls_config);
139    let mut tls_stream = acceptor.accept(buffered).await?;
140
141    let h2_info = read_h2_info_if_negotiated(&mut tls_stream).await?;
142    let tcp_info = read_host_tcp_info();
143
144    let info = ConnectionInfo {
145        tls: tls_info,
146        h2: h2_info,
147        tcp: tcp_info,
148    };
149
150    let body = serde_json::to_vec(&info)?;
151    let response = format!(
152        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
153        body.len()
154    );
155    tls_stream.write_all(response.as_bytes()).await?;
156    tls_stream.write_all(&body).await?;
157    tls_stream.shutdown().await?;
158    Ok(info)
159}
160
161/// If the TLS handshake negotiated `h2`, read and parse the HTTP/2 connection
162/// preface and the first control frames. Non-fatal parse errors are logged and
163/// surfaced in the returned struct so tests can see partial data.
164async fn read_h2_info_if_negotiated<S>(
165    tls_stream: &mut tokio_rustls::server::TlsStream<S>,
166) -> anyhow::Result<Option<H2ConnectionInfo>>
167where
168    S: AsyncRead + AsyncWrite + Unpin,
169{
170    let negotiated = tls_stream.get_ref().1.alpn_protocol().map(|p| p.to_vec());
171
172    if negotiated.as_deref() != Some(b"h2".as_slice()) {
173        return Ok(None);
174    }
175
176    let mut h2 = H2ConnectionInfo {
177        preface_seen: false,
178        settings: Vec::new(),
179        window_updates: Vec::new(),
180        priorities: Vec::new(),
181        negotiated_protocol: negotiated,
182        error: None,
183    };
184
185    // Read the fixed 24-byte preface, then the first few control frames.
186    match read_h2_preface_and_frames(tls_stream, &mut h2).await {
187        Ok(()) => Ok(Some(h2)),
188        Err(e) => {
189            tracing::debug!("H2 frame capture stopped: {e:#}");
190            h2.error = Some(e.to_string());
191            Ok(Some(h2))
192        }
193    }
194}
195
196/// Read the first TLS record from `stream`, parse the ClientHello, and return
197/// both the parsed info and a stream that has the consumed bytes prepended so
198/// `tokio-rustls` can complete the handshake.
199async fn read_and_parse_client_hello(
200    mut stream: TcpStream,
201) -> anyhow::Result<(ClientHelloInfo, BufferedStream<TcpStream>)> {
202    // Read the 5-byte record header directly. `peek` was avoided on purpose:
203    // a single peek guarantees only one byte, so a client (or middlebox) that
204    // fragments the header across TCP segments could leave the length bytes
205    // zeroed and the record length below would be garbage. `read_exact` waits
206    // for the full header without busy-polling.
207    let mut record = vec![0u8; 5];
208    stream
209        .read_exact(&mut record)
210        .await
211        .context("read TLS record header")?;
212    if record[0] != 0x16 {
213        bail!(
214            "first byte is 0x{:02x}, expected 0x16 (handshake record)",
215            record[0]
216        );
217    }
218    let record_len = u16::from_be_bytes([record[3], record[4]]) as usize;
219    if record_len > 1 << 14 {
220        bail!("TLS record length {record_len} exceeds maximum fragment size");
221    }
222
223    record.resize(5 + record_len, 0);
224    stream
225        .read_exact(&mut record[5..])
226        .await
227        .context("read TLS ClientHello record")?;
228
229    let info = parse_client_hello(&record).context("parse ClientHello")?;
230    let buffered = BufferedStream::new(record, stream);
231    Ok((info, buffered))
232}
233
234fn parse_client_hello(record: &[u8]) -> anyhow::Result<ClientHelloInfo> {
235    use tls_parser::{TlsExtension, TlsMessage, TlsMessageHandshake};
236
237    let (rem, parsed) = tls_parser::parse_tls_plaintext(record)
238        .map_err(|e| anyhow::anyhow!("tls-parser failed: {e:?}"))?;
239    if !rem.is_empty() {
240        bail!(
241            "trailing unparsed bytes ({}) in TLS record payload",
242            rem.len()
243        );
244    }
245    if parsed.msg.len() != 1 {
246        bail!(
247            "TLS record payload contains {} messages, expected exactly 1",
248            parsed.msg.len()
249        );
250    }
251
252    let ch = match &parsed.msg[0] {
253        TlsMessage::Handshake(TlsMessageHandshake::ClientHello(ch)) => ch,
254        other => bail!("expected ClientHello, got {other:?}"),
255    };
256    let cipher_suites: Vec<u16> = ch.ciphers.iter().map(|c| c.0).collect();
257
258    let ext_bytes = ch.ext.unwrap_or(&[]);
259    let (rem_ext, parsed_exts) = tls_parser::parse_tls_extensions(ext_bytes)
260        .map_err(|e| anyhow::anyhow!("tls-parser extensions failed: {e:?}"))?;
261    if !rem_ext.is_empty() {
262        bail!(
263            "trailing unparsed bytes ({}) in TLS extensions",
264            rem_ext.len()
265        );
266    }
267
268    let mut seen_exts = std::collections::HashSet::new();
269    for ext in &parsed_exts {
270        let ext_type = u16::from(tls_parser::TlsExtensionType::from(ext));
271        if !seen_exts.insert(ext_type) {
272            bail!("duplicate TLS extension type 0x{ext_type:04x} in ClientHello");
273        }
274    }
275
276    let mut alpn = Vec::new();
277    let mut supported_versions = Vec::new();
278    let mut signature_algorithms = Vec::new();
279    let mut supported_groups = Vec::new();
280    let mut ec_point_formats = Vec::new();
281    let mut sni = None;
282
283    let extensions: Vec<u16> = parsed_exts
284        .iter()
285        .map(|ext| u16::from(tls_parser::TlsExtensionType::from(ext)))
286        .collect();
287
288    for ext in &parsed_exts {
289        match ext {
290            TlsExtension::ALPN(protocols) => {
291                alpn.extend(protocols.iter().map(|p| p.to_vec()));
292            }
293            TlsExtension::SupportedVersions(versions) => {
294                supported_versions.extend(versions.iter().map(|v| v.0));
295            }
296            TlsExtension::SignatureAlgorithms(algorithms) => {
297                signature_algorithms.extend(algorithms.iter().copied());
298            }
299            TlsExtension::EllipticCurves(groups) => {
300                supported_groups.extend(groups.iter().map(|g| g.0));
301            }
302            TlsExtension::EcPointFormats(formats) => {
303                ec_point_formats.extend(formats.iter().copied());
304            }
305            TlsExtension::SNI(entries) => {
306                if let Some((_, hostname)) = entries.first() {
307                    sni = Some(hostname.to_vec());
308                }
309            }
310            _ => {}
311        }
312    }
313
314    let fields = guise::fingerprint::ja3::ClientHelloFields {
315        version: ch.version.0,
316        cipher_suites: cipher_suites.clone(),
317        extensions: extensions.clone(),
318        supported_groups: supported_groups.clone(),
319        ec_point_formats: ec_point_formats.clone(),
320        alpn: alpn.clone(),
321        signature_algorithms: signature_algorithms.clone(),
322        supported_versions: supported_versions.clone(),
323    };
324
325    let ja3 = guise::fingerprint::ja3::compute_ja3(&fields);
326    let ja4 = guise::fingerprint::ja3::compute_ja4(&fields);
327
328    Ok(ClientHelloInfo {
329        legacy_version: ch.version.0,
330        cipher_suites,
331        extensions,
332        supported_groups,
333        ec_point_formats,
334        alpn,
335        signature_algorithms,
336        supported_versions,
337        ja3,
338        ja4,
339        sni,
340    })
341}
342
343/// Read the HTTP/2 connection preface and parse the first SETTINGS,
344/// WINDOW_UPDATE, and PRIORITY frames sent by the client.
345///
346/// We stop after a small byte/frame budget so a misbehaving client cannot keep
347/// this diagnostic service open indefinitely.
348async fn read_h2_preface_and_frames<S>(
349    stream: &mut S,
350    info: &mut H2ConnectionInfo,
351) -> anyhow::Result<()>
352where
353    S: AsyncRead + Unpin,
354{
355    const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
356    const MAX_FRAME_BYTES: usize = 16_384;
357    const MAX_FRAMES: usize = 32;
358
359    let mut preface_buf = vec![0u8; PREFACE.len()];
360    let _ = stream
361        .read_exact(&mut preface_buf)
362        .await
363        .context("read H2 preface")?;
364    if preface_buf != PREFACE {
365        bail!("invalid H2 preface");
366    }
367    info.preface_seen = true;
368
369    for _ in 0..MAX_FRAMES {
370        let mut header = [0u8; 9];
371        match AsyncReadExt::read_exact(&mut *stream, &mut header).await {
372            Ok(_) => {}
373            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
374            Err(e) => return Err(e.into()),
375        }
376
377        let length = u32::from_be_bytes([0, header[0], header[1], header[2]]) as usize;
378        let frame_type = header[3];
379        let flags = header[4];
380        let stream_id =
381            u32::from_be_bytes([header[5], header[6], header[7], header[8]]) & 0x7fff_ffff;
382
383        if length > MAX_FRAME_BYTES {
384            bail!("H2 frame length {length} exceeds limit");
385        }
386
387        // A SETTINGS frame with the ACK flag ends the mandatory exchange.
388        if frame_type == 0x04 && (flags & 0x01) != 0 {
389            if length != 0 {
390                bail!("SETTINGS ACK frame length must be 0, got {length}");
391            }
392            break;
393        }
394
395        if frame_type == 0x04 && stream_id != 0 {
396            bail!("SETTINGS frame stream ID must be 0, got {stream_id}");
397        }
398
399        if frame_type == 0x02 && stream_id == 0 {
400            bail!("PRIORITY frame stream ID must not be 0");
401        }
402
403        if matches!(frame_type, 0x00 | 0x01 | 0x09) {
404            // Stop reading once we see a request-bearing frame (DATA, HEADERS, CONTINUATION).
405            break;
406        }
407
408        let payload = if length > 0 {
409            let mut buf = vec![0u8; length];
410            let _ = stream
411                .read_exact(&mut buf)
412                .await
413                .context("read H2 frame payload")?;
414            buf
415        } else {
416            Vec::new()
417        };
418
419        match frame_type {
420            0x04 => parse_h2_settings(&payload, info)?,
421            0x08 => parse_h2_window_update(stream_id, &payload, info)?,
422            0x02 => parse_h2_priority(stream_id, &payload, info)?,
423            _ => {}
424        }
425    }
426
427    Ok(())
428}
429
430fn parse_h2_settings(payload: &[u8], info: &mut H2ConnectionInfo) -> anyhow::Result<()> {
431    if !payload.len().is_multiple_of(6) {
432        bail!(
433            "SETTINGS payload length {} is not a multiple of 6",
434            payload.len()
435        );
436    }
437    let mut seen_ids = std::collections::HashSet::new();
438    for chunk in payload.chunks_exact(6) {
439        let id = u16::from_be_bytes([chunk[0], chunk[1]]);
440        let value = u32::from_be_bytes([chunk[2], chunk[3], chunk[4], chunk[5]]);
441        if !seen_ids.insert(id) {
442            bail!("duplicate SETTINGS parameter ID {id} in SETTINGS frame");
443        }
444        info.settings.push(H2Setting { id, value });
445    }
446    Ok(())
447}
448
449fn parse_h2_window_update(
450    stream_id: u32,
451    payload: &[u8],
452    info: &mut H2ConnectionInfo,
453) -> anyhow::Result<()> {
454    if payload.len() != 4 {
455        bail!(
456            "WINDOW_UPDATE payload must be 4 bytes, got {}",
457            payload.len()
458        );
459    }
460    let increment =
461        u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) & 0x7fff_ffff;
462    if increment == 0 {
463        bail!("WINDOW_UPDATE increment is zero");
464    }
465    // Capture connection-level window updates (stream id 0) and request-stream
466    // updates so the fingerprint is complete.
467    info.window_updates.push(increment);
468    let _ = stream_id; // kept for future per-stream accounting
469    Ok(())
470}
471
472fn parse_h2_priority(
473    stream_id: u32,
474    payload: &[u8],
475    info: &mut H2ConnectionInfo,
476) -> anyhow::Result<()> {
477    if payload.len() != 5 {
478        bail!("PRIORITY payload must be 5 bytes, got {}", payload.len());
479    }
480    let dependency = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
481    let exclusive = (dependency & 0x8000_0000) != 0;
482    let dependency = dependency & 0x7fff_ffff;
483    if dependency == stream_id {
484        bail!("PRIORITY frame stream {stream_id} cannot depend on itself");
485    }
486    let weight = payload[4];
487    info.priorities.push(H2Priority {
488        stream_id,
489        exclusive,
490        dependency,
491        weight,
492    });
493    Ok(())
494}
495
496fn ensure_crypto_provider() {
497    // Rustls 0.23 cannot auto-select a crypto provider when both `ring` and
498    // `aws-lc-rs` are present in the dependency graph. We pin the ring provider
499    // explicitly and ignore the already-installed error on repeated calls.
500    let _ = rustls::crypto::ring::default_provider().install_default();
501}
502
503fn server_config() -> anyhow::Result<ServerConfig> {
504    ensure_crypto_provider();
505    let cert = include_bytes!("cert.pem").to_vec();
506    let key = include_bytes!("key.pem").to_vec();
507
508    let certs: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(&cert)
509        .collect::<Result<Vec<_>, _>>()
510        .context("parse cert.pem")?;
511    let key = PrivateKeyDer::pem_slice_iter(&key)
512        .next()
513        .transpose()
514        .context("parse key.pem")?
515        .context("key.pem contains no PKCS#8 private key")?;
516
517    let mut config = ServerConfig::builder()
518        .with_no_client_auth()
519        .with_single_cert(certs, key)
520        .context("build rustls server config")?;
521    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
522    Ok(config)
523}
524
525/// A stream that first yields a buffered prefix, then delegates to an inner
526/// stream. Used to let `tokio-rustls` complete a TLS handshake after we have
527/// already consumed and parsed the ClientHello bytes.
528struct BufferedStream<S> {
529    prefix: Vec<u8>,
530    position: usize,
531    inner: S,
532}
533
534impl<S> BufferedStream<S> {
535    fn new(prefix: Vec<u8>, inner: S) -> Self {
536        Self {
537            prefix,
538            position: 0,
539            inner,
540        }
541    }
542}
543
544impl<S: AsyncRead + Unpin> AsyncRead for BufferedStream<S> {
545    fn poll_read(
546        mut self: Pin<&mut Self>,
547        cx: &mut Context<'_>,
548        buf: &mut ReadBuf<'_>,
549    ) -> Poll<std::io::Result<()>> {
550        if self.position < self.prefix.len() {
551            let remaining = self.prefix.len() - self.position;
552            let to_copy = remaining.min(buf.remaining());
553            buf.put_slice(&self.prefix[self.position..self.position + to_copy]);
554            self.position += to_copy;
555            Poll::Ready(Ok(()))
556        } else {
557            Pin::new(&mut self.inner).poll_read(cx, buf)
558        }
559    }
560}
561
562impl<S: AsyncWrite + Unpin> AsyncWrite for BufferedStream<S> {
563    fn poll_write(
564        mut self: Pin<&mut Self>,
565        cx: &mut Context<'_>,
566        buf: &[u8],
567    ) -> Poll<std::io::Result<usize>> {
568        Pin::new(&mut self.inner).poll_write(cx, buf)
569    }
570
571    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
572        Pin::new(&mut self.inner).poll_flush(cx)
573    }
574
575    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
576        Pin::new(&mut self.inner).poll_shutdown(cx)
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    #[test]
585    fn buffered_stream_yields_prefix_then_inner() {
586        // A simple synchronous smoke test for the AsyncRead behaviour via a
587        // tokio runtime: the prefix is returned before the inner stream.
588        let rt = tokio::runtime::Runtime::new().unwrap();
589        rt.block_on(async {
590            let prefix = b"hello ";
591            let inner: &[u8] = b"world";
592            let mut stream = BufferedStream::new(prefix.to_vec(), inner);
593            let mut out = Vec::new();
594            tokio::io::AsyncReadExt::read_to_end(&mut stream, &mut out)
595                .await
596                .unwrap();
597            assert_eq!(out, b"hello world");
598        });
599    }
600
601    /// A minimal but well-formed TLS 1.2-era ClientHello record offering one
602    /// cipher suite (0x1301) and no extensions.
603    fn minimal_client_hello_record() -> Vec<u8> {
604        let mut body = Vec::new();
605        body.extend_from_slice(&[0x03, 0x03]); // legacy version
606        body.extend_from_slice(&[0x42; 32]); // random
607        body.push(0); // session id length
608        body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); // cipher suites
609        body.extend_from_slice(&[0x01, 0x00]); // compression methods
610        body.extend_from_slice(&[0x00, 0x00]); // extensions length
611        let mut handshake = vec![0x01];
612        handshake.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]);
613        handshake.extend_from_slice(&body);
614        let mut record = vec![0x16, 0x03, 0x01];
615        record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
616        record.extend_from_slice(&handshake);
617        record
618    }
619
620    /// Regression: the ClientHello reader peeked the 5-byte record header
621    /// with a single `TcpStream::peek`, which guarantees only ONE byte. A
622    /// peer that fragments the header across TCP segments left the length
623    /// bytes zeroed, so the reader computed a garbage record length and the
624    /// capture failed (or misaligned the stream for the TLS handshake that
625    /// reuses those bytes). The reader must wait for the complete header.
626    #[tokio::test]
627    async fn client_hello_reader_tolerates_fragmented_record_header() {
628        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
629        let addr = listener.local_addr().unwrap();
630        let record = minimal_client_hello_record();
631
632        let client = tokio::spawn(async move {
633            let mut conn = TcpStream::connect(addr).await.unwrap();
634            // Dribble the header: two bytes, a pause, then the rest.
635            conn.write_all(&record[..2]).await.unwrap();
636            conn.flush().await.unwrap();
637            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
638            conn.write_all(&record[2..]).await.unwrap();
639            conn.flush().await.unwrap();
640            // Keep the connection open until the server is done reading.
641            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
642        });
643
644        let (stream, _) = listener.accept().await.unwrap();
645        let (info, _buffered) = read_and_parse_client_hello(stream)
646            .await
647            .expect("fragmented record header must still parse");
648        assert_eq!(info.cipher_suites, vec![0x1301]);
649        client.await.unwrap();
650    }
651
652    /// Regression: the H2 capture loop checked the empty-payload fast path
653    /// BEFORE the SETTINGS-ACK terminator. A SETTINGS ACK is required to be
654    /// empty (RFC 9113 §6.5), so it always took the `continue` path and the
655    /// ACK never ended the capture: frames after the ACK were wrongly
656    /// attributed to the connection preface fingerprint.
657    #[tokio::test]
658    async fn h2_capture_stops_at_settings_ack() {
659        let mut bytes = Vec::new();
660        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
661        // SETTINGS, one entry (id=1, value=4096).
662        bytes.extend_from_slice(&[0x00, 0x00, 0x06, 0x04, 0x00]);
663        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
664        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x00, 0x10, 0x00]);
665        // SETTINGS ACK (empty, flags=0x1).
666        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, 0x01]);
667        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
668        // A WINDOW_UPDATE after the ACK must NOT be captured.
669        bytes.extend_from_slice(&[0x00, 0x00, 0x04, 0x08, 0x00]);
670        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
671        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x01]);
672
673        let mut cursor: &[u8] = &bytes;
674        let mut info = H2ConnectionInfo {
675            preface_seen: false,
676            settings: Vec::new(),
677            window_updates: Vec::new(),
678            priorities: Vec::new(),
679            negotiated_protocol: None,
680            error: None,
681        };
682        read_h2_preface_and_frames(&mut cursor, &mut info)
683            .await
684            .expect("preface and frames parse");
685        assert!(info.preface_seen);
686        assert_eq!(info.settings.len(), 1);
687        assert_eq!(info.settings[0].id, 1);
688        assert_eq!(info.settings[0].value, 4096);
689        assert!(
690            info.window_updates.is_empty(),
691            "frames after the SETTINGS ACK must not be captured"
692        );
693    }
694    #[tokio::test]
695    async fn h2_capture_stops_at_empty_data_frame() {
696        let mut bytes = Vec::new();
697        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
698        // Empty DATA frame (len=0, type=0, flags=1 END_STREAM, stream_id=1).
699        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x01]);
700        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
701        // Following frame after empty DATA frame must be ignored.
702        bytes.extend_from_slice(&[0x00, 0x00, 0x04, 0x08, 0x00]);
703        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
704        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x01]);
705
706        let mut cursor: &[u8] = &bytes;
707        let mut info = H2ConnectionInfo {
708            preface_seen: false,
709            settings: Vec::new(),
710            window_updates: Vec::new(),
711            priorities: Vec::new(),
712            negotiated_protocol: None,
713            error: None,
714        };
715        read_h2_preface_and_frames(&mut cursor, &mut info)
716            .await
717            .expect("preface and empty DATA frame parse");
718        assert!(info.preface_seen);
719        assert!(info.window_updates.is_empty());
720    }
721
722    #[tokio::test]
723    async fn h2_rejects_invalid_settings_ack_length() {
724        let mut bytes = Vec::new();
725        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
726        // SETTINGS ACK with length=1 (invalid per RFC 9113 §6.5).
727        bytes.extend_from_slice(&[0x00, 0x00, 0x01, 0x04, 0x01]);
728        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
729        bytes.push(0x00);
730
731        let mut cursor: &[u8] = &bytes;
732        let mut info = H2ConnectionInfo {
733            preface_seen: false,
734            settings: Vec::new(),
735            window_updates: Vec::new(),
736            priorities: Vec::new(),
737            negotiated_protocol: None,
738            error: None,
739        };
740        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
741            .await
742            .unwrap_err();
743        assert!(err
744            .to_string()
745            .contains("SETTINGS ACK frame length must be 0"));
746    }
747
748    #[tokio::test]
749    async fn h2_rejects_settings_frame_with_nonzero_stream_id() {
750        let mut bytes = Vec::new();
751        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
752        // SETTINGS with stream_id=1 (invalid per RFC 9113 §6.5).
753        bytes.extend_from_slice(&[0x00, 0x00, 0x06, 0x04, 0x00]);
754        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
755        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x00, 0x10, 0x00]);
756
757        let mut cursor: &[u8] = &bytes;
758        let mut info = H2ConnectionInfo {
759            preface_seen: false,
760            settings: Vec::new(),
761            window_updates: Vec::new(),
762            priorities: Vec::new(),
763            negotiated_protocol: None,
764            error: None,
765        };
766        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
767            .await
768            .unwrap_err();
769        assert!(err
770            .to_string()
771            .contains("SETTINGS frame stream ID must be 0"));
772    }
773
774    #[tokio::test]
775    async fn h2_rejects_priority_frame_with_zero_stream_id() {
776        let mut bytes = Vec::new();
777        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
778        // PRIORITY with stream_id=0 (invalid per RFC 9113 §6.2).
779        bytes.extend_from_slice(&[0x00, 0x00, 0x05, 0x02, 0x00]);
780        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
781        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x10]);
782
783        let mut cursor: &[u8] = &bytes;
784        let mut info = H2ConnectionInfo {
785            preface_seen: false,
786            settings: Vec::new(),
787            window_updates: Vec::new(),
788            priorities: Vec::new(),
789            negotiated_protocol: None,
790            error: None,
791        };
792        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
793            .await
794            .unwrap_err();
795        assert!(err
796            .to_string()
797            .contains("PRIORITY frame stream ID must not be 0"));
798    }
799
800    #[test]
801    fn client_hello_rejects_trailing_bytes_in_extensions() {
802        let mut body = Vec::new();
803        body.extend_from_slice(&[0x03, 0x03]); // legacy version
804        body.extend_from_slice(&[0x42; 32]); // random
805        body.push(0); // session id length
806        body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); // cipher suites
807        body.extend_from_slice(&[0x01, 0x00]); // compression methods
808                                               // Extension block length 5: SNI extension header (4 bytes) + 1 trailing byte 0xff
809        body.extend_from_slice(&[0x00, 0x05]);
810        body.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0xff]);
811
812        let mut handshake = vec![0x01];
813        handshake.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]);
814        handshake.extend_from_slice(&body);
815        let mut record = vec![0x16, 0x03, 0x01];
816        record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
817        record.extend_from_slice(&handshake);
818
819        let err = parse_client_hello(&record).unwrap_err();
820        assert!(err.to_string().contains("trailing unparsed bytes"));
821    }
822    #[tokio::test]
823    async fn h2_rejects_zero_length_window_update() {
824        let mut bytes = Vec::new();
825        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
826        // WINDOW_UPDATE with length=0 (invalid per RFC 9113 §6.9).
827        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x08, 0x00]);
828        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
829
830        let mut cursor: &[u8] = &bytes;
831        let mut info = H2ConnectionInfo {
832            preface_seen: false,
833            settings: Vec::new(),
834            window_updates: Vec::new(),
835            priorities: Vec::new(),
836            negotiated_protocol: None,
837            error: None,
838        };
839        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
840            .await
841            .unwrap_err();
842        assert!(err
843            .to_string()
844            .contains("WINDOW_UPDATE payload must be 4 bytes, got 0"));
845    }
846
847    #[tokio::test]
848    async fn h2_rejects_zero_length_priority() {
849        let mut bytes = Vec::new();
850        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
851        // PRIORITY with length=0 (invalid per RFC 9113 §6.3).
852        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x02, 0x00]);
853        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
854
855        let mut cursor: &[u8] = &bytes;
856        let mut info = H2ConnectionInfo {
857            preface_seen: false,
858            settings: Vec::new(),
859            window_updates: Vec::new(),
860            priorities: Vec::new(),
861            negotiated_protocol: None,
862            error: None,
863        };
864        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
865            .await
866            .unwrap_err();
867        assert!(err
868            .to_string()
869            .contains("PRIORITY payload must be 5 bytes, got 0"));
870    }
871
872    #[tokio::test]
873    async fn h2_rejects_duplicate_settings_parameter() {
874        let mut bytes = Vec::new();
875        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
876        // SETTINGS frame with duplicate ID 1.
877        bytes.extend_from_slice(&[0x00, 0x00, 0x0c, 0x04, 0x00]);
878        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
879        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x00, 0x10, 0x00]);
880        bytes.extend_from_slice(&[0x00, 0x01, 0x00, 0x00, 0x20, 0x00]);
881
882        let mut cursor: &[u8] = &bytes;
883        let mut info = H2ConnectionInfo {
884            preface_seen: false,
885            settings: Vec::new(),
886            window_updates: Vec::new(),
887            priorities: Vec::new(),
888            negotiated_protocol: None,
889            error: None,
890        };
891        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
892            .await
893            .unwrap_err();
894        assert!(err
895            .to_string()
896            .contains("duplicate SETTINGS parameter ID 1"));
897    }
898
899    #[tokio::test]
900    async fn h2_rejects_self_dependent_priority() {
901        let mut bytes = Vec::new();
902        bytes.extend_from_slice(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
903        // PRIORITY frame on stream 1 depending on stream 1.
904        bytes.extend_from_slice(&[0x00, 0x00, 0x05, 0x02, 0x00]);
905        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
906        bytes.extend_from_slice(&[0x00, 0x00, 0x00, 0x01, 0x10]);
907
908        let mut cursor: &[u8] = &bytes;
909        let mut info = H2ConnectionInfo {
910            preface_seen: false,
911            settings: Vec::new(),
912            window_updates: Vec::new(),
913            priorities: Vec::new(),
914            negotiated_protocol: None,
915            error: None,
916        };
917        let err = read_h2_preface_and_frames(&mut cursor, &mut info)
918            .await
919            .unwrap_err();
920        assert!(err
921            .to_string()
922            .contains("PRIORITY frame stream 1 cannot depend on itself"));
923    }
924
925    #[test]
926    fn client_hello_rejects_duplicate_extension_types() {
927        let mut body = Vec::new();
928        body.extend_from_slice(&[0x03, 0x03]); // legacy version
929        body.extend_from_slice(&[0x42; 32]); // random
930        body.push(0); // session id length
931        body.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); // cipher suites
932        body.extend_from_slice(&[0x01, 0x00]); // compression methods
933                                               // Extension block: two supported_versions extensions (0x002b)
934        body.extend_from_slice(&[0x00, 0x0e]);
935        body.extend_from_slice(&[0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04]);
936        body.extend_from_slice(&[0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04]);
937
938        let mut handshake = vec![0x01];
939        handshake.extend_from_slice(&(body.len() as u32).to_be_bytes()[1..]);
940        handshake.extend_from_slice(&body);
941        let mut record = vec![0x16, 0x03, 0x01];
942        record.extend_from_slice(&(handshake.len() as u16).to_be_bytes());
943        record.extend_from_slice(&handshake);
944
945        let err = parse_client_hello(&record).unwrap_err();
946        assert!(err
947            .to_string()
948            .contains("duplicate TLS extension type 0x002b"));
949    }
950}