rustgate-proxy 0.2.0

MITM-capable HTTP/HTTPS proxy with WebSocket C2 tunneling (SOCKS5, reverse TCP)
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
use crate::cert::CertificateAuthority;
use crate::error::ProxyError;
use crate::handler::{boxed_body, BoxBody, RequestHandler};
use crate::tls;
use bytes::Bytes;
use http_body_util::{BodyExt, Empty, Full};
use hyper::client::conn::http1 as client_http1;
use hyper::server::conn::http1 as server_http1;
use hyper::service::service_fn;
use hyper::upgrade::Upgraded;
use hyper::{Method, Request, Response};
use hyper_util::rt::TokioIo;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpStream;
use tracing::{debug, error, info, warn};

/// Shared state passed to each connection handler.
pub struct ProxyState {
    pub ca: Arc<CertificateAuthority>,
    pub mitm: bool,
    pub handler: Arc<dyn RequestHandler>,
}

/// Handle a single accepted TCP connection.
pub async fn handle_connection(
    stream: TcpStream,
    addr: SocketAddr,
    state: Arc<ProxyState>,
) {
    debug!("New connection from {addr}");

    let io = TokioIo::new(stream);
    let state = state.clone();

    let service = service_fn(move |req: Request<hyper::body::Incoming>| {
        let state = state.clone();
        async move { handle_request(req, state).await }
    });

    if let Err(e) = server_http1::Builder::new()
        .preserve_header_case(true)
        .title_case_headers(true)
        .serve_connection(io, service)
        .with_upgrades()
        .await
    {
        if !e.to_string().contains("early eof")
            && !e.to_string().contains("connection closed")
        {
            error!("Connection error from {addr}: {e}");
        }
    }
}

/// Route a request: CONNECT goes to tunnel/MITM, everything else gets forwarded.
async fn handle_request(
    req: Request<hyper::body::Incoming>,
    state: Arc<ProxyState>,
) -> Result<Response<BoxBody>, hyper::Error> {
    if req.method() == Method::CONNECT {
        handle_connect(req, state).await
    } else {
        handle_forward(req, state).await
    }
}

// ─── HTTP Forwarding ───────────────────────────────────────────────────────────

/// Forward a plain HTTP request to the upstream server.
async fn handle_forward(
    req: Request<hyper::body::Incoming>,
    state: Arc<ProxyState>,
) -> Result<Response<BoxBody>, hyper::Error> {
    let uri = req.uri().clone();
    let host = match uri.host() {
        Some(h) => h.to_string(),
        None => {
            warn!("Request with no host: {uri}");
            return Ok(bad_request("Missing host in URI"));
        }
    };
    let port = uri.port_u16().unwrap_or(80);
    let addr = format!("{host}:{port}");

    // Build the request to forward (path-only URI, strip hop-by-hop headers)
    let (mut parts, body) = req.into_parts();
    let path = parts
        .uri
        .path_and_query()
        .map(|pq| pq.as_str())
        .unwrap_or("/");
    parts.uri = match path.parse() {
        Ok(uri) => uri,
        Err(_) => {
            warn!("Invalid path: {path}");
            return Ok(bad_request("Invalid request URI"));
        }
    };
    strip_hop_by_hop_headers(&mut parts.headers);

    let mut forwarded_req = Request::from_parts(parts, boxed_body(body));

    // Let the handler inspect/modify the request
    state.handler.handle_request(&mut forwarded_req);

    // Connect to upstream
    let upstream = match TcpStream::connect(&addr).await {
        Ok(s) => s,
        Err(e) => {
            error!("Failed to connect to {addr}: {e}");
            return Ok(bad_gateway(&format!("Failed to connect to {addr}")));
        }
    };

    let io = TokioIo::new(upstream);
    let (mut sender, conn) = match client_http1::handshake(io).await {
        Ok(r) => r,
        Err(e) => {
            error!("Handshake with {addr} failed: {e}");
            return Ok(bad_gateway("Upstream handshake failed"));
        }
    };

    tokio::spawn(async move {
        if let Err(e) = conn.await {
            error!("Upstream connection error: {e}");
        }
    });

    match sender.send_request(forwarded_req).await {
        Ok(res) => {
            let (parts, body) = res.into_parts();
            let mut response = Response::from_parts(parts, boxed_body(body));
            state.handler.handle_response(&mut response);
            Ok(response)
        }
        Err(e) => {
            error!("Upstream request failed: {e}");
            Ok(bad_gateway("Upstream request failed"))
        }
    }
}

// ─── CONNECT Handling ──────────────────────────────────────────────────────────

/// Handle a CONNECT request: either tunnel (passthrough) or MITM.
async fn handle_connect(
    req: Request<hyper::body::Incoming>,
    state: Arc<ProxyState>,
) -> Result<Response<BoxBody>, hyper::Error> {
    let target = match req.uri().authority() {
        Some(auth) => auth.to_string(),
        None => {
            warn!("CONNECT without authority");
            return Ok(bad_request("CONNECT target missing"));
        }
    };

    let (host, port) = parse_host_port(&target);
    let addr = format!("{host}:{port}");

    info!("CONNECT {target}");

    if state.mitm {
        // MITM mode: intercept the TLS connection
        handle_mitm(req, host, addr, state).await
    } else {
        // Passthrough mode: just tunnel bytes
        handle_tunnel(req, addr).await
    }
}

/// Passthrough tunneling: bidirectional copy between client and upstream.
async fn handle_tunnel(
    req: Request<hyper::body::Incoming>,
    addr: String,
) -> Result<Response<BoxBody>, hyper::Error> {
    tokio::spawn(async move {
        match hyper::upgrade::on(req).await {
            Ok(upgraded) => {
                if let Err(e) = tunnel_bidirectional(upgraded, &addr).await {
                    error!("Tunnel error to {addr}: {e}");
                }
            }
            Err(e) => {
                error!("Upgrade failed: {e}");
            }
        }
    });

    // Respond with 200 to tell the client the tunnel is established
    Ok(Response::new(empty_body()))
}

/// Copy data bidirectionally between the upgraded client connection and upstream.
async fn tunnel_bidirectional(
    upgraded: Upgraded,
    addr: &str,
) -> crate::error::Result<()> {
    let mut upstream = TcpStream::connect(addr).await?;

    let mut client = TokioIo::new(upgraded);

    let (client_to_server, server_to_client) =
        tokio::io::copy_bidirectional(&mut client, &mut upstream).await?;

    debug!(
        "Tunnel closed: {addr} (client→server: {client_to_server}B, server→client: {server_to_client}B)"
    );
    Ok(())
}

/// MITM mode: terminate TLS with both ends, intercept HTTP traffic.
async fn handle_mitm(
    req: Request<hyper::body::Incoming>,
    host: String,
    addr: String,
    state: Arc<ProxyState>,
) -> Result<Response<BoxBody>, hyper::Error> {
    let state = state.clone();

    tokio::spawn(async move {
        match hyper::upgrade::on(req).await {
            Ok(upgraded) => {
                if let Err(e) =
                    mitm_intercept(upgraded, &host, &addr, state).await
                {
                    error!("MITM error for {host}: {e}");
                }
            }
            Err(e) => {
                error!("MITM upgrade failed: {e}");
            }
        }
    });

    Ok(Response::new(empty_body()))
}

/// Perform MITM interception on an upgraded connection.
async fn mitm_intercept(
    upgraded: Upgraded,
    host: &str,
    addr: &str,
    state: Arc<ProxyState>,
) -> crate::error::Result<()> {
    // Create a TLS acceptor with a fake cert for this domain
    let acceptor = tls::make_tls_acceptor(&state.ca, host).await?;

    // Accept TLS from the client side
    let client_io = TokioIo::new(upgraded);
    let client_tls = acceptor
        .accept(client_io)
        .await
        .map_err(|e| ProxyError::Other(format!("Client TLS accept failed: {e}")))?;

    let client_tls = TokioIo::new(client_tls);

    // Serve HTTP on the decrypted client stream
    let host = host.to_string();
    let addr = addr.to_string();

    let service = service_fn(move |req: Request<hyper::body::Incoming>| {
        let host = host.clone();
        let addr = addr.clone();
        let state = state.clone();
        async move {
            mitm_forward_request(req, &host, &addr, state).await
        }
    });

    if let Err(e) = server_http1::Builder::new()
        .preserve_header_case(true)
        .title_case_headers(true)
        .serve_connection(client_tls, service)
        .await
    {
        if !e.to_string().contains("early eof")
            && !e.to_string().contains("connection closed")
        {
            debug!("MITM connection closed: {e}");
        }
    }

    Ok(())
}

/// Forward a request from the MITM-decrypted stream to the real upstream over TLS.
async fn mitm_forward_request(
    req: Request<hyper::body::Incoming>,
    host: &str,
    addr: &str,
    state: Arc<ProxyState>,
) -> Result<Response<BoxBody>, hyper::Error> {
    let (mut parts, body) = req.into_parts();
    strip_hop_by_hop_headers(&mut parts.headers);

    let mut forwarded_req = Request::from_parts(parts, boxed_body(body));

    // Let the handler inspect/modify
    state.handler.handle_request(&mut forwarded_req);

    // Connect to upstream over TLS
    let upstream_tls = match tls::connect_tls_upstream(host, addr).await {
        Ok(s) => s,
        Err(e) => {
            error!("Failed TLS connect to {addr}: {e}");
            return Ok(bad_gateway(&format!(
                "Failed to connect to upstream: {e}"
            )));
        }
    };

    let io = TokioIo::new(upstream_tls);
    let (mut sender, conn) = match client_http1::handshake(io).await {
        Ok(r) => r,
        Err(e) => {
            error!("Upstream TLS handshake failed: {e}");
            return Ok(bad_gateway("Upstream TLS handshake failed"));
        }
    };

    tokio::spawn(async move {
        if let Err(e) = conn.await {
            debug!("Upstream TLS connection closed: {e}");
        }
    });

    match sender.send_request(forwarded_req).await {
        Ok(res) => {
            let (parts, body) = res.into_parts();
            let mut response = Response::from_parts(parts, boxed_body(body));
            state.handler.handle_response(&mut response);
            Ok(response)
        }
        Err(e) => {
            error!("Upstream TLS request failed: {e}");
            Ok(bad_gateway("Upstream request failed"))
        }
    }
}

// ─── Helpers ───────────────────────────────────────────────────────────────────

/// Hop-by-hop headers that should not be forwarded.
const HOP_BY_HOP_HEADERS: &[&str] = &[
    "connection",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "te",
    "trailers",
    "transfer-encoding",
    "upgrade",
];

/// Parse host and port from a CONNECT target, handling IPv6 bracket notation.
/// e.g. "example.com:443", "[::1]:443", "example.com"
pub fn parse_host_port(target: &str) -> (String, u16) {
    if let Some(bracketed) = target.strip_prefix('[') {
        // IPv6: [::1]:port
        if let Some((ip6, rest)) = bracketed.split_once(']') {
            let port = rest
                .strip_prefix(':')
                .and_then(|p| p.parse().ok())
                .unwrap_or(443);
            return (ip6.to_string(), port);
        }
    }
    // IPv4 / hostname: host:port
    if let Some((host, port_str)) = target.rsplit_once(':') {
        if let Ok(port) = port_str.parse::<u16>() {
            return (host.to_string(), port);
        }
    }
    (target.to_string(), 443)
}

fn strip_hop_by_hop_headers(headers: &mut hyper::HeaderMap) {
    // Also remove headers listed in the Connection header value
    if let Some(conn_val) = headers.get("connection").cloned() {
        if let Ok(val) = conn_val.to_str() {
            for name in val.split(',') {
                let name = name.trim();
                if !name.is_empty() {
                    headers.remove(name);
                }
            }
        }
    }

    for name in HOP_BY_HOP_HEADERS {
        headers.remove(*name);
    }
}

fn empty_body() -> BoxBody {
    Empty::<Bytes>::new()
        .map_err(|never| match never {})
        .boxed()
}

fn bad_request(msg: &str) -> Response<BoxBody> {
    Response::builder()
        .status(400)
        .body(full_body(msg))
        .unwrap()
}

fn bad_gateway(msg: &str) -> Response<BoxBody> {
    Response::builder()
        .status(502)
        .body(full_body(msg))
        .unwrap()
}

fn full_body(msg: &str) -> BoxBody {
    Full::new(Bytes::from(msg.to_string()))
        .map_err(|never| match never {})
        .boxed()
}