// 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::{
future,
net::SocketAddr,
sync::{Arc, Mutex, RwLock, atomic::AtomicUsize},
time::{Duration, Instant},
};
use color_eyre::eyre::Context;
use hyper::{Request, body::Incoming, service::service_fn};
use hyper_util::{
rt::{TokioExecutor, TokioIo},
server::conn::auto,
};
use metrics::{counter, gauge};
use rand::{RngExt, SeedableRng};
use rand_chacha::ChaCha20Rng;
use russh::{
keys::{
decode_secret_key,
ssh_key::{LineEnding, private::Ed25519Keypair},
},
server::Config,
};
use rustls::ServerConfig;
#[cfg(feature = "acme")]
use rustls_acme::acme::ACME_TLS_ALPN_NAME;
use rustls_pki_types::ServerName;
use sandhole_socket::tcp_listener::{get_tcp_listener, get_tcp_listener_with_keepalive};
use socket2::TcpKeepalive;
use sysinfo::{CpuRefreshKind, MemoryRefreshKind, Networks, RefreshKind, System};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::{
fs,
io::copy_bidirectional_with_sizes,
net::TcpStream,
pin,
time::{interval, timeout},
};
use tokio_rustls::TlsAcceptor;
use tokio_util::sync::CancellationToken;
use webpki::EndEntityCert;
#[cfg(feature = "acme")]
use crate::acme::{AcmeResolver, AlpnAcmeResolver};
#[cfg(feature = "prometheus")]
use crate::admin::connection_handler::get_prometheus_service;
#[cfg(feature = "login")]
use crate::login::ApiLogin;
#[cfg_attr(not(feature = "prometheus"), allow(unused_imports))]
use crate::quota::TokenHolder;
#[cfg(feature = "login")]
use crate::webpki::WebpkiVerifierConfigurer;
use crate::{
AdminNotification, BindHostnames, SandholeServer, SystemData, TunnelingProxyData,
addressing::{AddressDelegator, DnsResolver},
certificates::{AlpnChallengeResolver, CertificateResolver, DummyAlpnChallengeResolver},
config::ApplicationConfig,
connection_handler::ConnectionHandler,
connections::{ConnectionMap, HttpAliasingConnection},
droppable_handle::DroppableHandle,
error::ServerError,
fingerprints::FingerprintsValidator,
http::{DomainRedirect, Protocol, ProxyData, ProxyType, proxy_handler},
ip::{IpFilter, IpFilterConfig},
quota::{DummyQuotaHandler, QuotaHandler, QuotaMap},
reactor::{AliasReactor, HttpReactor, SniReactor, SshReactor, TcpReactor, UdpReactor},
ssh::Server,
tcp::TcpHandler,
telemetry::{
TELEMETRY_COUNTER_NETWORK_RX, TELEMETRY_COUNTER_NETWORK_TX,
TELEMETRY_COUNTER_SNI_CONNECTIONS, TELEMETRY_GAUGE_CPU_USAGE, TELEMETRY_GAUGE_TOTAL_MEMORY,
TELEMETRY_GAUGE_USED_MEMORY, TELEMETRY_KEY_HOSTNAME, Telemetry,
},
tls::{ClientHelloStatus, RewindStream, TlsPeekData, parse_client_hello},
udp::UdpHandler,
};
#[cfg_attr(not(feature = "prometheus"), allow(unused_imports))]
use crate::{
admin::{ADMIN_ALIAS_PORT, connection_handler::AdminAliasHandler},
sock_addr_alias::SockAddrAlias,
};
#[doc(hidden)]
// Main entrypoint of the application.
pub async fn entrypoint(config: ApplicationConfig) -> color_eyre::Result<()> {
#[cfg(not(coverage_nightly))]
tracing::info!("Starting Sandhole...");
// Check configuration flags for issues or other operations
if config.disable_http && config.disable_tcp && config.disable_udp && config.disable_aliasing {
return Err(ServerError::InvalidConfig(
"One of HTTP, TCP, UDP, or aliasing must be enabled".into(),
)
.into());
}
if config.force_https {
if config.disable_http {
return Err(ServerError::InvalidConfig(
"--force-https is incompatible with --disable-http".into(),
)
.into());
}
if config.disable_https {
return Err(ServerError::InvalidConfig(
"--force-https is incompatible with --disable-https".into(),
)
.into());
}
}
if config.mode.no_domain {
if config.allow_requested_subdomains {
#[cfg(not(coverage_nightly))]
tracing::warn!("--allow-requested-subdomains has no effect with --no-domain");
}
#[cfg(feature = "rustrict")]
if config.random_subdomain_filter_profanities {
#[cfg(not(coverage_nightly))]
tracing::warn!("--random-subdomain-filter-profanities has no effect with --no-domain");
}
if config.random_subdomain_seed.is_some() {
#[cfg(not(coverage_nightly))]
tracing::warn!("--random-subdomain-seed has no effect with --no-domain");
}
if config.random_subdomain_value.is_some() {
#[cfg(not(coverage_nightly))]
tracing::warn!("--random-subdomain-value has no effect with --no-domain");
}
if config.random_subdomain_value_file.is_some() {
#[cfg(not(coverage_nightly))]
tracing::warn!("--random-subdomain-value-file has no effect with --no-domain");
}
if config.bind_hostnames == BindHostnames::Cname {
return Err(ServerError::InvalidConfig(
"Cannot set --bind-hostnames=cname without --domain".into(),
)
.into());
}
}
let http_request_timeout = config.http_request_timeout;
let tcp_connection_timeout = config.tcp_connection_timeout;
let log_format = config.log_format;
let buffer_size = usize::try_from(config.buffer_size)
.with_context(|| "Cannot convert buffer size to usize")?;
// Initialize crypto and credentials
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
// Find the private SSH key for Sandhole or create a new one.
let key = match fs::read_to_string(config.private_key_file.as_path()).await {
Ok(key) => decode_secret_key(&key, None).with_context(|| "Error decoding secret key")?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
#[cfg(not(coverage_nightly))]
tracing::info!("Key file not found. Creating...");
let key = russh::keys::PrivateKey::from(Ed25519Keypair::from_seed(
&ChaCha20Rng::from_rng(&mut rand::rng()).random(),
));
if !config.disable_directory_creation {
fs::create_dir_all(
config
.private_key_file
.as_path()
.parent()
.ok_or(ServerError::InvalidFilePath)
.with_context(|| "Error parsing secret key path")?,
)
.await
.with_context(|| "Error creating secret key directory")?;
}
let key_string = key.to_openssh(LineEnding::LF)?;
let key = decode_secret_key(&key_string, None)
.with_context(|| "Error decoding secret key")?;
fs::write(config.private_key_file.as_path(), key_string)
.await
.with_context(|| "Error saving secret key to filesystem")?;
key
}
Err(error) => return Err(error).with_context(|| "Error reading secret key"),
};
// Initialize modules
if !config.disable_directory_creation {
fs::create_dir_all(config.user_keys_directory.as_path())
.await
.with_context(|| "Error creating user keys directory")?;
fs::create_dir_all(config.admin_keys_directory.as_path())
.await
.with_context(|| "Error creating admin keys directory")?;
}
// Listen on the user_keys and admin_keys directories for new SSH public keys.
let fingerprints = FingerprintsValidator::watch(
config.user_keys_directory,
config.admin_keys_directory,
config.directory_poll_interval,
)
.await
.with_context(|| "Error setting up public keys watcher")?;
// Initialize the login API service if a URL has been set.
#[cfg(feature = "login")]
let api_login = config
.password_authentication_url
.map(|url| {
ApiLogin::builder()
.configurer(WebpkiVerifierConfigurer)
.endpoint(url)
.maybe_timeout(http_request_timeout)
.use_system_ca(config.use_system_ca)
.build()
})
.transpose()
.with_context(|| "Error intializing login API")?;
// Initialize the ACME ALPN service if a contact email has been provided.
#[cfg(feature = "acme")]
let alpn_resolver: Box = match config.acme_contact_email {
_ if config.disable_https => Box::new(DummyAlpnChallengeResolver),
Some(contact) if u16::from(config.https_port) == 443 => Box::new(AcmeResolver::new(
AlpnAcmeResolver,
config.acme_cache_directory,
contact,
config.acme_use_staging,
config.use_system_ca,
)),
Some(_) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(
"ACME challenges are only supported on HTTPS port 443 (currently {}). Disabling.",
config.https_port
);
Box::new(DummyAlpnChallengeResolver)
}
None => Box::new(DummyAlpnChallengeResolver),
};
#[cfg(not(feature = "acme"))]
let alpn_resolver: Box = Box::new(DummyAlpnChallengeResolver);
if !config.disable_directory_creation {
fs::create_dir_all(config.certificates_directory.as_path())
.await
.with_context(|| "Error creating certificates directory")?;
}
// Listen on the certificates sub-directories for updates to Let's Encrypt certificates.
let certificates = Arc::new(
CertificateResolver::watch(
config.certificates_directory,
RwLock::new(alpn_resolver),
config.directory_poll_interval,
)
.await
.with_context(|| "Error setting up certificates watcher")?,
);
// Initialize the IP address allowlist/blocklist service.
let ip_filter = Arc::new(IpFilter::from(IpFilterConfig {
allowlist: config.ip_allowlist,
blocklist: config.ip_blocklist,
})?);
#[cfg(feature = "prometheus")]
let telemetry = Arc::new(Telemetry::new(
!config.disable_aliasing && !config.disable_prometheus,
));
#[cfg(not(feature = "prometheus"))]
let telemetry = Arc::new(Telemetry::new(false));
#[cfg(feature = "prometheus")]
let prometheus_handle = match metrics::set_global_recorder(Arc::clone(&telemetry)) {
Ok(_) => {
telemetry.register_metrics();
Some(telemetry.prometheus_handle())
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Failed to install telemetry.");
None
}
};
#[cfg(not(feature = "prometheus"))]
if metrics::set_global_recorder(Arc::clone(&telemetry)).is_ok() {
telemetry.register_metrics();
}
let quota_handler: Arc> = match config.quota_per_user {
Some(max_quota) => Arc::new(Box::new(Arc::new(QuotaMap::new(max_quota.into())))),
None => Arc::new(Box::new(DummyQuotaHandler)),
};
let tcp_keepalive = if config.disable_tcp_keepalive {
None
} else {
Some(
TcpKeepalive::new()
.with_time(config.tcp_keepalive_time)
.with_interval(config.tcp_keepalive_interval),
)
};
let http_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.reactor(HttpReactor {
certificates: Arc::clone(&certificates),
telemetry: Arc::clone(&telemetry),
})
.build(),
);
let sni_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.reactor(SniReactor(Arc::clone(&telemetry)))
.build(),
);
let ssh_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.reactor(SshReactor(Arc::clone(&telemetry)))
.build(),
);
let tcp_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.build(),
);
let udp_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.build(),
);
let admin_alias_connections = Arc::new(
ConnectionMap::builder()
.strategy(crate::LoadBalancingStrategy::Deny)
.algorithm(crate::LoadBalancingAlgorithm::RoundRobin)
.quota_handler(Arc::new(Box::new(DummyQuotaHandler)))
.build(),
);
let alias_connections = Arc::new(
ConnectionMap::builder()
.strategy(config.load_balancing)
.algorithm(config.load_balancing_algorithm)
.quota_handler(Arc::clone("a_handler))
.reactor(AliasReactor(Arc::clone(&telemetry)))
.build(),
);
let tcp_handler: Arc = Arc::new(
TcpHandler::builder()
.listen_address(config.listen_address)
.conn_manager(Arc::clone(&tcp_connections))
.ip_filter(Arc::clone(&ip_filter))
.buffer_size(buffer_size)
.disable_tcp_logs(config.disable_tcp_logs)
.maybe_tcp_keepalive(tcp_keepalive.clone())
.maybe_tcp_connection_timeout(tcp_connection_timeout)
.build(),
);
// Add TCP handler service as a listener for TCP port updates.
tcp_connections.update_reactor(Some(TcpReactor {
handler: Arc::clone(&tcp_handler),
telemetry: Arc::clone(&telemetry),
}));
let udp_handler: Arc = Arc::new(
UdpHandler::builder()
.listen_address(config.listen_address)
.conn_manager(Arc::clone(&udp_connections))
.ip_filter(Arc::clone(&ip_filter))
.disable_udp_logs(config.disable_udp_logs)
.udp_timeout(config.udp_timeout)
.build(),
);
// Add udp handler service as a listener for udp port updates.
udp_connections.update_reactor(Some(UdpReactor {
handler: Arc::clone(&udp_handler),
telemetry: Arc::clone(&telemetry),
}));
// Add addressing service with optional profanity filtering
let addressing = Arc::new({
let builder = AddressDelegator::builder()
.resolver(DnsResolver::new()?)
.txt_record_prefix(config.txt_record_prefix)
.maybe_root_domain(config.mode.domain.clone())
.bind_hostnames(config.bind_hostnames)
.force_random_subdomains(!config.allow_requested_subdomains)
.maybe_random_subdomain_seed(config.random_subdomain_seed)
.random_subdomain_length(config.random_subdomain_length);
#[cfg(feature = "rustrict")]
let builder = builder
.random_subdomain_filter_profanities(config.random_subdomain_filter_profanities)
.requested_domain_filter_profanities(config.requested_domain_filter_profanities)
.requested_subdomain_filter_profanities(config.requested_subdomain_filter_profanities);
let seed = {
if let Some(path) = config.random_subdomain_value_file {
if config.random_subdomain_value.is_some() {
#[cfg(not(coverage_nightly))]
tracing::warn!(
"--random-subdomain-value-file is set; --random-subdomain-value will be ignored."
);
}
let data = fs::read_to_string(path)
.await
.with_context(|| "Failed to read --random-subdomain-value-file")?;
let seed = data
.trim()
.parse()
.with_context(|| "Unable to parse --random-subdomain-value-file as u64")?;
Some(seed)
} else {
config.random_subdomain_value
}
};
if let Some(seed) = seed {
builder.seed(seed).build()
} else {
builder.build()
}
});
// Configure the default domain redirect for Sandhole.
let domain_redirect = config.mode.domain.clone().map(|from| {
Arc::new(DomainRedirect {
from,
to: config.domain_redirect,
})
});
// Telemetry tasks
let ssh_data = Arc::new(Mutex::default());
if !config.disable_aliasing {
let data_clone = Arc::clone(&ssh_data);
let connections_clone = Arc::clone(&ssh_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update SSH data, based on the connection map.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let data = connections_clone.data();
let telemetry_per_minute = telemetry_clone.get_ssh_connections_per_minute();
let telemetry_current = telemetry_clone.get_current_ssh_connections();
let data = data
.into_iter()
.map(|(alias, addresses)| {
let connections_per_minute = telemetry_per_minute
.get(&alias)
.copied()
.unwrap_or_default();
let current_connections =
telemetry_current.get(&alias).copied().unwrap_or_default();
(
alias,
(addresses, connections_per_minute, current_connections),
)
})
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
}
let http_data = Arc::new(Mutex::default());
let sni_data = Arc::new(Mutex::default());
if !config.disable_http {
let data_clone = Arc::clone(&http_data);
let connections_clone = Arc::clone(&http_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update HTTP data, based on the connection map and the telemetry counters.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let data = connections_clone.data();
let telemetry = telemetry_clone.get_http_requests_per_minute();
let data = data
.into_iter()
.map(|(hostname, addresses)| {
let requests_per_minute =
telemetry.get(&hostname).copied().unwrap_or_default();
(hostname, (addresses, requests_per_minute))
})
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
if !config.disable_sni {
let data_clone = Arc::clone(&sni_data);
let connections_clone = Arc::clone(&sni_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update SNI data, based on the connection map and the telemetry counters.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let data = connections_clone.data();
let telemetry_per_minute = telemetry_clone.get_sni_connections_per_minute();
let telemetry_current = telemetry_clone.get_current_sni_connections();
let data = data
.into_iter()
.map(|(hostname, addresses)| {
let connections_per_minute = telemetry_per_minute
.get(&hostname)
.copied()
.unwrap_or_default();
let current_connections = telemetry_current
.get(&hostname)
.copied()
.unwrap_or_default();
(
hostname,
(addresses, connections_per_minute, current_connections),
)
})
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
}
}
let tcp_data = Arc::new(Mutex::default());
if !config.disable_tcp {
let data_clone = Arc::clone(&tcp_data);
let connections_clone = Arc::clone(&tcp_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update TCP data, based on the connection map.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let data = connections_clone.data();
let telemetry_per_minute = telemetry_clone.get_tcp_connections_per_minute();
let telemetry_current = telemetry_clone.get_current_tcp_connections();
let data = data
.into_iter()
.map(|(port, addresses)| {
let connections_per_minute =
telemetry_per_minute.get(&port).copied().unwrap_or_default();
let current_connections =
telemetry_current.get(&port).copied().unwrap_or_default();
(
port,
(addresses, connections_per_minute, current_connections),
)
})
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
}
let udp_data = Arc::new(Mutex::default());
if !config.disable_udp {
let data_clone = Arc::clone(&udp_data);
let connections_clone = Arc::clone(&udp_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update UDP data, based on the connection map.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let data = connections_clone.data();
let telemetry_per_minute = telemetry_clone.get_udp_connections_per_minute();
let telemetry_current = telemetry_clone.get_current_udp_connections();
let data = data
.into_iter()
.map(|(port, addresses)| {
let connections_per_minute =
telemetry_per_minute.get(&port).copied().unwrap_or_default();
let current_connections =
telemetry_current.get(&port).copied().unwrap_or_default();
(
port,
(addresses, connections_per_minute, current_connections),
)
})
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
}
let alias_data = Arc::new(Mutex::default());
if !config.disable_aliasing {
let data_clone = Arc::clone(&alias_data);
let alias_connections_clone = Arc::clone(&alias_connections);
let admin_connections_clone = Arc::clone(&admin_alias_connections);
let telemetry_clone = Arc::clone(&telemetry);
// Periodically update alias data, based on the connection map.
tokio::spawn(async move {
let mut refresh_interval = interval(Duration::from_millis(3_000));
refresh_interval.tick().await;
loop {
refresh_interval.tick().await;
let alias_data = alias_connections_clone.data();
let admin_data = admin_connections_clone.data();
let telemetry_alias_per_minute = telemetry_clone.get_alias_connections_per_minute();
let telemetry_alias_current = telemetry_clone.get_current_alias_connections();
let telemetry_admin_alias_per_minute =
telemetry_clone.get_admin_alias_connections_per_minute();
let telemetry_admin_alias_current =
telemetry_clone.get_current_admin_alias_connections();
let data = alias_data
.into_iter()
.map(|(alias, addresses)| {
let connections_per_minute = telemetry_alias_per_minute
.get(&alias)
.copied()
.unwrap_or_default();
let current_connections = telemetry_alias_current
.get(&alias)
.copied()
.unwrap_or_default();
(
alias,
(addresses, connections_per_minute, current_connections),
)
})
.chain(admin_data.into_iter().map(|(alias, addresses)| {
let connections_per_minute = telemetry_admin_alias_per_minute
.get(&alias)
.copied()
.unwrap_or_default();
let current_connections = telemetry_admin_alias_current
.get(&alias)
.copied()
.unwrap_or_default();
(
alias,
(addresses, connections_per_minute, current_connections),
)
}))
.collect();
*data_clone.lock().expect("not poisoned") = data;
}
});
}
let system_data = Arc::new(Mutex::default());
let data_clone = Arc::clone(&system_data);
// Periodically update system data (every second, as to keep network TX/RX rates accurate).
tokio::spawn(async move {
let system_refresh = RefreshKind::nothing()
.with_cpu(CpuRefreshKind::nothing().with_usage())
.with_memory(MemoryRefreshKind::nothing().with_ram());
let mut system = match System::new_with_specifics(system_refresh) {
Ok(system) => system,
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Failed to inspect system.");
return;
}
};
let mut networks = match Networks::new_with_refreshed_list() {
Ok(networks) => networks,
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Failed to inspect networks.");
return;
}
};
let mut system_data_interval = interval(Duration::from_millis(1_000));
system_data_interval.tick().await;
loop {
let start = Instant::now();
system_data_interval.tick().await;
system.refresh_specifics(system_refresh);
networks.refresh(true);
let (network_tx, network_rx) = match networks
.values()
.map(|data| (data.transmitted(), data.received()))
.reduce(|acc, elem| (acc.0 + elem.0, acc.1 + elem.1))
{
Some((tx, rx)) => (tx, rx),
None => (0, 0),
};
let cpu_usage = system.global_cpu_usage() / system.cpus().len() as f32;
gauge!(TELEMETRY_GAUGE_CPU_USAGE).set(cpu_usage / 100.0);
let used_memory = system.used_memory();
gauge!(TELEMETRY_GAUGE_USED_MEMORY).set(used_memory as f64);
let total_memory = system.total_memory();
gauge!(TELEMETRY_GAUGE_TOTAL_MEMORY).set(total_memory as f64);
counter!(TELEMETRY_COUNTER_NETWORK_TX).increment(network_tx);
counter!(TELEMETRY_COUNTER_NETWORK_RX).increment(network_rx);
let data = SystemData {
cpu_usage,
used_memory,
total_memory,
network_tx,
network_rx,
duration: start.elapsed(),
};
*data_clone.lock().expect("not poisoned") = data;
}
});
let admin_notifications = Arc::new(Mutex::default());
let notifications_clone = Arc::clone(&admin_notifications);
let domain_clone = config.mode.domain.clone();
let certificates_clone = Arc::clone(&certificates);
// Periodically check for problems (every 10 seconds) and update notifications.
tokio::spawn(async move {
let mut system_data_interval = interval(Duration::from_millis(15_000));
let domain_server_name = domain_clone
.as_ref()
.and_then(|domain| ServerName::try_from(domain.as_str()).ok());
loop {
system_data_interval.tick().await;
let mut notifications = vec![];
if !config.disable_https
&& let Some(domain) = domain_clone.as_ref()
&& let Some(server_name) = domain_server_name.as_ref()
{
if let Some(cert_key) = certificates_clone.resolve_server_name(domain)
&& let Ok(cert) = cert_key.end_entity_cert()
&& let Ok(eec) = EndEntityCert::try_from(cert)
{
match eec.verify_is_valid_for_subject_name(server_name) {
Ok(()) => (),
Err(webpki::Error::CertExpired { .. }) => {
notifications
.push(AdminNotification::ExpiredCertificate(domain.clone()));
}
Err(_) => {
notifications.push(AdminNotification::InvalidTls(domain.clone()));
}
}
} else {
notifications.push(AdminNotification::NoCertificate(domain.clone()));
}
}
*notifications_clone.lock().expect("not poisoned") = notifications;
}
});
// SSH server
let ssh_config = Arc::new(Config {
auth_rejection_time: Duration::from_secs(2),
auth_rejection_time_initial: Some(Duration::from_secs(0)),
inactivity_timeout: Some(Duration::from_secs(3_600)),
keepalive_interval: Some(config.ssh_keepalive_interval),
keepalive_max: config.ssh_keepalive_max,
keys: vec![key],
maximum_packet_size: config.buffer_size,
..Default::default()
});
// Create the local forwarding-specific HTTP proxy data.
let aliasing_proxy_data = Arc::new(
ProxyData::builder()
.conn_manager(Arc::new(
HttpAliasingConnection::builder()
.http(Arc::clone(&http_connections))
.alias(Arc::clone(&alias_connections))
.build(),
))
.maybe_domain_redirect(domain_redirect.as_ref().map(Arc::clone))
// HTTP only.
.protocol(Protocol::Http {
port: config.http_port.into(),
})
// Always use aliasing channels instead of tunneling channels.
.proxy_type(ProxyType::Aliasing)
.maybe_pool_queue_timeout(config.pool_timeout)
.http_pool_size(config.http_pool_size)
.http_pool_max_idle_time(config.http_pool_max_idle_time)
.http_pool_max_reuse(config.http_pool_max_reuse)
.buffer_size(buffer_size)
.maybe_http_request_timeout(http_request_timeout)
.maybe_websocket_timeout(tcp_connection_timeout)
.disable_http_logs(config.disable_http_logs)
.log_format(log_format)
.build(),
);
let proxy_data = Arc::clone(&aliasing_proxy_data);
tokio::spawn(async move {
let mut cleanup_interval = interval(Duration::from_secs(300));
cleanup_interval.tick().await;
loop {
cleanup_interval.tick().await;
proxy_data.cleanup_keepalive_pools();
}
});
let mut sandhole = Arc::new(SandholeServer {
session_id: AtomicUsize::new(0),
sessions_password: Mutex::default(),
sessions_publickey: Mutex::default(),
http: Arc::clone(&http_connections),
sni: sni_connections,
ssh: ssh_connections,
tcp: tcp_connections,
udp: udp_connections,
admin_alias: admin_alias_connections,
alias: alias_connections,
http_data,
sni_data,
ssh_data,
tcp_data,
udp_data,
alias_data,
system_data,
admin_notifications,
aliasing_proxy_data,
fingerprints_validator: fingerprints,
#[cfg(feature = "login")]
api_login,
address_delegator: addressing,
tcp_handler,
udp_handler,
domain: config.mode.domain,
http_port: config.http_port.into(),
https_port: config.https_port.into(),
ssh_port: config.ssh_port.into(),
force_random_ports: !config.allow_requested_ports,
authenticate_any_key_as_user: config.authenticate_any_key_as_user,
disable_http: config.disable_http,
disable_https: config.disable_http || config.disable_https,
disable_sni: config.disable_http || config.disable_https || config.disable_sni,
disable_tcp: config.disable_tcp,
disable_udp: config.disable_udp,
disable_aliasing: config.disable_aliasing,
buffer_size,
pool_size: config.pool_size,
max_connections_per_ip: usize::from(config.max_simultaneous_connections_per_ip),
pool_timeout: config.pool_timeout,
rate_limit: config
.rate_limit_per_user
.map(|rate| rate as f64)
.unwrap_or(f64::INFINITY),
channel_open_timeout: config.channel_open_timeout,
#[cfg(feature = "login")]
authentication_request_timeout: config.authentication_request_timeout,
idle_connection_timeout: config.idle_connection_timeout,
unproxied_connection_timeout: config
.unproxied_connection_timeout
.unwrap_or(config.idle_connection_timeout),
tcp_connection_timeout,
});
// Admin aliases
#[cfg(feature = "prometheus")]
if let Some(Some(handle)) = prometheus_handle {
sandhole
.admin_alias
.insert(
SockAddrAlias("prometheus.sandhole".into(), ADMIN_ALIAS_PORT),
SocketAddr::from(([0, 0, 0, 0], 0)),
TokenHolder::System,
Arc::new(AdminAliasHandler {
handler: Arc::new(move || {
get_prometheus_service(handle.clone(), tcp_connection_timeout, buffer_size)
}),
}),
)
.expect("shouldn't fail to insert Prometheus admin alias");
}
// HTTP handler
let mut join_handle_http = if config.disable_http {
DroppableHandle(tokio::spawn(future::pending()))
} else {
let http_listener = {
if let Some(keepalive) = tcp_keepalive.clone() {
get_tcp_listener_with_keepalive(
(config.listen_address, config.http_port.into()),
keepalive,
)
} else {
get_tcp_listener((config.listen_address, config.http_port.into()))
}
}
.with_context(|| "Error listening to HTTP port")?;
#[cfg(not(coverage_nightly))]
tracing::info!(
"Listening for HTTP connections on port {}.",
config.http_port
);
let ip_filter_clone = Arc::clone(&ip_filter);
let http_proxy_data = Arc::new(
ProxyData::builder()
.conn_manager(Arc::clone(&http_connections))
.maybe_domain_redirect(domain_redirect.as_ref().map(Arc::clone))
// Use TLS redirect if --force-https is set, otherwise allow HTTP.
.protocol(if config.force_https {
Protocol::TlsRedirect {
from: config.http_port.into(),
to: config.https_port.into(),
}
} else {
Protocol::Http {
port: config.http_port.into(),
}
})
// Always use tunneling channels.
.proxy_type(ProxyType::Tunneling)
.maybe_pool_queue_timeout(config.pool_timeout)
.http_pool_size(config.http_pool_size)
.http_pool_max_idle_time(config.http_pool_max_idle_time)
.http_pool_max_reuse(config.http_pool_max_reuse)
.buffer_size(buffer_size)
.maybe_http_request_timeout(http_request_timeout)
.maybe_websocket_timeout(tcp_connection_timeout)
.disable_http_logs(config.disable_http_logs)
.log_format(log_format)
.build(),
);
let proxy_data = Arc::clone(&http_proxy_data);
tokio::spawn(async move {
let mut cleanup_interval = interval(Duration::from_secs(300));
cleanup_interval.tick().await;
loop {
cleanup_interval.tick().await;
proxy_data.cleanup_keepalive_pools();
}
});
DroppableHandle(tokio::spawn(async move {
loop {
let proxy_data = Arc::clone(&http_proxy_data);
let (stream, address) = match http_listener.accept().await {
Ok((stream, address)) => (stream, address),
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Unable to accept HTTP connection.");
break;
}
};
if !ip_filter_clone.is_allowed(address.ip()) {
#[cfg(not(coverage_nightly))]
tracing::info!(%address, "Rejecting HTTP connection: IP not allowed.");
continue;
}
// Create a Hyper service and serve over the accepted TCP connection.
let service = service_fn(move |req: Request| {
proxy_handler(req, address, None, Arc::clone(&proxy_data))
});
let io = TokioIo::new(stream);
tokio::spawn(async move {
let mut server = auto::Builder::new(TokioExecutor::new());
server.http1().pipeline_flush(true);
let conn = server.serve_connection_with_upgrades(io, service);
match tcp_connection_timeout {
Some(duration) => {
let _ = timeout(duration, conn).await;
}
None => {
let _ = conn.await;
}
}
});
}
}))
};
// HTTPS handler (with optional SSH handling)
let mut join_handle_https = if config.disable_http || config.disable_https {
DroppableHandle(tokio::spawn(future::pending()))
} else {
let https_listener = if let Some(keepalive) = tcp_keepalive.clone() {
get_tcp_listener_with_keepalive(
(config.listen_address, config.https_port.into()),
keepalive,
)
} else {
get_tcp_listener((config.listen_address, config.https_port.into()))
}
.with_context(|| "Error listening to HTTPS port")?;
#[cfg(not(coverage_nightly))]
tracing::info!(
"Listening for HTTPS connections on port {}.",
config.https_port
);
let certificates_clone = Arc::clone(&certificates);
let mut http11_server_config = ServerConfig::builder()
.with_no_client_auth()
.with_cert_resolver(certificates);
let mut http2_server_config = http11_server_config.clone();
http11_server_config
.alpn_protocols
.extend_from_slice(&[b"http/1.1".to_vec()]);
let http11_server_config = Arc::new(http11_server_config);
http2_server_config
.alpn_protocols
.extend_from_slice(&[b"h2".to_vec(), b"http/1.1".to_vec()]);
let http2_server_config = Arc::new(http2_server_config);
let ip_filter_clone = Arc::clone(&ip_filter);
let https_proxy_data = Arc::new(
ProxyData::builder()
.conn_manager(Arc::clone(&http_connections))
.maybe_domain_redirect(domain_redirect.as_ref().map(Arc::clone))
.protocol(Protocol::Https {
port: config.https_port.into(),
})
// Always use tunneling channels.
.proxy_type(ProxyType::Tunneling)
.maybe_pool_queue_timeout(config.pool_timeout)
.http_pool_size(config.http_pool_size)
.http_pool_max_idle_time(config.http_pool_max_idle_time)
.http_pool_max_reuse(config.http_pool_max_reuse)
.buffer_size(buffer_size)
.maybe_http_request_timeout(http_request_timeout)
.maybe_websocket_timeout(tcp_connection_timeout)
.disable_http_logs(config.disable_http_logs)
.log_format(log_format)
.build(),
);
let proxy_data = Arc::clone(&https_proxy_data);
tokio::spawn(async move {
let mut cleanup_interval = interval(Duration::from_secs(300));
cleanup_interval.tick().await;
loop {
cleanup_interval.tick().await;
proxy_data.cleanup_keepalive_pools();
}
});
let sandhole_clone = Arc::clone(&sandhole);
let ssh_config_clone = Arc::clone(&ssh_config);
DroppableHandle(tokio::spawn(async move {
loop {
let (stream, address) = match https_listener.accept().await {
Ok((stream, address)) => (stream, address),
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Unable to accept HTTPS connection.");
break;
}
};
if !ip_filter_clone.is_allowed(address.ip()) {
#[cfg(not(coverage_nightly))]
tracing::info!(%address, "Rejecting HTTPS connection: IP not allowed.");
continue;
}
let config = HandleHttpsConnectionConfig {
stream,
address,
connect_ssh_on_https_port: config.connect_ssh_on_https_port,
proxy_data: Arc::clone(&https_proxy_data),
ssh_config: Arc::clone(&ssh_config_clone),
sandhole: Arc::clone(&sandhole_clone),
certificates: Arc::clone(&certificates_clone),
http2_server_config: Arc::clone(&http2_server_config),
http11_server_config: Arc::clone(&http11_server_config),
};
tokio::spawn(handle_https_connection(config));
}
}))
};
// Start Sandhole on SSH port
let ssh_listener = if let Some(keepalive) = tcp_keepalive {
get_tcp_listener_with_keepalive((config.listen_address, config.ssh_port.into()), keepalive)
} else {
get_tcp_listener((config.listen_address, config.ssh_port.into()))
}
.with_context(|| "Error listening to SSH port")?;
#[cfg(not(coverage_nightly))]
tracing::info!("Listening for SSH connections on port {}.", config.ssh_port);
#[cfg(not(coverage_nightly))]
tracing::info!("Sandhole is now running.");
// Add OS signal handlers for termination.
let signal_handler = wait_for_signal();
pin!(signal_handler);
loop {
tokio::select! {
conn = ssh_listener.accept() => {
let (stream, address) = match conn {
Ok((stream, address)) => (stream, address),
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::error!(%error, "Unable to accept SSH connection.");
break;
},
};
if !ip_filter.is_allowed(address.ip()) {
#[cfg(not(coverage_nightly))]
tracing::info!(%address, "Rejecting SSH connection: IP not allowed.");
continue;
}
handle_ssh_connection(HandleSshConnectionConfig {
stream,
address,
config: Arc::clone(&ssh_config),
server: &mut sandhole,
});
}
_ = &mut signal_handler => {
break;
}
_ = &mut join_handle_http.0 => {
break;
}
_ = &mut join_handle_https.0 => {
break;
}
}
}
#[cfg(not(coverage_nightly))]
tracing::info!("Sandhole is shutting down.");
Ok(())
}
struct HandleHttpsConnectionConfig {
stream: TcpStream,
address: SocketAddr,
connect_ssh_on_https_port: bool,
proxy_data: TunnelingProxyData,
ssh_config: Arc,
sandhole: Arc,
certificates: Arc,
http2_server_config: Arc,
http11_server_config: Arc,
}
// Maximum number of bytes to buffer while waiting for a complete ClientHello
const MAX_CLIENT_HELLO_SIZE: usize = 1 << 15;
async fn handle_https_connection(
HandleHttpsConnectionConfig {
mut stream,
address,
connect_ssh_on_https_port,
proxy_data,
ssh_config,
mut sandhole,
certificates,
http2_server_config,
http11_server_config,
}: HandleHttpsConnectionConfig,
) {
let mut ssh_peek_buf = [0u8; 8];
let Ok(Ok(n)) = timeout(
sandhole.idle_connection_timeout,
stream.peek(&mut ssh_peek_buf),
)
.await
else {
return;
};
if connect_ssh_on_https_port && ssh_peek_buf[..n].starts_with(b"SSH-2.0-") {
// Handle as an SSH connection instead of HTTPS.
handle_ssh_connection(HandleSshConnectionConfig {
stream,
address,
config: Arc::clone(&ssh_config),
server: &mut sandhole,
});
return;
}
let mut consumed: Vec = Vec::with_capacity(4096);
let mut read_buf = [0u8; 4096];
let TlsPeekData { sni, alpn } = loop {
let n = match timeout(sandhole.idle_connection_timeout, stream.read(&mut read_buf)).await {
Ok(Ok(0)) | Ok(Err(_)) | Err(_) => return,
Ok(Ok(n)) => n,
};
consumed.extend_from_slice(&read_buf[..n]);
match parse_client_hello(&consumed) {
ClientHelloStatus::Ready(peek_data) => break peek_data,
ClientHelloStatus::Incomplete if consumed.len() <= MAX_CLIENT_HELLO_SIZE => (),
ClientHelloStatus::Incomplete => {
#[cfg(not(coverage_nightly))]
tracing::debug!(%address, "Rejecting HTTPS connection: ClientHello too large.");
return;
}
ClientHelloStatus::Invalid(alert) => {
if !alert.is_empty() {
let _ = stream.write_all(&alert).await;
}
let _ = stream.shutdown().await;
#[cfg(not(coverage_nightly))]
tracing::debug!(
%address,
"Rejecting HTTPS connection: invalid ClientHello or missing SNI."
);
return;
}
}
};
let mut stream = RewindStream::new(consumed, stream);
#[cfg(feature = "acme")]
if alpn == [ACME_TLS_ALPN_NAME] {
if let Some(challenge_config) = certificates.challenge_rustls_config() {
match TlsAcceptor::from(challenge_config).accept(stream).await {
Ok(mut tls) => {
let _ = tls.shutdown().await;
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%error, %sni, "Error accepting ACME challenge TLS stream.");
}
}
} else {
#[cfg(not(coverage_nightly))]
tracing::warn!("Unable to get ACME challenge TLS config.");
}
return;
}
#[cfg(not(feature = "acme"))]
let _ = certificates;
let ip = address.ip().to_canonical();
if let Some(tunnel_handler) = sandhole.sni.get(&sni, ip) {
let Ok(mut channel) = tunnel_handler.tunneling_channel(ip, address.port()).await else {
#[cfg(not(coverage_nightly))]
tracing::warn!(%sni, "Unable to get tunneling channel for SNI proxy.");
return;
};
counter!(TELEMETRY_COUNTER_SNI_CONNECTIONS, TELEMETRY_KEY_HOSTNAME => sni.clone())
.increment(1);
match sandhole.tcp_connection_timeout {
Some(duration) => {
let _ = timeout(
duration,
copy_bidirectional_with_sizes(
&mut stream,
&mut channel,
sandhole.buffer_size,
sandhole.buffer_size,
),
)
.await;
}
None => {
let _ = copy_bidirectional_with_sizes(
&mut stream,
&mut channel,
sandhole.buffer_size,
sandhole.buffer_size,
)
.await;
}
}
return;
};
if let Some(tunnel_handler) = sandhole.http.get(&sni, ip) {
let is_http2 = tunnel_handler
.http_data()
.map(|data| data.http2)
.unwrap_or_default()
&& alpn.iter().any(|alpn| alpn == b"h2");
if is_http2 {
match TlsAcceptor::from(http2_server_config).accept(stream).await {
Ok(stream) => {
// Create a Hyper service and serve over the accepted TLS connection.
let io = TokioIo::new(stream);
let service = service_fn(move |req: Request| {
proxy_handler(req, address, None, Arc::clone(&proxy_data))
});
let server = auto::Builder::new(TokioExecutor::new());
let conn = server.serve_connection_with_upgrades(io, service);
match sandhole.tcp_connection_timeout {
Some(duration) => {
let _ = timeout(duration, conn).await;
}
None => {
let _ = conn.await;
}
}
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%error, %address, "Error establishing TLS connection.");
}
};
} else {
match TlsAcceptor::from(http11_server_config).accept(stream).await {
Ok(stream) => {
// Create a Hyper service and serve over the accepted TLS connection.
let io = TokioIo::new(stream);
let service = service_fn(move |req: Request| {
proxy_handler(req, address, None, Arc::clone(&proxy_data))
});
let mut server = auto::Builder::new(TokioExecutor::new());
server.http1().pipeline_flush(true);
let conn = server.serve_connection_with_upgrades(io, service);
match sandhole.tcp_connection_timeout {
Some(duration) => {
let _ = timeout(duration, conn).await;
}
None => {
let _ = conn.await;
}
}
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%error, %address, "Error establishing TLS connection.");
}
};
};
} else {
match TlsAcceptor::from(http2_server_config).accept(stream).await {
Ok(stream) => {
// Create a Hyper service and serve over the accepted TLS connection.
let io = TokioIo::new(stream);
let service = service_fn(move |req: Request| {
proxy_handler(req, address, None, Arc::clone(&proxy_data))
});
let mut server = auto::Builder::new(TokioExecutor::new());
server.http1().pipeline_flush(true);
let conn = server.serve_connection_with_upgrades(io, service);
match sandhole.tcp_connection_timeout {
Some(duration) => {
let _ = timeout(duration, conn).await;
}
None => {
let _ = conn.await;
}
}
}
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%error, %address, "Error establishing TLS connection.");
}
};
}
}
struct HandleSshConnectionConfig<'a> {
stream: TcpStream,
address: SocketAddr,
config: Arc,
server: &'a mut Arc,
}
fn handle_ssh_connection(
HandleSshConnectionConfig {
stream,
address,
config,
server,
}: HandleSshConnectionConfig,
) {
let cancellation_token = CancellationToken::new();
// Create a new SSH handler.
let handler = server.new_client(address, cancellation_token.clone());
tokio::spawn(async move {
let mut session = match russh::server::run_stream(config, stream, handler).await {
Ok(session) => session,
Err(error) => {
#[cfg(not(coverage_nightly))]
tracing::warn!(%error, "Connection setup failed.");
return;
}
};
tokio::select! {
result = &mut session => {
if let Err(error) = result {
#[cfg(not(coverage_nightly))] tracing::warn!(%error, %address, "SSH connection closed.");
}
}
_ = cancellation_token.cancelled() => {
#[cfg(not(coverage_nightly))] tracing::info!(%address, "Disconnecting client...");
let _ = session.handle().disconnect(russh::Disconnect::ByApplication, "".into(), "English".into()).await;
},
}
});
}
#[cfg(unix)]
async fn wait_for_signal() {
use tokio::signal::unix::{SignalKind, signal};
let mut signal_terminate = signal(SignalKind::terminate()).expect("valid signal");
let mut signal_interrupt = signal(SignalKind::interrupt()).expect("valid signal");
tokio::select! {
_ = signal_terminate.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received SIGTERM.");
},
_ = signal_interrupt.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received SIGINT.");
},
};
}
#[cfg(windows)]
async fn wait_for_signal() {
use tokio::signal::windows;
let mut signal_c = windows::ctrl_c().expect("valid signal");
let mut signal_break = windows::ctrl_break().expect("valid signal");
let mut signal_close = windows::ctrl_close().expect("valid signal");
let mut signal_shutdown = windows::ctrl_shutdown().expect("valid signal");
tokio::select! {
_ = signal_c.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received CTRL_C.");
},
_ = signal_break.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received CTRL_BREAK.");
},
_ = signal_close.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received CTRL_CLOSE.");
},
_ = signal_shutdown.recv() => {
#[cfg(not(coverage_nightly))]
tracing::debug!("Received CTRL_SHUTDOWN.");
},
};
}