-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathproxy.rs
More file actions
254 lines (225 loc) · 8.04 KB
/
Copy pathproxy.rs
File metadata and controls
254 lines (225 loc) · 8.04 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
use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use bytes::Bytes;
use http_body_util::combinators::BoxBody;
use http_body_util::{BodyExt, Empty, Full};
use hyper::body::Incoming;
use hyper::service::Service;
use hyper::{Method, Request, Response, StatusCode};
use rustls::ServerConnection;
use rustls_pki_types::CertificateDer;
use tokio::io::copy_bidirectional;
use tokio::net::TcpStream;
use tracing::{error, info, warn};
use crate::policy::{self, PolicyDecision, PolicyEngine, RequestContext};
type ProxyBody = BoxBody<Bytes, Infallible>;
#[derive(Clone)]
pub struct ProxyService {
policy_engine: Arc<dyn PolicyEngine>,
peer_certs: Vec<CertificateDer<'static>>,
source_peer_addr: SocketAddr,
}
impl ProxyService {
pub fn new(
policy_engine: Arc<dyn PolicyEngine>,
peer_certs: Vec<CertificateDer<'static>>,
source_peer_addr: SocketAddr,
) -> Self {
Self {
policy_engine,
peer_certs,
source_peer_addr,
}
}
async fn handle(self, req: Request<Incoming>) -> Response<ProxyBody> {
if req.method() != Method::CONNECT {
return response(StatusCode::METHOD_NOT_ALLOWED, "only CONNECT is supported");
}
let dest = match Destination::from_request(&req) {
Ok(d) => d,
Err(reason) => return response(StatusCode::BAD_REQUEST, &reason),
};
let ctx = RequestContext {
peer_certificates: self.peer_certs.clone(),
destination: dest.authority.clone(),
};
let source_identity = match self.policy_engine.evaluate(&ctx).await {
PolicyDecision::Allow { source_identity } => {
info!(
source_identity = %source_identity,
source_peer_addr = %self.source_peer_addr,
dest_authority = %dest.authority,
policy_decision = "allow",
"CONNECT allowed"
);
source_identity
}
PolicyDecision::Deny {
source_identity: Some(source_identity),
reason,
} => {
warn!(
source_identity = %source_identity,
source_peer_addr = %self.source_peer_addr,
dest_authority = %dest.authority,
policy_decision = "deny",
deny_reason = %reason,
"CONNECT denied"
);
return response(StatusCode::FORBIDDEN, "forbidden");
}
PolicyDecision::Deny {
source_identity: None,
reason,
} => {
warn!(
source_peer_addr = %self.source_peer_addr,
dest_authority = %dest.authority,
policy_decision = "deny",
deny_reason = %reason,
"CONNECT denied"
);
return response(StatusCode::FORBIDDEN, "forbidden");
}
};
// Connect to destination BEFORE returning 200 so the client knows
// the tunnel is actually established.
let mut upstream = match TcpStream::connect((&*dest.host, dest.port)).await {
Ok(s) => s,
Err(e) => {
error!(
source_identity = %source_identity,
source_peer_addr = %self.source_peer_addr,
dest_authority = %dest.authority,
error = %e,
"TCP connect failed"
);
return response(StatusCode::BAD_GATEWAY, "bad gateway");
}
};
let on_upgrade = hyper::upgrade::on(req);
let source_peer_addr = self.source_peer_addr;
tokio::spawn(async move {
let upgraded = match on_upgrade.await {
Ok(u) => u,
Err(e) => {
warn!(
source_identity = %source_identity,
source_peer_addr = %source_peer_addr,
dest_authority = %dest.authority,
error = %e,
"upgrade failed"
);
return;
}
};
let mut downstream = hyper_util::rt::TokioIo::new(upgraded);
match copy_bidirectional(&mut downstream, &mut upstream).await {
Ok((up, down)) => {
info!(
source_identity = %source_identity,
source_peer_addr = %source_peer_addr,
dest_authority = %dest.authority,
bytes_client_to_dest = up,
bytes_dest_to_client = down,
"tunnel closed"
);
}
Err(e) => {
error!(
source_identity = %source_identity,
source_peer_addr = %source_peer_addr,
dest_authority = %dest.authority,
error = %e,
"tunnel error"
);
}
}
});
response(StatusCode::OK, "")
}
}
impl Service<Request<Incoming>> for ProxyService {
type Response = Response<ProxyBody>;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, req: Request<Incoming>) -> Self::Future {
let this = self.clone();
Box::pin(async move { Ok(this.handle(req).await) })
}
}
pub struct MakeProxyService {
policy_engine: Arc<dyn PolicyEngine>,
}
impl MakeProxyService {
pub fn new(policy_engine: Arc<dyn PolicyEngine>) -> Self {
Self { policy_engine }
}
pub fn make_service(
&self,
peer_certs: Vec<CertificateDer<'static>>,
source_peer_addr: SocketAddr,
) -> ProxyService {
ProxyService::new(self.policy_engine.clone(), peer_certs, source_peer_addr)
}
}
pub fn extract_peer_certs(conn: &ServerConnection) -> Vec<CertificateDer<'static>> {
conn.peer_certificates()
.map(|certs| certs.to_vec())
.unwrap_or_default()
}
fn response(status: StatusCode, message: &str) -> Response<ProxyBody> {
let body: ProxyBody = if message.is_empty() {
Empty::<Bytes>::new().boxed()
} else {
Full::new(Bytes::from(message.to_owned())).boxed()
};
let mut resp = Response::new(body);
*resp.status_mut() = status;
resp
}
#[derive(Clone)]
pub struct Destination {
pub host: String,
pub port: u16,
pub authority: String,
}
impl Destination {
pub fn from_request(req: &Request<Incoming>) -> Result<Self, String> {
let authority = req
.uri()
.authority()
.ok_or("CONNECT request missing authority")?;
Self::from_authority(authority)
}
pub fn from_authority(authority: &http::uri::Authority) -> Result<Self, String> {
let raw_host = authority.host();
if raw_host.is_empty() {
return Err("empty host in CONNECT authority".into());
}
// Authority::host() preserves brackets for IPv6 (e.g. "[::1]").
// Strip them so `host` is always the bare address for TcpStream::connect.
let host = raw_host
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or(raw_host)
.to_owned();
let port = authority.port_u16().unwrap_or(443);
// Reconstruct with brackets for IPv6 to feed the canonical normalizer
let formatted = if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
};
let authority_str = policy::normalize_destination(&formatted)
.map_err(|e| format!("bad destination: {e}"))?;
Ok(Self {
host,
port,
authority: authority_str,
})
}
}