soth-mitm 0.2.0

Rust intercepting proxy crate with deterministic handler/event contracts for SOTH.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use super::close_codes::{CloseReasonCode, ParseFailureCode};
use super::event_emitters::{emit_connect_parse_failed, emit_stream_closed, unknown_context};
use super::event_emitters_protocol::emit_http3_passthrough_event;
use super::flow_connect_tunnel_support::{flow_action_label, parse_http3_passthrough_hint};
use super::flow_forward_proxy_http1::handle_forward_http1_proxy_request;
use super::flow_forward_proxy_http1_helpers::{
    is_forward_http1_request_candidate, is_self_listener_target,
};
use super::flow_intercept::intercept_http_connection;
use super::flow_policy_snapshot::{clear_flow_policy_snapshot, resolve_flow_policy_snapshot};
use super::http_body_relay::write_proxy_response;
use super::http_head_parser::read_connect_head;
use super::io_timeouts::{
    copy_bidirectional_with_websocket_idle_timeout, is_idle_watchdog_timeout,
    is_stream_stage_timeout, write_all_with_idle_timeout,
};
use super::route_planner_model::{FlowRoutePlanner, RouteBinding, RouteConnectIntent, RouteTarget};
use super::route_planner_transport::connect_via_route;
use super::RuntimeHandles;
use crate::engine::{parse_connect_request_head_with_mode, ConnectParseError, MitmEngine};
use crate::observe::{EventConsumer, FlowContext};
use crate::policy::{FlowAction, PolicyEngine};
use crate::protocol::ApplicationProtocol;
use crate::types::ProcessInfo;
use std::io;
use std::sync::Arc;
use tokio::net::TcpStream;

pub(crate) async fn handle_client<P, S>(
    runtime: RuntimeHandles<P, S>,
    downstream: TcpStream,
    client_addr: String,
    flow_id: crate::types::FlowId,
    process_info: Option<ProcessInfo>,
    max_connect_head_bytes: usize,
    max_http_head_bytes: usize,
    flow_guard: &mut crate::server::runtime_governor::FlowRuntimeGuard,
) -> io::Result<()>
where
    P: PolicyEngine + Send + Sync + 'static,
    S: EventConsumer + Send + Sync + 'static,
{
    let close_context = unknown_context(flow_id, client_addr.clone());
    let engine_instance_id = runtime.engine.instance_id();
    let flow_hooks = Arc::clone(&runtime.flow_hooks);
    let result = handle_client_inner(
        runtime,
        downstream,
        client_addr,
        flow_id,
        process_info,
        max_connect_head_bytes,
        max_http_head_bytes,
        flow_guard,
    )
    .await;
    clear_flow_policy_snapshot(engine_instance_id, flow_id);
    flow_hooks.on_stream_end(close_context).await;
    result
}

async fn handle_client_inner<P, S>(
    runtime: RuntimeHandles<P, S>,
    mut downstream: TcpStream,
    client_addr: String,
    flow_id: crate::types::FlowId,
    process_info: Option<ProcessInfo>,
    max_connect_head_bytes: usize,
    max_http_head_bytes: usize,
    flow_guard: &mut crate::server::runtime_governor::FlowRuntimeGuard,
) -> io::Result<()>
where
    P: PolicyEngine + Send + Sync + 'static,
    S: EventConsumer + Send + Sync + 'static,
{
    let engine = Arc::clone(&runtime.engine);
    let cert_store = Arc::clone(&runtime.cert_store);
    let runtime_governor = Arc::clone(&runtime.runtime_governor);
    let tls_diagnostics = Arc::clone(&runtime.tls_diagnostics);
    let tls_learning = Arc::clone(&runtime.tls_learning);
    let flow_hooks = Arc::clone(&runtime.flow_hooks);
    let upstream_tls_cache = Arc::clone(&runtime.upstream_tls_cache);
    let listener_addr = downstream.local_addr().ok();

    let mut input =
        match read_connect_head(&mut downstream, max_connect_head_bytes, &runtime_governor).await {
            Ok(parsed) => parsed,
            Err(error) => {
                let parse_code = match error.kind() {
                    io::ErrorKind::UnexpectedEof => ParseFailureCode::IncompleteHeaders,
                    io::ErrorKind::InvalidData => ParseFailureCode::HeaderTooLarge,
                    _ => ParseFailureCode::ReadError,
                };

                let context = unknown_context(flow_id, client_addr);

                emit_connect_parse_failed(
                    &engine,
                    context.clone(),
                    parse_code,
                    Some(error.to_string()),
                );
                emit_stream_closed(
                    &engine,
                    context,
                    CloseReasonCode::ConnectParseFailed,
                    Some(format!("{}: {error}", parse_code.as_str())),
                    None,
                    None,
                );

                if error.kind() != io::ErrorKind::UnexpectedEof {
                    let status = if parse_code == ParseFailureCode::HeaderTooLarge {
                        "431 Request Header Fields Too Large"
                    } else {
                        "400 Bad Request"
                    };
                    write_proxy_response(
                        &mut downstream,
                        status,
                        "invalid or incomplete CONNECT request",
                    )
                    .await?;
                }
                return Ok(());
            }
        };

    let (connect, header_len) =
        match parse_connect_request_head_with_mode(&input, engine.config.connect_parse_mode) {
            Ok(parsed) => parsed,
            Err(ConnectParseError::MethodNotConnect)
                if is_forward_http1_request_candidate(&input) =>
            {
                return handle_forward_http1_proxy_request(
                    engine,
                    runtime_governor,
                    flow_hooks,
                    downstream,
                    client_addr,
                    flow_id,
                    process_info.clone(),
                    input,
                    max_http_head_bytes,
                    listener_addr,
                    Some(flow_guard),
                )
                .await;
            }
            Err(parse_error) => {
                let context = unknown_context(flow_id, client_addr);
                emit_connect_parse_failed(
                    &engine,
                    context.clone(),
                    ParseFailureCode::Parser(parse_error),
                    None,
                );
                emit_stream_closed(
                    &engine,
                    context,
                    CloseReasonCode::ConnectParseFailed,
                    Some(parse_error.code().to_string()),
                    None,
                    None,
                );
                write_proxy_response(
                    &mut downstream,
                    "400 Bad Request",
                    "invalid CONNECT request",
                )
                .await?;
                return Ok(());
            }
        };

    let (listen_addr, listen_port) = listener_addr
        .map(|addr| (addr.ip().to_string(), addr.port()))
        .unwrap_or_else(|| (engine.config.listen_addr.clone(), engine.config.listen_port));

    if is_self_listener_target(
        &connect.server_host,
        connect.server_port,
        &listen_addr,
        listen_port,
    ) {
        let context = FlowContext {
            flow_id,
            client_addr,
            server_host: connect.server_host,
            server_port: connect.server_port,
            protocol: ApplicationProtocol::Tunnel,
        };
        write_proxy_response(
            &mut downstream,
            "508 Loop Detected",
            "proxy CONNECT target resolves to listener itself",
        )
        .await?;
        emit_stream_closed(
            &engine,
            context,
            CloseReasonCode::RoutePlannerFailed,
            Some(format!(
                "connect self-target loop detected: listener {listen_addr}:{listen_port}"
            )),
            None,
            None,
        );
        return Ok(());
    }

    let mut route_planner = FlowRoutePlanner::default();
    let route = match route_planner.bind_once(
        &engine.config,
        RouteTarget::new(connect.server_host.clone(), connect.server_port, None),
    ) {
        Ok(binding) => binding,
        Err(error) => {
            let context = FlowContext {
                flow_id,
                client_addr,
                server_host: connect.server_host,
                server_port: connect.server_port,
                protocol: ApplicationProtocol::Tunnel,
            };
            write_proxy_response(
                &mut downstream,
                "502 Bad Gateway",
                "route planner failed for CONNECT target",
            )
            .await?;
            emit_stream_closed(
                &engine,
                context,
                CloseReasonCode::RoutePlannerFailed,
                Some(error.to_string()),
                None,
                None,
            );
            return Ok(());
        }
    };

    let policy_snapshot = resolve_flow_policy_snapshot(
        &engine,
        flow_id,
        client_addr.clone(),
        route.target_host.clone(),
        route.target_port,
        route.policy_path.clone(),
        process_info.clone(),
    );

    let context = FlowContext {
        flow_id: policy_snapshot.flow_id,
        client_addr,
        server_host: route.target_host.clone(),
        server_port: route.target_port,
        protocol: ApplicationProtocol::Tunnel,
    };

    let http3_requested_by = if engine.config.http3_passthrough {
        parse_http3_passthrough_hint(&input[..header_len])
    } else {
        None
    };
    if let Some(requested_by) = http3_requested_by {
        if policy_snapshot.action != FlowAction::Block {
            emit_http3_passthrough_event(
                &engine,
                context.clone(),
                requested_by,
                flow_action_label(policy_snapshot.action),
            );
        }
    }
    let mut action = if http3_requested_by.is_some() && policy_snapshot.action != FlowAction::Block
    {
        FlowAction::Tunnel
    } else {
        policy_snapshot.action
    };
    if action == FlowAction::Intercept
        && !flow_hooks
            .should_intercept_tls(context.clone(), process_info.clone())
            .await
    {
        action = FlowAction::Tunnel;
    }

    match action {
        FlowAction::Block => {
            flow_guard.release_permit();
            write_proxy_response(&mut downstream, "403 Forbidden", &policy_snapshot.reason).await?;
            emit_stream_closed(
                &engine,
                context,
                CloseReasonCode::Blocked,
                Some(policy_snapshot.reason),
                None,
                None,
            );
            Ok(())
        }
        FlowAction::Tunnel => {
            // Release the intercept permit — tunnel connections are blind
            // byte-copy and don't use the detect/classify pipeline.
            flow_guard.release_permit();
            tunnel_connection(
                engine,
                context,
                route,
                &mut downstream,
                &mut input,
                header_len,
            )
            .await
        }
        FlowAction::Intercept => {
            intercept_http_connection(
                engine,
                cert_store,
                runtime_governor,
                tls_diagnostics,
                tls_learning,
                flow_hooks,
                upstream_tls_cache,
                context,
                process_info,
                route,
                policy_snapshot.override_state,
                downstream,
                max_http_head_bytes,
            )
            .await
        }
    }
}

async fn tunnel_connection<P, S>(
    engine: Arc<MitmEngine<P, S>>,
    context: FlowContext,
    route: RouteBinding,
    downstream: &mut TcpStream,
    input: &mut [u8],
    header_len: usize,
) -> io::Result<()>
where
    P: PolicyEngine + Send + Sync + 'static,
    S: EventConsumer + Send + Sync + 'static,
{
    let mut upstream = match connect_via_route(&route, RouteConnectIntent::TargetTunnel).await {
        Ok(stream) => stream,
        Err(error) => {
            let detail = format!(
                "upstream_connect_failed[{}]: {error}",
                route.route_mode_label()
            );
            write_proxy_response(downstream, "502 Bad Gateway", &detail).await?;
            emit_stream_closed(
                &engine,
                context,
                CloseReasonCode::UpstreamConnectFailed,
                Some(error.to_string()),
                None,
                None,
            );
            return Ok(());
        }
    };

    write_all_with_idle_timeout(
        downstream,
        b"HTTP/1.1 200 Connection Established\r\n\r\n",
        "connect_tunnel_established_write",
    )
    .await?;

    let buffered_client_data = &input[header_len..];
    if !buffered_client_data.is_empty() {
        write_all_with_idle_timeout(
            &mut upstream,
            buffered_client_data,
            "connect_tunnel_prefetch_write",
        )
        .await?;
    }

    match copy_bidirectional_with_websocket_idle_timeout(downstream, &mut upstream).await {
        Ok((from_client, from_server)) => {
            // Tunneled flows are blind TCP passthrough — no body inspection,
            // no buffering, no budget.  Always report clean EOF.
            emit_stream_closed(
                &engine,
                context,
                CloseReasonCode::RelayEof,
                None,
                Some(from_client),
                Some(from_server),
            );
            Ok(())
        }
        Err(error) => {
            let reason = if is_idle_watchdog_timeout(&error) {
                CloseReasonCode::IdleWatchdogTimeout
            } else if is_stream_stage_timeout(&error) {
                CloseReasonCode::StreamStageTimeout
            } else {
                CloseReasonCode::RelayError
            };
            emit_stream_closed(
                &engine,
                context,
                reason,
                Some(error.to_string()),
                None,
                None,
            );
            Err(error)
        }
    }
}

#[cfg(test)]
mod flow_connect_tunnel_tests {
    use super::parse_http3_passthrough_hint;

    #[test]
    fn detects_http3_passthrough_via_proxy_protocol_hint() {
        let head = b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\nX-Proxy-Protocol: h3\r\n\r\n";
        assert_eq!(parse_http3_passthrough_hint(head), Some("x-proxy-protocol"));
    }

    #[test]
    fn detects_http3_passthrough_via_boolean_flag_hint() {
        let head = b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\nX-HTTP3-Passthrough: yes\r\n\r\n";
        assert_eq!(
            parse_http3_passthrough_hint(head),
            Some("x-http3-passthrough")
        );
    }

    #[test]
    fn does_not_accept_vendor_specific_legacy_hint_headers() {
        let head = b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\nX-Soth-Proxy-Protocol: h3\r\n\r\n";
        assert_eq!(parse_http3_passthrough_hint(head), None);
    }
}