// sandhole: Expose HTTP/SSH/TCP services through SSH port forwarding
// Copyright (C) 2024-2026 Eric Rodrigues Pires
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
// more details.
//
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see .
use std::{
collections::HashSet,
mem::size_of,
net::{IpAddr, SocketAddr},
pin::pin,
sync::Arc,
time::Duration,
};
use crate::{
connection_handler::ConnectionHandler,
connections::ConnectionMap,
droppable_handle::DroppableHandle,
ip::IpFilter,
reactor::UdpReactor,
ssh::connection_handler::{SshChannel, SshTunnelHandler},
telemetry::{TELEMETRY_COUNTER_UDP_CONNECTIONS, TELEMETRY_KEY_PORT},
};
use ahash::RandomState;
use bon::Builder;
use color_eyre::eyre::Context;
use dashmap::DashMap;
use metrics::counter;
use sandhole_socket::{
udp_listener::get_udp_socket,
udp_over_tcp::{datagram_buffer, deserialize_datagram, serialize_datagram},
};
use tokio::{
io::{AsyncWriteExt, WriteHalf},
select,
sync::Mutex,
time::sleep,
};
// Type for a UDP socket with the write and read halves.
struct UdpSocketHandler {
write: Arc>>,
_read_task: DroppableHandle<()>,
}
// Service that handles creating UDP sockets for reverse forwarding connections.
#[derive(Builder)]
pub(crate) struct UdpHandler {
// Address to listen to when creating sockets.
listen_address: IpAddr,
// Map containing spawned tasks of connections for each socket.
#[builder(skip = DashMap::default())]
tasks: DashMap, RandomState>,
// Map linking a stateless socket to its underlying SSH channel.
#[builder(skip = DashMap::default())]
sockets: DashMap<(u16, SocketAddr), UdpSocketHandler, RandomState>,
// Connection map to assign a tunneling service for each incoming connection.
conn_manager: Arc, UdpReactor>>,
// Service that identifies whether to allow or block a given IP address.
ip_filter: Arc,
// Whether to send UDP logs to the SSH handles behind the forwarded connections.
disable_udp_logs: bool,
// How long until SSH channels from UDP sockets are automatically garbage-collected.
udp_timeout: Duration,
}
pub(crate) trait UdpPortHandler {
async fn create_port_socket(&self, port: u16) -> color_eyre::Result;
async fn get_free_port(&self) -> color_eyre::Result;
fn update_ports(&self, ports: Vec);
}
impl UdpPortHandler for Arc {
// Create a UDP listener on the given port.
async fn create_port_socket(&self, port: u16) -> color_eyre::Result {
if self.tasks.contains_key(&port) {
return Ok(port);
}
// Check if we're able to bind to the given address and port.
let socket = Arc::new(get_udp_socket((self.listen_address, port))?);
let port = socket
.local_addr()
.with_context(|| "Missing local address when binding port")?
.port();
let clone = Arc::clone(self);
// Start task that will listen to incoming connections.
let join_handle = DroppableHandle(tokio::spawn(async move {
loop {
let mut buf = datagram_buffer();
match socket.recv_from(buf.as_mut()).await {
Ok((len, address)) => {
let ip = address.ip().to_canonical();
if !clone.ip_filter.is_allowed(ip) {
#[cfg(not(coverage_nightly))]
tracing::info!(%address, "Rejecting UDP connection: IP not allowed.");
continue;
}
// Prepare data to be sent to SSH channel
let mut read_buf = datagram_buffer();
serialize_datagram(&mut read_buf[..], &buf[..len]);
// Check for an existing SSH channel
if let Some(entry) = clone.sockets.get(&(port, address)) {
let value = entry.value();
let channel = Arc::clone(&value.write);
drop(entry);
if channel
.lock()
.await
.write_all(&read_buf[..size_of::() + len])
.await
.is_ok()
{
continue;
} else {
clone.sockets.remove(&(port, address));
}
}
// Get the handler for this port
if let Some(handler) = clone.conn_manager.get(&port, ip)
&& let Ok(channel) = handler.tunneling_channel(ip, address.port()).await
{
counter!(TELEMETRY_COUNTER_UDP_CONNECTIONS, TELEMETRY_KEY_PORT => port.to_string())
.increment(1);
// Log new connection to SSH handler
if !clone.disable_udp_logs {
let _ = handler.log_channel().send(
format!(
"New connection from {}:{} to UDP port {}\r\n",
ip,
address.port(),
port
)
.into_bytes(),
);
}
let udp_write = Arc::clone(&socket);
let (ssh_read, mut ssh_write) = tokio::io::split(channel);
if let Err(error) = ssh_write
.write_all(&read_buf[..size_of::() + len])
.await
{
#[cfg(not(coverage_nightly))]
tracing::warn!(%port, %error, "Error sending UDP datagram to SSH channel.");
continue;
}
let clone_2 = Arc::clone(&clone);
let _read_task = DroppableHandle(tokio::spawn(async move {
let mut write_buf = datagram_buffer();
let mut ssh_read = pin!(ssh_read);
loop {
let sleep_fut = sleep(clone_2.udp_timeout);
let read_fut = async {
match deserialize_datagram(
&mut write_buf[..],
&mut ssh_read,
)
.await
{
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%port, %error, "Error deserializing UDP datagram from SSH channel.");
false
}
Ok(len) => {
if let Err(error) = udp_write
.send_to(&write_buf[..len], address)
.await
{
#[cfg(not(coverage_nightly))]
tracing::warn!(%port, %error, "Error sending UDP datagram.");
false
} else {
true
}
}
}
};
let sleep_fut = pin!(sleep_fut);
let read_fut = pin!(read_fut);
select! {
success = read_fut => if !success { break; },
_ = sleep_fut => break,
}
}
clone_2.sockets.remove(&(port, address));
}));
clone.sockets.insert(
(port, address),
UdpSocketHandler {
write: Arc::new(Mutex::new(ssh_write)),
_read_task,
},
);
}
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%port, %error, "Error getting remote connection on UDP port.");
}
}
}
}));
self.tasks.insert(port, join_handle);
Ok(port)
}
// Create a UDP listener on a random open port, returning the port number.
async fn get_free_port(&self) -> color_eyre::Result {
// By passing 0 to create_port_listener, the OS will choose a port for us.
self.create_port_socket(0).await
}
// Handle changes to the proxy ports, creating/deleting listeners as needed.
fn update_ports(&self, ports: Vec) {
// Find the ports listening to the localhost address
let mut ports: HashSet = ports.into_iter().collect();
// Remove any socket tasks not in the list of localhost port
self.tasks.retain(|port, _| ports.contains(port));
// Find the list of new ports
ports.retain(|port| !self.tasks.contains_key(port));
if !ports.is_empty() {
let clone = Arc::clone(self);
// Create port listeners for the new ports
tokio::spawn(async move {
for port in ports.into_iter() {
if let Err(error) = clone.create_port_socket(port).await {
#[cfg(not(coverage_nightly))]
tracing::error!(%port, %error, "Failed to create listener for UDP port.");
}
}
});
}
}
}