http_mitm_proxy/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use http_body_util::{BodyExt, Empty, combinators::BoxBody};
4use hyper::{
5    Method, Request, Response, StatusCode,
6    body::{Body, Incoming},
7    server,
8    service::{HttpService, service_fn},
9};
10use hyper_util::rt::{TokioExecutor, TokioIo};
11use moka::sync::Cache;
12use std::{borrow::Borrow, error::Error as StdError, future::Future, sync::Arc};
13use tls::{CertifiedKeyDer, generate_cert};
14use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
15use tokio_rustls::rustls;
16
17pub use futures;
18pub use hyper;
19pub use moka;
20
21#[cfg(feature = "native-tls-client")]
22pub use tokio_native_tls;
23
24#[cfg(any(feature = "native-tls-client", feature = "rustls-client"))]
25pub mod default_client;
26mod tls;
27
28#[cfg(any(feature = "native-tls-client", feature = "rustls-client"))]
29pub use default_client::DefaultClient;
30
31#[derive(Clone, Copy, Debug)]
32pub struct RemoteAddr(pub std::net::SocketAddr);
33
34#[derive(Clone)]
35/// The main struct to run proxy server
36pub struct MitmProxy<I> {
37    /// Root issuer to sign fake certificates. You may need to trust this issuer on client application to use HTTPS.
38    ///
39    /// If None, proxy will just tunnel HTTPS traffic and will not observe HTTPS traffic.
40    pub root_issuer: Option<I>,
41    /// Cache to store generated certificates. If None, cache will not be used.
42    /// If root_issuer is None, cache will not be used.
43    ///
44    /// The key of cache is hostname.
45    pub cert_cache: Option<Cache<String, CertifiedKeyDer>>,
46}
47
48impl<I> MitmProxy<I> {
49    /// Create a new MitmProxy
50    pub fn new(root_issuer: Option<I>, cache: Option<Cache<String, CertifiedKeyDer>>) -> Self {
51        Self {
52            root_issuer,
53            cert_cache: cache,
54        }
55    }
56}
57
58impl<I> MitmProxy<I>
59where
60    I: Borrow<rcgen::Issuer<'static, rcgen::KeyPair>> + Send + Sync + 'static,
61{
62    /// Bind to a socket address and return a future that runs the proxy server.
63    /// URL for requests that passed to service are full URL including scheme.
64    /// remote address of client is stored in request extensions as `RemoteAddr`.
65    pub async fn bind<A: ToSocketAddrs, S>(
66        self,
67        addr: A,
68        service: S,
69    ) -> Result<impl Future<Output = ()>, std::io::Error>
70    where
71        S: HttpService<Incoming> + Clone + Send + 'static,
72        S::Error: Into<Box<dyn StdError + Send + Sync>>,
73        S::ResBody: Send + Sync + 'static,
74        <S::ResBody as Body>::Data: Send,
75        <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
76        S::Future: Send,
77    {
78        let listener = TcpListener::bind(addr).await?;
79
80        let proxy = Arc::new(self);
81
82        Ok(async move {
83            loop {
84                let (stream, remote_addr) = match listener.accept().await {
85                    Ok(conn) => conn,
86                    Err(err) => {
87                        tracing::warn!("Failed to accept connection: {}", err);
88                        continue;
89                    }
90                };
91
92                let service = service.clone();
93
94                let proxy = proxy.clone();
95                tokio::spawn(async move {
96                    if let Err(err) = server::conn::http1::Builder::new()
97                        .preserve_header_case(true)
98                        .title_case_headers(true)
99                        .serve_connection(
100                            TokioIo::new(stream),
101                            service_fn(move |mut req| {
102                                req.extensions_mut().insert(RemoteAddr(remote_addr));
103                                Self::wrap_service(proxy.clone(), service.clone()).call(req)
104                            }),
105                        )
106                        .with_upgrades()
107                        .await
108                    {
109                        tracing::error!("Error in proxy: {}", err);
110                    }
111                });
112            }
113        })
114    }
115
116    /// Transform a service to a service that can be used in hyper server.
117    /// URL for requests that passed to service are full URL including scheme.
118    /// See `examples/https.rs` for usage.
119    /// If you want to serve simple HTTP proxy server, you can use `bind` method instead.
120    /// `bind` will call this method internally.
121    pub fn wrap_service<S>(
122        proxy: Arc<Self>,
123        service: S,
124    ) -> impl HttpService<
125        Incoming,
126        ResBody = BoxBody<<S::ResBody as Body>::Data, <S::ResBody as Body>::Error>,
127        Future: Send,
128    >
129    where
130        S: HttpService<Incoming> + Clone + Send + 'static,
131        S::Error: Into<Box<dyn StdError + Send + Sync>>,
132        S::ResBody: Send + Sync + 'static,
133        <S::ResBody as Body>::Data: Send,
134        <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
135        S::Future: Send,
136    {
137        service_fn(move |req| {
138            let proxy = proxy.clone();
139            let mut service = service.clone();
140
141            async move {
142                if req.method() == Method::CONNECT {
143                    // https
144                    let Some(connect_authority) = req.uri().authority().cloned() else {
145                        tracing::error!(
146                            "Bad CONNECT request: {}, Reason: Invalid Authority",
147                            req.uri()
148                        );
149                        return Ok(no_body(StatusCode::BAD_REQUEST)
150                            .map(|b| b.boxed().map_err(|never| match never {}).boxed()));
151                    };
152
153                    tokio::spawn(async move {
154                        let client = match hyper::upgrade::on(req).await {
155                            Ok(client) => client,
156                            Err(err) => {
157                                tracing::error!(
158                                    "Failed to upgrade CONNECT request for {}: {}",
159                                    connect_authority,
160                                    err
161                                );
162                                return;
163                            }
164                        };
165                        if let Some(server_config) =
166                            proxy.server_config(connect_authority.host().to_string(), true)
167                        {
168                            let server_config = match server_config {
169                                Ok(server_config) => server_config,
170                                Err(err) => {
171                                    tracing::error!(
172                                        "Failed to create server config for {}, {}",
173                                        connect_authority.host(),
174                                        err
175                                    );
176                                    return;
177                                }
178                            };
179                            let server_config = Arc::new(server_config);
180                            let tls_acceptor = tokio_rustls::TlsAcceptor::from(server_config);
181                            let client = match tls_acceptor.accept(TokioIo::new(client)).await {
182                                Ok(client) => client,
183                                Err(err) => {
184                                    tracing::error!(
185                                        "Failed to accept TLS connection for {}, {}",
186                                        connect_authority.host(),
187                                        err
188                                    );
189                                    return;
190                                }
191                            };
192                            let f = move |mut req: Request<_>| {
193                                let connect_authority = connect_authority.clone();
194                                let mut service = service.clone();
195
196                                async move {
197                                    inject_authority(&mut req, connect_authority.clone());
198                                    service.call(req).await
199                                }
200                            };
201                            let res = if client.get_ref().1.alpn_protocol() == Some(b"h2") {
202                                server::conn::http2::Builder::new(TokioExecutor::new())
203                                    .serve_connection(TokioIo::new(client), service_fn(f))
204                                    .await
205                            } else {
206                                server::conn::http1::Builder::new()
207                                    .preserve_header_case(true)
208                                    .title_case_headers(true)
209                                    .serve_connection(TokioIo::new(client), service_fn(f))
210                                    .with_upgrades()
211                                    .await
212                            };
213
214                            if let Err(err) = res {
215                                tracing::debug!("Connection closed: {}", err);
216                            }
217                        } else {
218                            let mut server =
219                                match TcpStream::connect(connect_authority.as_str()).await {
220                                    Ok(server) => server,
221                                    Err(err) => {
222                                        tracing::error!(
223                                            "Failed to connect to {}: {}",
224                                            connect_authority,
225                                            err
226                                        );
227                                        return;
228                                    }
229                                };
230                            let _ = tokio::io::copy_bidirectional(
231                                &mut TokioIo::new(client),
232                                &mut server,
233                            )
234                            .await;
235                        }
236                    });
237
238                    Ok(Response::new(
239                        http_body_util::Empty::new()
240                            .map_err(|never: std::convert::Infallible| match never {})
241                            .boxed(),
242                    ))
243                } else {
244                    // http
245                    service.call(req).await.map(|res| res.map(|b| b.boxed()))
246                }
247            }
248        })
249    }
250
251    fn get_certified_key(&self, host: String) -> Option<CertifiedKeyDer> {
252        self.root_issuer.as_ref().and_then(|root_issuer| {
253            if let Some(cache) = self.cert_cache.as_ref() {
254                // Try to get from cache, but handle generation errors gracefully
255                cache
256                    .try_get_with(host.clone(), move || {
257                        generate_cert(host, root_issuer.borrow())
258                    })
259                    .map_err(|err| {
260                        tracing::error!("Failed to generate certificate for host: {}", err);
261                    })
262                    .ok()
263            } else {
264                generate_cert(host, root_issuer.borrow())
265                    .map_err(|err| {
266                        tracing::error!("Failed to generate certificate for host: {}", err);
267                    })
268                    .ok()
269            }
270        })
271    }
272
273    fn server_config(
274        &self,
275        host: String,
276        h2: bool,
277    ) -> Option<Result<rustls::ServerConfig, rustls::Error>> {
278        if let Some(cert) = self.get_certified_key(host) {
279            let config = rustls::ServerConfig::builder()
280                .with_no_client_auth()
281                .with_single_cert(
282                    vec![rustls::pki_types::CertificateDer::from(cert.cert_der)],
283                    rustls::pki_types::PrivateKeyDer::Pkcs8(
284                        rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_der),
285                    ),
286                );
287
288            Some(if h2 {
289                config.map(|mut server_config| {
290                    server_config.alpn_protocols = vec!["h2".into(), "http/1.1".into()];
291                    server_config
292                })
293            } else {
294                config
295            })
296        } else {
297            None
298        }
299    }
300}
301
302fn no_body<D>(status: StatusCode) -> Response<Empty<D>> {
303    let mut res = Response::new(Empty::new());
304    *res.status_mut() = status;
305    res
306}
307
308fn inject_authority<B>(request_middleman: &mut Request<B>, authority: hyper::http::uri::Authority) {
309    let mut parts = request_middleman.uri().clone().into_parts();
310    parts.scheme = Some(hyper::http::uri::Scheme::HTTPS);
311    if parts.authority.is_none() {
312        parts.authority = Some(authority.clone());
313    }
314
315    match hyper::http::uri::Uri::from_parts(parts) {
316        Ok(uri) => *request_middleman.uri_mut() = uri,
317        Err(err) => {
318            tracing::error!(
319                "Failed to inject authority '{}' into URI: {}",
320                authority,
321                err
322            );
323            // Keep the original URI if injection fails
324        }
325    }
326}