// 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 .
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
//!
#![doc = include_str!("../README.md")]
//!
#![doc(html_logo_url = "https://sandhole.com.br/favicon.png")]
use std::{
collections::{BTreeMap, HashMap},
net::SocketAddr,
sync::{Arc, Mutex, atomic::AtomicUsize},
time::Duration,
};
use ahash::RandomState;
use async_speed_limit::Limiter;
use hyper::body::Incoming;
use russh::keys::ssh_key::Fingerprint;
use tokio_util::sync::CancellationToken;
use crate::{
addressing::{AddressDelegator, DnsResolver},
admin::connection_handler::AdminAliasHandler,
connections::{ConnectionMap, HttpAliasingConnection},
fingerprints::FingerprintsValidator,
http::ProxyData,
quota::TokenHolderUser,
reactor::{AliasReactor, HttpReactor, SniReactor, SshReactor, TcpReactor, UdpReactor},
sock_addr_alias::SockAddrAlias,
ssh::connection_handler::{SshChannel, SshTunnelHandler},
tcp::TcpHandler,
udp::UdpHandler,
};
#[doc(hidden)]
pub use crate::{
config::{
ApplicationConfig, BindHostnames, LoadBalancingAlgorithm, LoadBalancingStrategy, LogFormat,
RandomSubdomainSeed,
},
entrypoint::entrypoint,
};
#[cfg(feature = "acme")]
mod acme;
mod addressing;
mod admin;
mod certificates;
mod config;
mod connection_handler;
mod connections;
mod directory;
mod droppable_handle;
mod entrypoint;
mod error;
mod fingerprints;
mod http;
mod ip;
mod keepalive;
#[cfg(feature = "login")]
mod login;
mod quota;
mod reactor;
mod sock_addr_alias;
mod ssh;
mod tcp;
mod telemetry;
mod tls;
mod udp;
mod webpki;
// Data collected from the system and displayed on the admin interface.
#[derive(Default, Clone)]
struct SystemData {
used_memory: u64,
total_memory: u64,
network_tx: u64,
network_rx: u64,
cpu_usage: f32,
duration: Duration,
}
// A list of sessions and their cancelation channels.
type SessionMap = (Limiter, HashMap);
// A generic table with data for the admin interface.
type DataTable = Arc>>;
// Helper type for HTTP proxy data types.
type HttpProxyData = Arc, SshTunnelHandler, SshChannel>>;
// HTTP proxy data used by the tunneling connections.
type TunnelingProxyData = HttpProxyData, HttpReactor>>;
// HTTP proxy data used by the local forwarding aliasing connections.
type AliasingProxyData = HttpProxyData;
// Notifications displayed in the admin interface.
#[derive(Clone)]
pub(crate) enum AdminNotification {
ExpiredCertificate(String),
InvalidTls(String),
NoCertificate(String),
}
pub(crate) struct SandholeServer {
// A unique ID assigned for each SSH session.
pub(crate) session_id: AtomicUsize,
// A map of all sessions for a given user authenticated with a username+password pair.
pub(crate) sessions_password: Mutex>,
// A map of all sessions for a given user authenticated with a public key.
pub(crate) sessions_publickey: Mutex>,
// The map for forwarded SSH connections.
pub(crate) ssh: Arc, SshReactor>>,
// The map for forwarded HTTP connections.
pub(crate) http: Arc, HttpReactor>>,
// The map for forwarded SNI connections.
pub(crate) sni: Arc, SniReactor>>,
// The map for forwarded TCP connections.
pub(crate) tcp: Arc, TcpReactor>>,
// The map for forwarded UDP connections.
pub(crate) udp: Arc, UdpReactor>>,
// The map for admin aliased connections.
pub(crate) admin_alias: Arc, AliasReactor>>,
// The map for forwarded aliased connections.
pub(crate) alias: Arc, AliasReactor>>,
// Data related to the SSH forwardings for the admin interface.
pub(crate) ssh_data: DataTable, u64, f64)>,
// Data related to the HTTP forwardings for the admin interface.
pub(crate) http_data: DataTable, u64)>,
// Data related to the SNI forwardings for the admin interface.
pub(crate) sni_data: DataTable, u64, f64)>,
// Data related to the TCP forwardings for the admin interface.
pub(crate) tcp_data: DataTable, u64, f64)>,
// Data related to the UDP forwardings for the admin interface.
pub(crate) udp_data: DataTable, u64, f64)>,
// Data related to the alias forwardings for the admin interface.
pub(crate) alias_data:
DataTable, u64, f64)>,
// System data for the admin interface.
pub(crate) system_data: Arc>,
// Warnings for the admin interface.
pub(crate) admin_notifications: Arc>>,
// HTTP proxy data used by the local forwarding aliasing connections.
pub(crate) aliasing_proxy_data: AliasingProxyData,
// Service for validating fingerprint authentications and automatically update its data when the filesystem changes.
pub(crate) fingerprints_validator: FingerprintsValidator,
// Service for user+password authentication via a login API via a config-provided URL.
#[cfg(feature = "login")]
pub(crate) api_login: Option>,
// Service for assigning automatic addresses according to the addressing policies.
pub(crate) address_delegator: Arc>,
// Service for handling opening and closing TCP sockets for non-aliased services.
pub(crate) tcp_handler: Arc,
// Service for handling opening and closing UDP sockets.
pub(crate) udp_handler: Arc,
// The base domain of Sandhole.
pub(crate) domain: Option,
// Which port Sandhole listens to for HTTP connections.
pub(crate) http_port: u16,
// Which port Sandhole listens to for HTTPS connections.
pub(crate) https_port: u16,
// Which port Sandhole listens to for SSH connections.
pub(crate) ssh_port: u16,
// If true, allows users to select the TCP ports assigned by tcp_handler.
pub(crate) force_random_ports: bool,
// If true, any SSH key is authenticated as a user instead of not authenticating.
pub(crate) authenticate_any_key_as_user: bool,
// If true, HTTP is disabled.
pub(crate) disable_http: bool,
// If true, HTTPS is disabled.
pub(crate) disable_https: bool,
// If true, SNI is disabled.
pub(crate) disable_sni: bool,
// If true, TCP is disabled for all ports except for HTTP.
pub(crate) disable_tcp: bool,
// If true, UDP is disabled for all ports.
pub(crate) disable_udp: bool,
// If true, aliasing is disabled, including SSH and all local forwarding connections.
pub(crate) disable_aliasing: bool,
// Buffer size for bidirectional copying.
pub(crate) buffer_size: usize,
// Pool size for SSH handlers.
pub(crate) pool_size: usize,
// Maximum simultaneous connections per IP for SSH handlers.
pub(crate) max_connections_per_ip: usize,
// Rate limit per second for services of a single user.
pub(crate) rate_limit: f64,
// How long to wait for SSH clients to confirm a forwarded channel open.
pub(crate) channel_open_timeout: Duration,
// How long until a login API request is timed out.
#[cfg(feature = "login")]
pub(crate) authentication_request_timeout: Duration,
// How long until an unauthed connection is closed.
pub(crate) idle_connection_timeout: Duration,
// How long until an unauthed connection is closed AFTER it successfully local forwards.
pub(crate) unproxied_connection_timeout: Duration,
// How long until TCP, WebSocket, and local forwarding connections are closed.
pub(crate) tcp_connection_timeout: Option,
// How long should a connection wait for a spot in the pool before being timed out.
pub(crate) pool_timeout: Option,
}
impl SandholeServer {
// Returns true if the address is an alias and not localhost/empty/*
pub(crate) fn is_alias(&self, address: &str) -> bool {
address != "localhost"
&& !address.is_empty()
&& address != "*"
&& self.domain.as_ref().is_some_and(|domain| address != domain)
}
}