-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlib.rs
More file actions
323 lines (299 loc) · 12.7 KB
/
lib.rs
File metadata and controls
323 lines (299 loc) · 12.7 KB
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
#![doc = include_str!("../README.md")]
use http_body_util::{BodyExt, Empty, combinators::BoxBody};
use hyper::{
Method, Request, Response, StatusCode,
body::{Body, Incoming},
server,
service::{HttpService, service_fn},
};
use hyper_util::rt::{TokioExecutor, TokioIo};
use moka::sync::Cache;
use std::{borrow::Borrow, error::Error as StdError, future::Future, sync::Arc};
use tls::{CertifiedKeyDer, generate_cert};
use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
use tokio_rustls::rustls;
pub use futures;
pub use hyper;
pub use moka;
#[cfg(feature = "native-tls-client")]
pub use tokio_native_tls;
#[cfg(any(feature = "native-tls-client", feature = "rustls-client"))]
pub mod default_client;
mod tls;
#[cfg(any(feature = "native-tls-client", feature = "rustls-client"))]
pub use default_client::DefaultClient;
#[derive(Clone)]
/// The main struct to run proxy server
pub struct MitmProxy<I> {
/// Root issuer to sign fake certificates. You may need to trust this issuer on client application to use HTTPS.
///
/// If None, proxy will just tunnel HTTPS traffic and will not observe HTTPS traffic.
pub root_issuer: Option<I>,
/// Cache to store generated certificates. If None, cache will not be used.
/// If root_issuer is None, cache will not be used.
///
/// The key of cache is hostname.
pub cert_cache: Option<Cache<String, CertifiedKeyDer>>,
}
impl<I> MitmProxy<I> {
/// Create a new MitmProxy
pub fn new(root_issuer: Option<I>, cache: Option<Cache<String, CertifiedKeyDer>>) -> Self {
Self {
root_issuer,
cert_cache: cache,
}
}
}
impl<I> MitmProxy<I>
where
I: Borrow<rcgen::Issuer<'static, rcgen::KeyPair>> + Send + Sync + 'static,
{
/// Bind to a socket address and return a future that runs the proxy server.
/// URL for requests that passed to service are full URL including scheme.
/// remote address of client is stored in request extensions as std::net::SocketAddr.
pub async fn bind<A: ToSocketAddrs, S>(
self,
addr: A,
service: S,
) -> Result<impl Future<Output = ()>, std::io::Error>
where
S: HttpService<Incoming> + Clone + Send + 'static,
S::Error: Into<Box<dyn StdError + Send + Sync>>,
S::ResBody: Send + Sync + 'static,
<S::ResBody as Body>::Data: Send,
<S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
S::Future: Send,
{
let listener = TcpListener::bind(addr).await?;
let proxy = Arc::new(self);
Ok(async move {
loop {
let (stream, remote_addr) = match listener.accept().await {
Ok(conn) => conn,
Err(err) => {
tracing::warn!("Failed to accept connection: {}", err);
continue;
}
};
let service = service.clone();
let proxy = proxy.clone();
tokio::spawn(async move {
if let Err(err) = server::conn::http1::Builder::new()
.preserve_header_case(true)
.title_case_headers(true)
.serve_connection(
TokioIo::new(stream),
service_fn(move |mut req| {
req.extensions_mut().insert(remote_addr);
Self::wrap_service(proxy.clone(), service.clone()).call(req)
}),
)
.with_upgrades()
.await
{
tracing::error!("Error in proxy: {}", err);
}
});
}
})
}
/// Transform a service to a service that can be used in hyper server.
/// URL for requests that passed to service are full URL including scheme.
/// See `examples/https.rs` for usage.
/// If you want to serve simple HTTP proxy server, you can use `bind` method instead.
/// `bind` will call this method internally.
pub fn wrap_service<S>(
proxy: Arc<Self>,
service: S,
) -> impl HttpService<
Incoming,
ResBody = BoxBody<<S::ResBody as Body>::Data, <S::ResBody as Body>::Error>,
Future: Send,
>
where
S: HttpService<Incoming> + Clone + Send + 'static,
S::Error: Into<Box<dyn StdError + Send + Sync>>,
S::ResBody: Send + Sync + 'static,
<S::ResBody as Body>::Data: Send,
<S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>,
S::Future: Send,
{
service_fn(move |req| {
let proxy = proxy.clone();
let mut service = service.clone();
async move {
if req.method() == Method::CONNECT {
// https
let Some(connect_authority) = req.uri().authority().cloned() else {
tracing::error!(
"Bad CONNECT request: {}, Reason: Invalid Authority",
req.uri()
);
return Ok(no_body(StatusCode::BAD_REQUEST)
.map(|b| b.boxed().map_err(|never| match never {}).boxed()));
};
tokio::spawn(async move {
let client = match hyper::upgrade::on(req).await {
Ok(client) => client,
Err(err) => {
tracing::error!(
"Failed to upgrade CONNECT request for {}: {}",
connect_authority,
err
);
return;
}
};
if let Some(server_config) =
proxy.server_config(connect_authority.host().to_string(), true)
{
let server_config = match server_config {
Ok(server_config) => server_config,
Err(err) => {
tracing::error!(
"Failed to create server config for {}, {}",
connect_authority.host(),
err
);
return;
}
};
let server_config = Arc::new(server_config);
let tls_acceptor = tokio_rustls::TlsAcceptor::from(server_config);
let client = match tls_acceptor.accept(TokioIo::new(client)).await {
Ok(client) => client,
Err(err) => {
tracing::error!(
"Failed to accept TLS connection for {}, {}",
connect_authority.host(),
err
);
return;
}
};
let f = move |mut req: Request<_>| {
let connect_authority = connect_authority.clone();
let mut service = service.clone();
async move {
inject_authority(&mut req, connect_authority.clone());
service.call(req).await
}
};
let res = if client.get_ref().1.alpn_protocol() == Some(b"h2") {
server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(client), service_fn(f))
.await
} else {
server::conn::http1::Builder::new()
.preserve_header_case(true)
.title_case_headers(true)
.serve_connection(TokioIo::new(client), service_fn(f))
.with_upgrades()
.await
};
if let Err(err) = res {
tracing::debug!("Connection closed: {}", err);
}
} else {
let mut server =
match TcpStream::connect(connect_authority.as_str()).await {
Ok(server) => server,
Err(err) => {
tracing::error!(
"Failed to connect to {}: {}",
connect_authority,
err
);
return;
}
};
let _ = tokio::io::copy_bidirectional(
&mut TokioIo::new(client),
&mut server,
)
.await;
}
});
Ok(Response::new(
http_body_util::Empty::new()
.map_err(|never: std::convert::Infallible| match never {})
.boxed(),
))
} else {
// http
service.call(req).await.map(|res| res.map(|b| b.boxed()))
}
}
})
}
fn get_certified_key(&self, host: String) -> Option<CertifiedKeyDer> {
self.root_issuer.as_ref().and_then(|root_issuer| {
if let Some(cache) = self.cert_cache.as_ref() {
// Try to get from cache, but handle generation errors gracefully
cache
.try_get_with(host.clone(), move || {
generate_cert(host, root_issuer.borrow())
})
.map_err(|err| {
tracing::error!("Failed to generate certificate for host: {}", err);
})
.ok()
} else {
generate_cert(host, root_issuer.borrow())
.map_err(|err| {
tracing::error!("Failed to generate certificate for host: {}", err);
})
.ok()
}
})
}
fn server_config(
&self,
host: String,
h2: bool,
) -> Option<Result<rustls::ServerConfig, rustls::Error>> {
if let Some(cert) = self.get_certified_key(host) {
let config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(
vec![rustls::pki_types::CertificateDer::from(cert.cert_der)],
rustls::pki_types::PrivateKeyDer::Pkcs8(
rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_der),
),
);
Some(if h2 {
config.map(|mut server_config| {
server_config.alpn_protocols = vec!["h2".into(), "http/1.1".into()];
server_config
})
} else {
config
})
} else {
None
}
}
}
fn no_body<D>(status: StatusCode) -> Response<Empty<D>> {
let mut res = Response::new(Empty::new());
*res.status_mut() = status;
res
}
fn inject_authority<B>(request_middleman: &mut Request<B>, authority: hyper::http::uri::Authority) {
let mut parts = request_middleman.uri().clone().into_parts();
parts.scheme = Some(hyper::http::uri::Scheme::HTTPS);
if parts.authority.is_none() {
parts.authority = Some(authority.clone());
}
match hyper::http::uri::Uri::from_parts(parts) {
Ok(uri) => *request_middleman.uri_mut() = uri,
Err(err) => {
tracing::error!(
"Failed to inject authority '{}' into URI: {}",
authority,
err
);
// Keep the original URI if injection fails
}
}
}