Lines
18.68 %
Functions
41.18 %
Branches
100 %
//! Nomisync SSH daemon.
//!
//! See `doc/sshd.org` for the full operator guide. Key defaults
//! (loopback-only bind, pubkey-preferred auth, no-forwarding policy)
//! live in this crate's documentation comments on each module.
mod accept;
mod auth;
mod eval_channel;
mod handler;
mod hostkey;
mod key_decoder;
#[cfg(test)]
mod key_decoder_tests;
mod metrics;
mod mouse_report;
mod mouse_report_tests;
mod pty_backend;
mod rate_limit;
mod tui_channel;
mod tui_transport;
use clap::Parser;
use russh::server::Config;
use std::ffi::OsString;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tracing::level_filters::LevelFilter;
#[derive(Parser, Debug)]
#[command(
name = "nomisync-sshd",
about = "Nomisync SSH TUI daemon",
long_about = "Nomisync SSH TUI daemon.\n\n\
Binds 127.0.0.1:2222 by default; the daemon accepts only \
PTY + shell and rejects exec, subsystem, port-forwarding, and \
X11. See doc/sshd.org for the operator guide (first-run \
host-key setup, adding user SSH keys, external exposure, \
hardened systemd unit)."
)]
struct Cli {
/// Address:port to bind. Loopback by default — explicit override
/// required for external exposure. Also honours
/// `NOMISYNC_SSHD_BIND` if set.
#[arg(long)]
bind: Option<SocketAddr>,
/// Path to the Ed25519 host-key file. Generated on first start
/// if missing. Also honours `NOMISYNC_SSHD_HOST_KEY` if set.
host_key: Option<PathBuf>,
/// Maximum *password* authentication attempts allowed per IP in
/// one window before subsequent attempts are refused.
#[arg(long, default_value_t = 6)]
max_auth_attempts_per_ip: u32,
/// Maximum *publickey* authentication attempts allowed per IP in
/// one window. Looser than the password bucket because a single
/// ssh client legitimately offers several identities per
/// connection.
#[arg(long, default_value_t = 30)]
max_pubkey_attempts_per_ip: u32,
/// Password-failures threshold that trips per-account lockout.
#[arg(long, default_value_t = 3)]
lockout_threshold: u32,
/// How long an account stays locked out, in seconds.
#[arg(long, default_value_t = 900)]
lockout_duration_secs: u64,
/// Public hostname this daemon answers on. Templated into the
/// post-`ssh-copy-id` ~/.ssh/config snippet sent to the client.
/// Honours `NOMISYNC_SSHD_HOSTNAME` if the flag is omitted.
public_hostname: Option<String>,
/// Public port this daemon answers on (matches the ingress TCP
/// service). Honours `NOMISYNC_SSHD_PORT`.
public_port: Option<u16>,
/// Host key fingerprint operators publish out-of-band. Templated
/// into the post-`ssh-copy-id` snippet so the client can verify
/// it on first connect. Honours `NOMISYNC_SSHD_HOST_FINGERPRINT`.
host_fingerprint: Option<String>,
/// Address:port to serve Prometheus `/metrics` on. No metrics
/// listener is opened when omitted.
metrics_bind: Option<SocketAddr>,
/// Most connections that may be unauthenticated at once; the rest are
/// dropped before the SSH banner. Logged-in sessions are not counted.
#[arg(long, default_value_t = 64, value_parser = clap::value_parser!(u16).range(1..=4096))]
max_startups: u16,
/// Seconds a connection has to authenticate before it is closed.
#[arg(long, default_value_t = 120, value_parser = clap::value_parser!(u64).range(1..=3600))]
pre_auth_timeout_secs: u64,
loglevel: Option<LevelFilter>,
/// Database connection URL. Defaults to `$DATABASE_URL` if
/// unset; omitted here only because clap won't happily read the
/// env in a default-value expression.
#[arg(short = 'd', long)]
database: Option<String>,
}
const DEFAULT_BIND: &str = "127.0.0.1:2222";
const DEFAULT_HOST_KEY: &str = "/etc/nomisync/ssh_host_ed25519_key";
fn resolve_bind(cli_value: Option<SocketAddr>) -> Result<SocketAddr, std::net::AddrParseError> {
pick_bind(cli_value, std::env::var("NOMISYNC_SSHD_BIND").ok())
fn pick_bind(
cli_value: Option<SocketAddr>,
env_value: Option<String>,
) -> Result<SocketAddr, std::net::AddrParseError> {
cli_value.map_or_else(|| env_value.as_deref().unwrap_or(DEFAULT_BIND).parse(), Ok)
fn resolve_host_key(cli_value: Option<PathBuf>) -> PathBuf {
pick_host_key(cli_value, std::env::var_os("NOMISYNC_SSHD_HOST_KEY"))
fn pick_host_key(cli_value: Option<PathBuf>, env_value: Option<OsString>) -> PathBuf {
cli_value
.or_else(|| env_value.map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from(DEFAULT_HOST_KEY))
fn resolve_str_or_env(cli_value: Option<String>, env: &str, fallback: &str) -> String {
.or_else(|| std::env::var(env).ok())
.unwrap_or_else(|| fallback.to_string())
fn resolve_port_or_env(cli_value: Option<u16>, env: &str, bind: SocketAddr) -> u16 {
.or_else(|| {
std::env::var(env)
.ok()
.and_then(|raw| raw.parse::<u16>().ok())
})
.unwrap_or_else(|| bind.port())
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
server::telemetry::init_logging(cli.loglevel, LevelFilter::INFO)?;
cli_core::start_server(cli.database, None).await?;
let bind = resolve_bind(cli.bind)?;
let host_key_path = resolve_host_key(cli.host_key);
let host_key = hostkey::load_or_generate(host_key_path.as_path())?;
let limiter = Arc::new(tokio::sync::Mutex::new(rate_limit::RateLimiter::new(
rate_limit::Config {
max_attempts_per_ip: cli.max_auth_attempts_per_ip,
max_pubkey_attempts_per_ip: cli.max_pubkey_attempts_per_ip,
window: Duration::from_mins(1),
account_lockout_threshold: cli.lockout_threshold,
account_lockout_duration: Duration::from_secs(cli.lockout_duration_secs),
},
rate_limit::InstantClock,
)));
let connect_info = handler::SshConnectInfo {
hostname: resolve_str_or_env(
cli.public_hostname,
"NOMISYNC_SSHD_HOSTNAME",
&bind.ip().to_string(),
),
port: resolve_port_or_env(cli.public_port, "NOMISYNC_SSHD_PORT", bind),
host_fingerprint: resolve_str_or_env(
cli.host_fingerprint,
"NOMISYNC_SSHD_HOST_FINGERPRINT",
"(not configured)",
};
let mut state = handler::SshdState {
limiter,
connect_info,
let config = Arc::new(Config {
inactivity_timeout: Some(Duration::from_mins(10)),
auth_rejection_time: Duration::from_secs(2),
keys: vec![host_key],
..Config::default()
});
let listener = TcpListener::bind(bind).await?;
tracing::info!("nomisync-sshd listening on {bind}");
if !bind.ip().is_loopback() {
tracing::warn!(
"bind {bind} is not loopback — this daemon has no TLS, no \
brute-force protection beyond per-IP rate limiting; expose \
deliberately."
);
let metrics = metrics::start(cli.metrics_bind, || {
server::telemetry::recorder::install_recorder().map_err(std::io::Error::other)
.await?;
if metrics.is_some() {
tokio::spawn(server::telemetry::pools::run_pool_sampler());
let limits = accept::AcceptLimits {
max_startups: usize::from(cli.max_startups),
pre_auth: Duration::from_secs(cli.pre_auth_timeout_secs),
accept::serve(&mut state, config, &listener, limits).await;
Ok(())
mod accept_tests;
mod eval_limit_tests;
mod eval_subsystem_tests;
mod metrics_tests;
mod pty_backend_tests;
mod tests;
mod tui_channel_tests;
mod tui_chart_tests;
mod tui_input_tests;
mod tui_mouse_tests;
mod tui_panic_tests;
mod tui_resize_tests;
mod tui_session;
mod tui_transport_tests;
mod upload_cap_tests;