1
//! russh `Handler` + `Server` glue.
2
//!
3
//! Accepts `publickey` and `password` (rate-limited) auth, accepts
4
//! `pty-req` + `shell`, and refuses everything else the threat model
5
//! excludes (`exec`, `subsystem`, `direct-tcpip`, `x11-req`,
6
//! `auth-agent-req`).
7
//!
8
//! The `shell_request` launch site runs the live TUI: it builds an
9
//! `SshTransport`, drives `tui::run_loop`, and attaches a per-session
10
//! DB-backed `ConsoleEval` so the Console tab evaluates nomiscript
11
//! against the authenticated user's `rpc::Session`.
12

            
13
use crate::auth::{Outcome, authenticate_password, authenticate_publickey};
14
use crate::eval_channel::{BACKLOG_REPLY, EvalChannelState, MAX_EVAL_CHANNELS, RusshSink};
15
use crate::metrics::SessionGauge;
16
use crate::rate_limit::{InstantClock, RateLimiter};
17
use crate::tui_channel::{Geometry, TuiChannelState};
18
use crate::tui_transport::SshTransport;
19
use rpc::ScriptCtx;
20
use russh::keys::HashAlg;
21
use russh::server::{Auth, ChannelOpenHandle, Handler, Server, Session, VerifiedPublicKey};
22
use russh::{Channel, ChannelId, ChannelOpenFailure, Pty};
23
use sqlx::types::Uuid;
24
use std::collections::HashMap;
25
use std::net::SocketAddr;
26
use std::sync::Arc;
27
use tokio::sync::{Mutex, mpsc, watch};
28
use tui::transport::RawEvent;
29

            
30
/// Decoded key events a TUI channel keeps unread. One byte is at most one event
31
/// and an SSH packet at most 32 KiB, so a whole packet fits; a client that keeps
32
/// the queue full has outrun the loop and loses the channel.
33
pub const TUI_INPUT_EVENTS: usize = 32768;
34

            
35
/// Banner template used after a successful ssh-copy-id upload. The
36
/// daemon substitutes `{hostname}`, `{port}`, `{user}`, `{fingerprint}`
37
/// at runtime.
38
#[derive(Clone)]
39
pub struct SshConnectInfo {
40
    pub hostname: String,
41
    pub port: u16,
42
    pub host_fingerprint: String,
43
}
44

            
45
/// Authentication method used by the active session. Phase C only
46
/// permits the `exec` channel that ssh-copy-id opens when the
47
/// caller authenticated via password.
48
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49
pub enum AuthMethod {
50
    Password,
51
    Publickey,
52
}
53

            
54
/// Shared state across every accepted session.
55
pub struct SshdState {
56
    pub limiter: Arc<Mutex<RateLimiter<InstantClock>>>,
57
    pub connect_info: SshConnectInfo,
58
}
59

            
60
impl Server for SshdState {
61
    type Handler = Session_;
62

            
63
34
    fn new_client(&mut self, peer_addr: Option<SocketAddr>) -> Self::Handler {
64
34
        Session_ {
65
34
            gauge: None,
66
34
            authenticated: watch::channel(false).0,
67
34
            peer: peer_addr,
68
34
            limiter: Arc::clone(&self.limiter),
69
34
            connect_info: self.connect_info.clone(),
70
34
            user_id: None,
71
34
            user_name: None,
72
34
            auth_method: None,
73
34
            pubkey_uploads: HashMap::new(),
74
34
            tui_channels: HashMap::new(),
75
34
            eval_channels: HashMap::new(),
76
34
        }
77
34
    }
78
}
79

            
80
15
pub(crate) fn log_session_error(error: &russh::Error) {
81
    // The Kubernetes TCP probes connect and hang up every few seconds, and a
82
    // client that walks away looks the same; logging those at warn buried
83
    // real session failures under dozens of lines an hour.
84
15
    if is_peer_hangup(error) {
85
15
        tracing::debug!("session ended by peer: {error:?}");
86
    } else {
87
        tracing::warn!("session error: {error:?}");
88
    }
89
15
}
90

            
91
/// Per-connection handler. Odd name because `Session` is taken by
92
/// russh.
93
pub struct Session_ {
94
    /// Set on successful auth, so only authenticated sessions are counted.
95
    gauge: Option<SessionGauge>,
96
    /// Turns true on login; the accept loop's pre-auth deadline watches it.
97
    authenticated: watch::Sender<bool>,
98
    peer: Option<SocketAddr>,
99
    limiter: Arc<Mutex<RateLimiter<InstantClock>>>,
100
    connect_info: SshConnectInfo,
101
    user_id: Option<Uuid>,
102
    user_name: Option<String>,
103
    auth_method: Option<AuthMethod>,
104
    /// Buffers for `exec` channels that ssh-copy-id is feeding pubkey
105
    /// lines through. Drained on `channel_eof`.
106
    pubkey_uploads: HashMap<ChannelId, Vec<u8>>,
107
    /// Per-channel TUI bridge state. Disjoint from `pubkey_uploads`:
108
    /// a channel is either an ssh-copy-id upload or a TUI session,
109
    /// never both.
110
    tui_channels: HashMap<ChannelId, TuiChannelState>,
111
    /// Per-channel state for the `nomisync-eval` subsystem. Disjoint
112
    /// from `pubkey_uploads` and `tui_channels`: a channel commits
113
    /// to one channel-type on its first request. Created in
114
    /// `subsystem_request`, fed in `data`, input ended in `channel_eof` and
115
    /// `channel_close`; it counts toward the per-connection cap, and stays here,
116
    /// until its replies are sent. `subsystem_request` prunes it then.
117
    eval_channels: HashMap<ChannelId, EvalChannelState>,
118
}
119

            
120
mod input;
121
mod refuse;
122
mod upload;
123

            
124
impl Session_ {
125
24
    fn peer_ip(&self) -> std::net::IpAddr {
126
24
        self.peer
127
24
            .map_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), |s| {
128
23
                s.ip()
129
23
            })
130
24
    }
131
}
132

            
133
impl Session_ {
134
    /// Records the authenticated identity and starts counting the session.
135
26
    pub(crate) fn accept(&mut self, user_id: Uuid, user: &str, method: AuthMethod) {
136
26
        self.user_id = Some(user_id);
137
26
        self.user_name = Some(user.to_string());
138
26
        self.auth_method = Some(method);
139
26
        self.gauge.get_or_insert_with(SessionGauge::open);
140
26
        self.authenticated.send_replace(true);
141
26
    }
142

            
143
30
    pub(crate) fn authenticated(&self) -> watch::Receiver<bool> {
144
30
        self.authenticated.subscribe()
145
30
    }
146
}
147

            
148
impl Handler for Session_ {
149
    type Error = russh::Error;
150

            
151
21
    async fn auth_publickey(
152
21
        &mut self,
153
21
        user: &str,
154
21
        key: VerifiedPublicKey<'_>,
155
21
    ) -> Result<Auth, Self::Error> {
156
21
        let fingerprint = key.public_key.fingerprint(HashAlg::Sha256).to_string();
157
21
        let outcome = authenticate_publickey(user, &fingerprint, self.peer_ip(), &self.limiter)
158
21
            .await
159
            .map_err(|_| russh::Error::Disconnect)?;
160
21
        match outcome {
161
            Outcome::Accept(uid) => {
162
21
                self.accept(uid, user, AuthMethod::Publickey);
163
21
                Ok(Auth::Accept)
164
            }
165
            Outcome::Reject => Ok(Auth::reject()),
166
        }
167
21
    }
168

            
169
3
    async fn auth_password(&mut self, user: &str, password: &str) -> Result<Auth, Self::Error> {
170
3
        let outcome = authenticate_password(user, password, self.peer_ip(), &self.limiter)
171
3
            .await
172
            .map_err(|_| russh::Error::Disconnect)?;
173
3
        match outcome {
174
            Outcome::Accept(uid) => {
175
2
                self.accept(uid, user, AuthMethod::Password);
176
2
                Ok(Auth::Accept)
177
            }
178
1
            Outcome::Reject => Ok(Auth::reject()),
179
        }
180
3
    }
181

            
182
40
    async fn channel_open_session(
183
40
        &mut self,
184
40
        _channel: Channel<russh::server::Msg>,
185
40
        reply: ChannelOpenHandle,
186
40
        _session: &mut Session,
187
40
    ) -> Result<(), Self::Error> {
188
40
        reply.accept().await;
189
40
        Ok(())
190
40
    }
191

            
192
12
    async fn pty_request(
193
12
        &mut self,
194
12
        channel: ChannelId,
195
12
        term: &str,
196
12
        col_width: u32,
197
12
        row_height: u32,
198
12
        pix_width: u32,
199
12
        pix_height: u32,
200
12
        _modes: &[(Pty, u32)],
201
12
        _session: &mut Session,
202
12
    ) -> Result<(), Self::Error> {
203
12
        self.tui_channels.insert(
204
12
            channel,
205
12
            TuiChannelState::new(term, col_width, row_height, pix_width, pix_height),
206
12
        );
207
12
        Ok(())
208
12
    }
209

            
210
12
    async fn shell_request(
211
12
        &mut self,
212
12
        channel: ChannelId,
213
12
        session: &mut Session,
214
12
    ) -> Result<(), Self::Error> {
215
12
        let Some(uid) = self.user_id else {
216
            tracing::warn!("shell_request without authenticated user; rejecting");
217
            session.close(channel)?;
218
            return Err(russh::Error::Disconnect);
219
        };
220
12
        if self
221
12
            .refuse_if_withheld(uid, channel, session, "shell")
222
12
            .await?
223
        {
224
            return Ok(());
225
12
        }
226
12
        let Some(state) = self.tui_channels.get_mut(&channel) else {
227
            tracing::warn!("shell_request without prior pty-req on channel {channel:?}; rejecting");
228
            session.close(channel)?;
229
            return Err(russh::Error::Disconnect);
230
        };
231

            
232
12
        let auto_depth = tvui::ColorDepth::detect(state.term.as_deref(), None);
233
12
        let cli = tui::CliConfig::default();
234
12
        let mut app = match tui::App::new(uid, cli, auto_depth) {
235
12
            Ok(app) => app,
236
            Err(err) => {
237
                tracing::error!("tui theme unavailable: {err}");
238
                session.close(channel)?;
239
                return Ok(());
240
            }
241
        };
242
12
        tracing::info!(
243
            "shell_request accepted user_id={uid} peer={:?} term={:?} cols={} rows={}",
244
            self.peer,
245
            state.term,
246
            state.geometry().cols,
247
            state.geometry().rows,
248
        );
249

            
250
12
        let (input_tx, input_rx) = mpsc::channel::<RawEvent>(TUI_INPUT_EVENTS);
251
12
        state.input_tx = Some(input_tx);
252
12
        let term = state.term.clone();
253
12
        let geometry = state.subscribe();
254

            
255
12
        let handle = session.handle();
256
12
        let close_handle = session.handle();
257
12
        let runtime = tokio::runtime::Handle::current();
258
12
        let runtime_for_spawn = runtime.clone();
259
12
        let runtime_for_close = runtime.clone();
260
12
        let runtime_for_console = runtime.clone();
261

            
262
12
        tokio::task::spawn_blocking(move || {
263
12
            match SshTransport::new(handle, channel, runtime_for_spawn, input_rx, term, geometry) {
264
                Ok(mut transport) => {
265
12
                    match tui::ConsoleEval::connect(
266
12
                        &runtime_for_console,
267
12
                        rpc::ScriptCtx::new(uid),
268
12
                        rpc::Session::guarded,
269
12
                    ) {
270
12
                        Ok(eval) => app.attach_console(eval),
271
                        Err(err) => {
272
                            tracing::warn!("console eval unavailable for user_id={uid}: {err}");
273
                            app.set_status(format!("console unavailable: {err}"));
274
                        }
275
                    }
276
12
                    if let Err(err) = tui::run_loop(&mut transport, &mut app) {
277
11
                        tracing::info!("tui session ended: {err}");
278
1
                    }
279
                }
280
                Err(err) => {
281
                    tracing::error!("tui transport build failed: {err}");
282
                    if runtime_for_close
283
                        .block_on(close_handle.close(channel))
284
                        .is_err()
285
                    {
286
                        tracing::warn!("closing the channel after a transport failure failed");
287
                    }
288
                }
289
            }
290
12
        });
291

            
292
12
        Ok(())
293
12
    }
294

            
295
2
    async fn window_change_request(
296
2
        &mut self,
297
2
        channel: ChannelId,
298
2
        col_width: u32,
299
2
        row_height: u32,
300
2
        pix_width: u32,
301
2
        pix_height: u32,
302
2
        _session: &mut Session,
303
2
    ) -> Result<(), Self::Error> {
304
2
        if let Some(state) = self.tui_channels.get(&channel) {
305
            let Geometry { cols, rows, .. } =
306
2
                state.resize(col_width, row_height, pix_width, pix_height);
307
2
            if let Some(tx) = &state.input_tx {
308
2
                let _ = tx.try_send(RawEvent::Resize(cols, rows));
309
            }
310
        }
311
2
        Ok(())
312
2
    }
313

            
314
2
    async fn exec_request(
315
2
        &mut self,
316
2
        channel: ChannelId,
317
2
        _data: &[u8],
318
2
        _session: &mut Session,
319
2
    ) -> Result<(), Self::Error> {
320
        // The only `exec` we accept is the one ssh-copy-id opens to
321
        // append to authorized_keys. Gate is "session authenticated
322
        // via password AND user has zero keys on file" — which is
323
        // exactly the bootstrap window. The requested command string
324
        // is ignored: stdin is consumed verbatim as authorized_keys
325
        // content, deferred to channel_eof.
326
2
        if !self.is_bootstrap_upload_allowed().await {
327
            self.refuse_request("exec");
328
            return Err(russh::Error::Disconnect);
329
2
        }
330
2
        tracing::info!(
331
            "exec_request accepted as ssh-copy-id upload user_id={:?} peer={:?}",
332
            self.user_id,
333
            self.peer
334
        );
335
2
        self.pubkey_uploads.entry(channel).or_default();
336
2
        Ok(())
337
2
    }
338

            
339
222
    async fn data(
340
222
        &mut self,
341
222
        channel: ChannelId,
342
222
        data: &[u8],
343
222
        session: &mut Session,
344
222
    ) -> Result<(), Self::Error> {
345
222
        if self.feed_upload(channel, data, session)? || self.feed_tui(channel, data, session)? {
346
45
            return Ok(());
347
177
        }
348
177
        if let Some(state) = self.eval_channels.get_mut(&channel)
349
177
            && state.feed(data).is_err()
350
        {
351
            session.data(channel, BACKLOG_REPLY.as_bytes().to_vec())?;
352
            session.close(channel)?;
353
            state.close();
354
177
        }
355
        // Replies are delivered out-of-band by the channel's forwarder via
356
        // the russh server Handle (see `RusshSink`); data() never waits.
357
177
        Ok(())
358
222
    }
359

            
360
8
    async fn channel_eof(
361
8
        &mut self,
362
8
        channel: ChannelId,
363
8
        session: &mut Session,
364
8
    ) -> Result<(), Self::Error> {
365
8
        if let Some(buf) = self.pubkey_uploads.remove(&channel) {
366
1
            let banner = self.process_pubkey_upload(&buf).await;
367
1
            session.data(channel, banner.into_bytes())?;
368
1
            session.close(channel)?;
369
        } else {
370
7
            self.tui_channels.remove(&channel);
371
7
            if let Some(state) = self.eval_channels.get_mut(&channel) {
372
7
                state.end_input();
373
            }
374
        }
375
8
        Ok(())
376
8
    }
377

            
378
1
    async fn channel_close(
379
1
        &mut self,
380
1
        channel: ChannelId,
381
1
        _session: &mut Session,
382
1
    ) -> Result<(), Self::Error> {
383
1
        self.pubkey_uploads.remove(&channel);
384
1
        self.tui_channels.remove(&channel);
385
        // The entry stays: the channel counts toward the cap until its replies are sent.
386
1
        if let Some(state) = self.eval_channels.get_mut(&channel) {
387
1
            state.close();
388
        }
389
1
        Ok(())
390
1
    }
391

            
392
25
    async fn subsystem_request(
393
25
        &mut self,
394
25
        channel: ChannelId,
395
25
        name: &str,
396
25
        session: &mut Session,
397
25
    ) -> Result<(), Self::Error> {
398
25
        if name != "nomisync-eval" {
399
            self.refuse_request("subsystem");
400
            return Err(russh::Error::Disconnect);
401
25
        }
402
25
        let Some(user_id) = self.user_id else {
403
            tracing::warn!("nomisync-eval requested before authentication; refusing");
404
            self.refuse_request("subsystem");
405
            return Err(russh::Error::Disconnect);
406
        };
407
        // The eval subsystem runs scripts against the tenant's own database, so
408
        // it is exactly as unsafe as a shell while that database is withheld.
409
25
        if self
410
25
            .refuse_if_withheld(user_id, channel, session, "subsystem")
411
25
            .await?
412
        {
413
            return Ok(());
414
25
        }
415

            
416
34
        self.eval_channels.retain(|_, state| state.is_live());
417
25
        if self.eval_channels.len() >= MAX_EVAL_CHANNELS {
418
14
            tracing::warn!("nomisync-eval refused: {MAX_EVAL_CHANNELS} channels already open");
419
14
            session.channel_failure(channel)?;
420
14
            session.close(channel)?;
421
14
            return Ok(());
422
11
        }
423

            
424
11
        let sink = Box::new(RusshSink::new(session.handle(), channel));
425
11
        match EvalChannelState::open(ScriptCtx::new(user_id), rpc::Session::guarded, sink) {
426
            Ok(state) => {
427
11
                self.eval_channels.insert(channel, state);
428
11
                Ok(())
429
            }
430
            Err(err) => {
431
                tracing::error!("nomisync-eval session init failed: {err}");
432
                Err(russh::Error::Disconnect)
433
            }
434
        }
435
25
    }
436

            
437
    async fn channel_open_direct_tcpip(
438
        &mut self,
439
        _channel: Channel<russh::server::Msg>,
440
        _host_to_connect: &str,
441
        _port_to_connect: u32,
442
        _originator_address: &str,
443
        _originator_port: u32,
444
        reply: ChannelOpenHandle,
445
        _session: &mut Session,
446
    ) -> Result<(), Self::Error> {
447
        self.refuse_request("direct-tcpip");
448
        reply
449
            .reject(ChannelOpenFailure::AdministrativelyProhibited)
450
            .await;
451
        Ok(())
452
    }
453

            
454
    async fn tcpip_forward(
455
        &mut self,
456
        _address: &str,
457
        _port: &mut u32,
458
        _session: &mut Session,
459
    ) -> Result<bool, Self::Error> {
460
        self.refuse_request("tcpip-forward");
461
        Ok(false)
462
    }
463
}
464

            
465
/// Whether a session error only means the peer went away.
466
22
fn is_peer_hangup(error: &russh::Error) -> bool {
467
22
    match error {
468
4
        russh::Error::Disconnect | russh::Error::HUP => true,
469
17
        russh::Error::IO(e) => matches!(
470
17
            e.kind(),
471
            std::io::ErrorKind::ConnectionReset
472
                | std::io::ErrorKind::UnexpectedEof
473
                | std::io::ErrorKind::BrokenPipe
474
        ),
475
1
        _ => false,
476
    }
477
22
}
478

            
479
#[cfg(test)]
480
mod tests;