Add tcp reverse tunneling

This commit is contained in:
Σrebe - Romain GERARD 2023-11-26 15:47:49 +01:00
parent cb4675a817
commit 87cf422489
No known key found for this signature in database
GPG key ID: 7A42B4B97E0332F4
6 changed files with 121 additions and 5 deletions

View file

@ -1,3 +1,5 @@
use ahash::{HashMap, HashMapExt};
use futures_util::StreamExt;
use std::cmp::min;
use std::ops::{Deref, Not};
use std::pin::Pin;
@ -10,10 +12,13 @@ use hyper::server::conn::Http;
use hyper::service::service_fn;
use hyper::{http, Body, Request, Response, StatusCode};
use jsonwebtoken::TokenData;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tokio_stream::wrappers::TcpListenerStream;
use tracing::{error, info, span, warn, Instrument, Level, Span};
use url::Host;
@ -63,7 +68,7 @@ async fn from_query(
Box::pin(cnx),
))
}
LocalProtocol::Tcp { .. } => {
LocalProtocol::Tcp => {
let host = Host::parse(&jwt.claims.r)?;
let port = jwt.claims.rp;
let (rx, tx) = tcp::connect(&host, port, &server_config.socket_so_mark, Duration::from_secs(10))
@ -72,6 +77,26 @@ async fn from_query(
Ok((jwt.claims.p, host, port, Box::pin(rx), Box::pin(tx)))
}
LocalProtocol::ReverseTcp => {
#[allow(clippy::type_complexity)]
static REVERSE: Lazy<Mutex<HashMap<(Host<String>, u16), TcpListenerStream>>> =
Lazy::new(|| Mutex::new(HashMap::with_capacity(0)));
let local_srv = (Host::parse(&jwt.claims.r)?, jwt.claims.rp);
let listening_server = REVERSE.lock().remove(&local_srv);
let mut listening_server = if let Some(listening_server) = listening_server {
listening_server
} else {
let bind = format!("{}:{}", local_srv.0, local_srv.1);
tcp::run_server(bind.parse()?).await?
};
let tcp = listening_server.next().await.unwrap()?;
let (local_rx, local_tx) = tokio::io::split(tcp);
REVERSE.lock().insert(local_srv.clone(), listening_server);
Ok((jwt.claims.p, local_srv.0, local_srv.1, Box::pin(local_rx), Box::pin(local_tx)))
}
_ => Err(anyhow::anyhow!("Invalid upgrade request")),
}
}