2021-12-07 14:20:45 +00:00
|
|
|
//! Copied from https://github.com/felipenoris/hyper-reverse-proxy
|
|
|
|
//! See there for original Copyright notice
|
|
|
|
|
2021-12-08 22:45:24 +00:00
|
|
|
use std::convert::TryInto;
|
|
|
|
use std::net::IpAddr;
|
|
|
|
use std::str::FromStr;
|
2021-12-09 11:18:23 +00:00
|
|
|
use std::sync::Arc;
|
2022-01-24 19:55:26 +00:00
|
|
|
use std::time::{Duration, SystemTime};
|
2021-12-08 22:45:24 +00:00
|
|
|
|
2021-12-07 14:20:45 +00:00
|
|
|
use anyhow::Result;
|
2021-12-08 12:28:07 +00:00
|
|
|
use log::*;
|
2021-12-07 14:20:45 +00:00
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
use http::{header::HeaderName, StatusCode};
|
2021-12-07 14:20:45 +00:00
|
|
|
use hyper::header::{HeaderMap, HeaderValue};
|
2022-01-24 19:55:26 +00:00
|
|
|
use hyper::{client::HttpConnector, header, Body, Client, Request, Response, Uri};
|
2021-12-09 11:18:23 +00:00
|
|
|
use rustls::client::{ServerCertVerified, ServerCertVerifier};
|
|
|
|
use rustls::{Certificate, ServerName};
|
2021-12-08 22:45:24 +00:00
|
|
|
|
|
|
|
use crate::tls_util::HttpsConnectorFixedDnsname;
|
2021-12-07 14:20:45 +00:00
|
|
|
|
2022-01-24 19:55:26 +00:00
|
|
|
pub const PROXY_TIMEOUT: Duration = Duration::from_secs(60);
|
|
|
|
|
2021-12-09 14:43:19 +00:00
|
|
|
const HOP_HEADERS: &[HeaderName] = &[
|
|
|
|
header::CONNECTION,
|
2022-01-25 16:01:39 +00:00
|
|
|
// header::KEEP_ALIVE, // not found in http::header
|
2021-12-09 14:43:19 +00:00
|
|
|
header::PROXY_AUTHENTICATE,
|
|
|
|
header::PROXY_AUTHORIZATION,
|
|
|
|
header::TE,
|
|
|
|
header::TRAILER,
|
|
|
|
header::TRANSFER_ENCODING,
|
|
|
|
header::UPGRADE,
|
|
|
|
];
|
|
|
|
|
|
|
|
fn is_hop_header(name: &HeaderName) -> bool {
|
|
|
|
HOP_HEADERS.iter().any(|h| h == name)
|
2021-12-07 14:20:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a clone of the headers without the [hop-by-hop headers].
|
|
|
|
///
|
|
|
|
/// [hop-by-hop headers]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
|
|
|
|
fn remove_hop_headers(headers: &HeaderMap<HeaderValue>) -> HeaderMap<HeaderValue> {
|
|
|
|
let mut result = HeaderMap::new();
|
|
|
|
for (k, v) in headers.iter() {
|
2021-12-09 22:38:56 +00:00
|
|
|
if !is_hop_header(k) {
|
2021-12-09 10:20:04 +00:00
|
|
|
result.append(k.clone(), v.clone());
|
2021-12-07 14:20:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
result
|
|
|
|
}
|
|
|
|
|
2022-05-06 10:21:15 +00:00
|
|
|
fn copy_upgrade_headers(
|
|
|
|
old_headers: &HeaderMap<HeaderValue>,
|
|
|
|
new_headers: &mut HeaderMap<HeaderValue>,
|
2022-05-10 10:02:19 +00:00
|
|
|
) -> Result<bool> {
|
2022-05-06 10:34:19 +00:00
|
|
|
// The Connection header is stripped as it is a hop header that we are not supposed to proxy.
|
|
|
|
// However, it might also contain an Upgrade directive, e.g. for Websockets:
|
|
|
|
// when that happen, we do want to preserve that directive.
|
2022-05-10 10:02:19 +00:00
|
|
|
let mut is_upgrade = false;
|
2022-05-06 10:21:15 +00:00
|
|
|
if let Some(conn) = old_headers.get(header::CONNECTION) {
|
2022-05-06 10:34:19 +00:00
|
|
|
let conn_str = conn.to_str()?.to_lowercase();
|
|
|
|
if conn_str.split(',').map(str::trim).any(|x| x == "upgrade") {
|
2022-05-06 10:21:15 +00:00
|
|
|
if let Some(upgrade) = old_headers.get(header::UPGRADE) {
|
|
|
|
new_headers.insert(header::CONNECTION, "Upgrade".try_into()?);
|
|
|
|
new_headers.insert(header::UPGRADE, upgrade.clone());
|
2022-05-10 10:02:19 +00:00
|
|
|
is_upgrade = true;
|
2022-05-06 10:21:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-05-10 10:02:19 +00:00
|
|
|
Ok(is_upgrade)
|
2021-12-07 14:20:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn forward_uri<B>(forward_url: &str, req: &Request<B>) -> Result<Uri> {
|
|
|
|
let forward_uri = match req.uri().query() {
|
|
|
|
Some(query) => format!("{}{}?{}", forward_url, req.uri().path(), query),
|
|
|
|
None => format!("{}{}", forward_url, req.uri().path()),
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(Uri::from_str(forward_uri.as_str())?)
|
|
|
|
}
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
fn create_proxied_request<B: std::default::Default>(
|
2021-12-07 14:20:45 +00:00
|
|
|
client_ip: IpAddr,
|
|
|
|
forward_url: &str,
|
|
|
|
request: Request<B>,
|
2022-05-10 10:02:19 +00:00
|
|
|
) -> Result<(Request<B>, Option<Request<B>>)> {
|
2021-12-08 12:28:07 +00:00
|
|
|
let mut builder = Request::builder()
|
|
|
|
.method(request.method())
|
2022-01-25 16:01:39 +00:00
|
|
|
.uri(forward_uri(forward_url, &request)?)
|
|
|
|
.version(hyper::Version::HTTP_11);
|
2021-12-07 14:20:45 +00:00
|
|
|
|
2022-05-06 10:21:15 +00:00
|
|
|
let old_headers = request.headers();
|
|
|
|
let new_headers = builder.headers_mut().unwrap();
|
2022-02-27 18:47:41 +00:00
|
|
|
|
2022-05-06 10:21:15 +00:00
|
|
|
*new_headers = remove_hop_headers(old_headers);
|
2021-12-07 14:20:45 +00:00
|
|
|
|
|
|
|
// If request does not have host header, add it from original URI authority
|
2022-05-06 10:21:15 +00:00
|
|
|
if let header::Entry::Vacant(entry) = new_headers.entry(header::HOST) {
|
2021-12-09 10:20:04 +00:00
|
|
|
if let Some(authority) = request.uri().authority() {
|
2021-12-07 14:20:45 +00:00
|
|
|
entry.insert(authority.as_str().parse()?);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-27 18:47:41 +00:00
|
|
|
// Concatenate cookie headers into single header
|
2022-02-27 18:53:06 +00:00
|
|
|
// (HTTP/2 allows several cookie headers, but we are proxying to HTTP/1.1 that does not)
|
2022-02-27 18:47:41 +00:00
|
|
|
let mut cookie_concat = vec![];
|
2022-05-06 10:21:15 +00:00
|
|
|
for cookie in new_headers.get_all(header::COOKIE) {
|
2022-02-27 18:47:41 +00:00
|
|
|
if !cookie_concat.is_empty() {
|
|
|
|
cookie_concat.extend(b"; ");
|
|
|
|
}
|
|
|
|
cookie_concat.extend_from_slice(cookie.as_bytes());
|
|
|
|
}
|
|
|
|
if !cookie_concat.is_empty() {
|
2022-02-27 18:53:06 +00:00
|
|
|
// insert clears the old value of COOKIE and inserts the concatenated version instead
|
2022-05-06 10:21:15 +00:00
|
|
|
new_headers.insert(header::COOKIE, cookie_concat.try_into()?);
|
2022-02-27 18:47:41 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 14:20:45 +00:00
|
|
|
// Add forwarding information in the headers
|
2021-12-08 16:27:27 +00:00
|
|
|
let x_forwarded_for_header_name = "x-forwarded-for";
|
2022-05-06 10:21:15 +00:00
|
|
|
match new_headers.entry(x_forwarded_for_header_name) {
|
2021-12-09 14:43:19 +00:00
|
|
|
header::Entry::Vacant(entry) => {
|
2021-12-07 14:20:45 +00:00
|
|
|
entry.insert(client_ip.to_string().parse()?);
|
|
|
|
}
|
|
|
|
|
2021-12-09 14:43:19 +00:00
|
|
|
header::Entry::Occupied(mut entry) => {
|
2021-12-07 14:20:45 +00:00
|
|
|
let addr = format!("{}, {}", entry.get().to_str()?, client_ip);
|
|
|
|
entry.insert(addr.parse()?);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-06 10:21:15 +00:00
|
|
|
new_headers.insert(
|
2021-12-08 16:50:40 +00:00
|
|
|
HeaderName::from_bytes(b"x-forwarded-proto")?,
|
|
|
|
"https".try_into()?,
|
|
|
|
);
|
2021-12-08 16:27:27 +00:00
|
|
|
|
2021-12-09 10:20:04 +00:00
|
|
|
// Proxy upgrade requests properly
|
2022-05-10 10:02:19 +00:00
|
|
|
let is_upgrade = copy_upgrade_headers(old_headers, new_headers)?;
|
2021-12-08 12:28:07 +00:00
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
if is_upgrade {
|
|
|
|
Ok((builder.body(B::default())?, Some(request)))
|
|
|
|
} else {
|
|
|
|
Ok((builder.body(request.into_body())?, None))
|
|
|
|
}
|
2021-12-07 14:20:45 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
async fn create_proxied_response<B: std::default::Default + Send + Sync + 'static>(
|
|
|
|
mut response: Response<B>,
|
|
|
|
upgrade_request: Option<Request<B>>,
|
|
|
|
) -> Result<Response<B>> {
|
2022-05-06 10:21:15 +00:00
|
|
|
let old_headers = response.headers();
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
let mut new_headers = remove_hop_headers(old_headers);
|
2022-05-06 10:21:15 +00:00
|
|
|
copy_upgrade_headers(old_headers, &mut new_headers)?;
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
if response.status() == StatusCode::SWITCHING_PROTOCOLS {
|
|
|
|
if let Some(mut req) = upgrade_request {
|
|
|
|
let mut res_upgraded = hyper::upgrade::on(response).await?;
|
|
|
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
match hyper::upgrade::on(&mut req).await {
|
|
|
|
Ok(mut req_upgraded) => {
|
|
|
|
if let Err(e) =
|
|
|
|
tokio::io::copy_bidirectional(&mut req_upgraded, &mut res_upgraded)
|
|
|
|
.await
|
|
|
|
{
|
|
|
|
warn!("Error copying data in upgraded request: {}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
warn!(
|
|
|
|
"Could not upgrade client request when switching protocols: {}",
|
|
|
|
e
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut new_res = Response::builder().status(StatusCode::SWITCHING_PROTOCOLS);
|
|
|
|
*new_res.headers_mut().unwrap() = new_headers;
|
|
|
|
Ok(new_res.body(B::default())?)
|
|
|
|
} else {
|
2022-12-06 13:24:00 +00:00
|
|
|
Err(anyhow!("Switching protocols but not an upgrade request"))
|
2022-05-10 10:02:19 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
*response.headers_mut() = new_headers;
|
|
|
|
Ok(response)
|
|
|
|
}
|
2022-05-06 10:21:15 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 14:20:45 +00:00
|
|
|
pub async fn call(
|
|
|
|
client_ip: IpAddr,
|
|
|
|
forward_uri: &str,
|
|
|
|
request: Request<Body>,
|
|
|
|
) -> Result<Response<Body>> {
|
2022-05-10 10:02:19 +00:00
|
|
|
let (proxied_request, upgrade_request) =
|
|
|
|
create_proxied_request(client_ip, forward_uri, request)?;
|
2021-12-07 14:20:45 +00:00
|
|
|
|
2021-12-08 12:28:07 +00:00
|
|
|
trace!("Proxied request: {:?}", proxied_request);
|
|
|
|
|
2022-01-24 19:55:26 +00:00
|
|
|
let mut connector = HttpConnector::new();
|
|
|
|
connector.set_connect_timeout(Some(PROXY_TIMEOUT));
|
|
|
|
|
2022-01-25 16:01:39 +00:00
|
|
|
let client: Client<_, hyper::Body> = Client::builder().set_host(false).build(connector);
|
2022-01-24 19:55:26 +00:00
|
|
|
|
2021-12-07 14:20:45 +00:00
|
|
|
let response = client.request(proxied_request).await?;
|
2021-12-08 12:28:07 +00:00
|
|
|
|
|
|
|
trace!("Inner response: {:?}", response);
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
let proxied_response = create_proxied_response(response, upgrade_request).await?;
|
2021-12-07 14:20:45 +00:00
|
|
|
Ok(proxied_response)
|
|
|
|
}
|
2021-12-08 21:58:19 +00:00
|
|
|
|
|
|
|
pub async fn call_https(
|
|
|
|
client_ip: IpAddr,
|
|
|
|
forward_uri: &str,
|
|
|
|
request: Request<Body>,
|
|
|
|
) -> Result<Response<Body>> {
|
2022-05-10 10:02:19 +00:00
|
|
|
let (proxied_request, upgrade_request) =
|
|
|
|
create_proxied_request(client_ip, forward_uri, request)?;
|
2021-12-08 21:58:19 +00:00
|
|
|
|
|
|
|
trace!("Proxied request (HTTPS): {:?}", proxied_request);
|
|
|
|
|
2021-12-08 22:45:24 +00:00
|
|
|
let tls_config = rustls::client::ClientConfig::builder()
|
|
|
|
.with_safe_defaults()
|
|
|
|
.with_custom_certificate_verifier(Arc::new(DontVerifyServerCert))
|
|
|
|
.with_no_client_auth();
|
2022-01-24 19:55:26 +00:00
|
|
|
|
|
|
|
let mut http_connector = HttpConnector::new();
|
|
|
|
http_connector.set_connect_timeout(Some(PROXY_TIMEOUT));
|
|
|
|
let connector = HttpsConnectorFixedDnsname::new(tls_config, "dummy", http_connector);
|
|
|
|
|
2022-01-25 16:01:39 +00:00
|
|
|
let client: Client<_, hyper::Body> = Client::builder().set_host(false).build(connector);
|
2021-12-08 21:58:19 +00:00
|
|
|
let response = client.request(proxied_request).await?;
|
|
|
|
|
|
|
|
trace!("Inner response (HTTPS): {:?}", response);
|
|
|
|
|
2022-05-10 10:02:19 +00:00
|
|
|
let proxied_response = create_proxied_response(response, upgrade_request).await?;
|
2021-12-08 21:58:19 +00:00
|
|
|
Ok(proxied_response)
|
|
|
|
}
|
2021-12-08 22:45:24 +00:00
|
|
|
|
|
|
|
struct DontVerifyServerCert;
|
|
|
|
|
|
|
|
impl ServerCertVerifier for DontVerifyServerCert {
|
|
|
|
fn verify_server_cert(
|
2021-12-09 11:18:23 +00:00
|
|
|
&self,
|
|
|
|
_end_entity: &Certificate,
|
|
|
|
_intermediates: &[Certificate],
|
|
|
|
_server_name: &ServerName,
|
|
|
|
_scts: &mut dyn Iterator<Item = &[u8]>,
|
|
|
|
_ocsp_response: &[u8],
|
|
|
|
_now: SystemTime,
|
|
|
|
) -> Result<ServerCertVerified, rustls::Error> {
|
2021-12-08 22:45:24 +00:00
|
|
|
Ok(ServerCertVerified::assertion())
|
|
|
|
}
|
|
|
|
}
|