1
//! Nomisync SSH daemon.
2
//!
3
//! See `doc/sshd.org` for the full operator guide. Key defaults
4
//! (loopback-only bind, pubkey-preferred auth, no-forwarding policy)
5
//! live in this crate's documentation comments on each module.
6

            
7
mod accept;
8
mod auth;
9
mod eval_channel;
10
mod handler;
11
mod hostkey;
12
mod key_decoder;
13
#[cfg(test)]
14
mod key_decoder_tests;
15
mod metrics;
16
mod mouse_report;
17
#[cfg(test)]
18
mod mouse_report_tests;
19
mod pty_backend;
20
mod rate_limit;
21
mod tui_channel;
22
mod tui_transport;
23

            
24
use clap::Parser;
25
use russh::server::Config;
26
use std::ffi::OsString;
27
use std::net::SocketAddr;
28
use std::path::PathBuf;
29
use std::sync::Arc;
30
use std::time::Duration;
31
use tokio::net::TcpListener;
32
use tracing::level_filters::LevelFilter;
33

            
34
#[derive(Parser, Debug)]
35
#[command(
36
    name = "nomisync-sshd",
37
    about = "Nomisync SSH TUI daemon",
38
    long_about = "Nomisync SSH TUI daemon.\n\n\
39
        Binds 127.0.0.1:2222 by default; the daemon accepts only \
40
        PTY + shell and rejects exec, subsystem, port-forwarding, and \
41
        X11. See doc/sshd.org for the operator guide (first-run \
42
        host-key setup, adding user SSH keys, external exposure, \
43
        hardened systemd unit)."
44
)]
45
struct Cli {
46
    /// Address:port to bind. Loopback by default — explicit override
47
    /// required for external exposure. Also honours
48
    /// `NOMISYNC_SSHD_BIND` if set.
49
    #[arg(long)]
50
    bind: Option<SocketAddr>,
51

            
52
    /// Path to the Ed25519 host-key file. Generated on first start
53
    /// if missing. Also honours `NOMISYNC_SSHD_HOST_KEY` if set.
54
    #[arg(long)]
55
    host_key: Option<PathBuf>,
56

            
57
    /// Maximum *password* authentication attempts allowed per IP in
58
    /// one window before subsequent attempts are refused.
59
    #[arg(long, default_value_t = 6)]
60
    max_auth_attempts_per_ip: u32,
61

            
62
    /// Maximum *publickey* authentication attempts allowed per IP in
63
    /// one window. Looser than the password bucket because a single
64
    /// ssh client legitimately offers several identities per
65
    /// connection.
66
    #[arg(long, default_value_t = 30)]
67
    max_pubkey_attempts_per_ip: u32,
68

            
69
    /// Password-failures threshold that trips per-account lockout.
70
    #[arg(long, default_value_t = 3)]
71
    lockout_threshold: u32,
72

            
73
    /// How long an account stays locked out, in seconds.
74
    #[arg(long, default_value_t = 900)]
75
    lockout_duration_secs: u64,
76

            
77
    /// Public hostname this daemon answers on. Templated into the
78
    /// post-`ssh-copy-id` ~/.ssh/config snippet sent to the client.
79
    /// Honours `NOMISYNC_SSHD_HOSTNAME` if the flag is omitted.
80
    #[arg(long)]
81
    public_hostname: Option<String>,
82

            
83
    /// Public port this daemon answers on (matches the ingress TCP
84
    /// service). Honours `NOMISYNC_SSHD_PORT`.
85
    #[arg(long)]
86
    public_port: Option<u16>,
87

            
88
    /// Host key fingerprint operators publish out-of-band. Templated
89
    /// into the post-`ssh-copy-id` snippet so the client can verify
90
    /// it on first connect. Honours `NOMISYNC_SSHD_HOST_FINGERPRINT`.
91
    #[arg(long)]
92
    host_fingerprint: Option<String>,
93

            
94
    /// Address:port to serve Prometheus `/metrics` on. No metrics
95
    /// listener is opened when omitted.
96
    #[arg(long)]
97
    metrics_bind: Option<SocketAddr>,
98

            
99
    /// Most connections that may be unauthenticated at once; the rest are
100
    /// dropped before the SSH banner. Logged-in sessions are not counted.
101
    #[arg(long, default_value_t = 64, value_parser = clap::value_parser!(u16).range(1..=4096))]
102
    max_startups: u16,
103

            
104
    /// Seconds a connection has to authenticate before it is closed.
105
    #[arg(long, default_value_t = 120, value_parser = clap::value_parser!(u64).range(1..=3600))]
106
    pre_auth_timeout_secs: u64,
107

            
108
    #[arg(long)]
109
    loglevel: Option<LevelFilter>,
110

            
111
    /// Database connection URL. Defaults to `$DATABASE_URL` if
112
    /// unset; omitted here only because clap won't happily read the
113
    /// env in a default-value expression.
114
    #[arg(short = 'd', long)]
115
    database: Option<String>,
116
}
117

            
118
const DEFAULT_BIND: &str = "127.0.0.1:2222";
119
const DEFAULT_HOST_KEY: &str = "/etc/nomisync/ssh_host_ed25519_key";
120

            
121
1
fn resolve_bind(cli_value: Option<SocketAddr>) -> Result<SocketAddr, std::net::AddrParseError> {
122
1
    pick_bind(cli_value, std::env::var("NOMISYNC_SSHD_BIND").ok())
123
1
}
124

            
125
5
fn pick_bind(
126
5
    cli_value: Option<SocketAddr>,
127
5
    env_value: Option<String>,
128
5
) -> Result<SocketAddr, std::net::AddrParseError> {
129
5
    cli_value.map_or_else(|| env_value.as_deref().unwrap_or(DEFAULT_BIND).parse(), Ok)
130
5
}
131

            
132
1
fn resolve_host_key(cli_value: Option<PathBuf>) -> PathBuf {
133
1
    pick_host_key(cli_value, std::env::var_os("NOMISYNC_SSHD_HOST_KEY"))
134
1
}
135

            
136
4
fn pick_host_key(cli_value: Option<PathBuf>, env_value: Option<OsString>) -> PathBuf {
137
4
    cli_value
138
2
        .or_else(|| env_value.map(PathBuf::from))
139
1
        .unwrap_or_else(|| PathBuf::from(DEFAULT_HOST_KEY))
140
4
}
141

            
142
fn resolve_str_or_env(cli_value: Option<String>, env: &str, fallback: &str) -> String {
143
    cli_value
144
        .or_else(|| std::env::var(env).ok())
145
        .unwrap_or_else(|| fallback.to_string())
146
}
147

            
148
fn resolve_port_or_env(cli_value: Option<u16>, env: &str, bind: SocketAddr) -> u16 {
149
    cli_value
150
        .or_else(|| {
151
            std::env::var(env)
152
                .ok()
153
                .and_then(|raw| raw.parse::<u16>().ok())
154
        })
155
        .unwrap_or_else(|| bind.port())
156
}
157

            
158
#[tokio::main]
159
async fn main() -> anyhow::Result<()> {
160
    let cli = Cli::parse();
161
    server::telemetry::init_logging(cli.loglevel, LevelFilter::INFO)?;
162

            
163
    cli_core::start_server(cli.database, None).await?;
164

            
165
    let bind = resolve_bind(cli.bind)?;
166
    let host_key_path = resolve_host_key(cli.host_key);
167
    let host_key = hostkey::load_or_generate(host_key_path.as_path())?;
168

            
169
    let limiter = Arc::new(tokio::sync::Mutex::new(rate_limit::RateLimiter::new(
170
        rate_limit::Config {
171
            max_attempts_per_ip: cli.max_auth_attempts_per_ip,
172
            max_pubkey_attempts_per_ip: cli.max_pubkey_attempts_per_ip,
173
            window: Duration::from_mins(1),
174
            account_lockout_threshold: cli.lockout_threshold,
175
            account_lockout_duration: Duration::from_secs(cli.lockout_duration_secs),
176
        },
177
        rate_limit::InstantClock,
178
    )));
179

            
180
    let connect_info = handler::SshConnectInfo {
181
        hostname: resolve_str_or_env(
182
            cli.public_hostname,
183
            "NOMISYNC_SSHD_HOSTNAME",
184
            &bind.ip().to_string(),
185
        ),
186
        port: resolve_port_or_env(cli.public_port, "NOMISYNC_SSHD_PORT", bind),
187
        host_fingerprint: resolve_str_or_env(
188
            cli.host_fingerprint,
189
            "NOMISYNC_SSHD_HOST_FINGERPRINT",
190
            "(not configured)",
191
        ),
192
    };
193

            
194
    let mut state = handler::SshdState {
195
        limiter,
196
        connect_info,
197
    };
198

            
199
    let config = Arc::new(Config {
200
        inactivity_timeout: Some(Duration::from_mins(10)),
201
        auth_rejection_time: Duration::from_secs(2),
202
        keys: vec![host_key],
203
        ..Config::default()
204
    });
205

            
206
    let listener = TcpListener::bind(bind).await?;
207
    tracing::info!("nomisync-sshd listening on {bind}");
208
    if !bind.ip().is_loopback() {
209
        tracing::warn!(
210
            "bind {bind} is not loopback — this daemon has no TLS, no \
211
             brute-force protection beyond per-IP rate limiting; expose \
212
             deliberately."
213
        );
214
    }
215

            
216
    let metrics = metrics::start(cli.metrics_bind, || {
217
        server::telemetry::recorder::install_recorder().map_err(std::io::Error::other)
218
    })
219
    .await?;
220
    if metrics.is_some() {
221
        tokio::spawn(server::telemetry::pools::run_pool_sampler());
222
    }
223
    let limits = accept::AcceptLimits {
224
        max_startups: usize::from(cli.max_startups),
225
        pre_auth: Duration::from_secs(cli.pre_auth_timeout_secs),
226
    };
227
    accept::serve(&mut state, config, &listener, limits).await;
228
    Ok(())
229
}
230

            
231
#[cfg(test)]
232
mod accept_tests;
233
#[cfg(test)]
234
mod eval_limit_tests;
235
#[cfg(test)]
236
mod eval_subsystem_tests;
237
#[cfg(test)]
238
mod metrics_tests;
239
#[cfg(test)]
240
mod pty_backend_tests;
241
#[cfg(test)]
242
mod tests;
243
#[cfg(test)]
244
mod tui_channel_tests;
245
#[cfg(test)]
246
mod tui_chart_tests;
247
#[cfg(test)]
248
mod tui_input_tests;
249
#[cfg(test)]
250
mod tui_mouse_tests;
251
#[cfg(test)]
252
mod tui_panic_tests;
253
#[cfg(test)]
254
mod tui_resize_tests;
255
#[cfg(test)]
256
mod tui_session;
257
#[cfg(test)]
258
mod tui_transport_tests;
259
#[cfg(test)]
260
mod upload_cap_tests;