Lines
75.52 %
Functions
88.57 %
Branches
100 %
//! russh `Handler` + `Server` glue.
//!
//! Accepts `publickey` and `password` (rate-limited) auth, accepts
//! `pty-req` + `shell`, and refuses everything else the threat model
//! excludes (`exec`, `subsystem`, `direct-tcpip`, `x11-req`,
//! `auth-agent-req`).
//! The `shell_request` launch site runs the live TUI: it builds an
//! `SshTransport`, drives `tui::run_loop`, and attaches a per-session
//! DB-backed `ConsoleEval` so the Console tab evaluates nomiscript
//! against the authenticated user's `rpc::Session`.
use crate::auth::{Outcome, authenticate_password, authenticate_publickey};
use crate::eval_channel::{BACKLOG_REPLY, EvalChannelState, MAX_EVAL_CHANNELS, RusshSink};
use crate::metrics::SessionGauge;
use crate::rate_limit::{InstantClock, RateLimiter};
use crate::tui_channel::{Geometry, TuiChannelState};
use crate::tui_transport::SshTransport;
use rpc::ScriptCtx;
use russh::keys::HashAlg;
use russh::server::{Auth, ChannelOpenHandle, Handler, Server, Session, VerifiedPublicKey};
use russh::{Channel, ChannelId, ChannelOpenFailure, Pty};
use sqlx::types::Uuid;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc, watch};
use tui::transport::RawEvent;
/// Decoded key events a TUI channel keeps unread. One byte is at most one event
/// and an SSH packet at most 32 KiB, so a whole packet fits; a client that keeps
/// the queue full has outrun the loop and loses the channel.
pub const TUI_INPUT_EVENTS: usize = 32768;
/// Banner template used after a successful ssh-copy-id upload. The
/// daemon substitutes `{hostname}`, `{port}`, `{user}`, `{fingerprint}`
/// at runtime.
#[derive(Clone)]
pub struct SshConnectInfo {
pub hostname: String,
pub port: u16,
pub host_fingerprint: String,
}
/// Authentication method used by the active session. Phase C only
/// permits the `exec` channel that ssh-copy-id opens when the
/// caller authenticated via password.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMethod {
Password,
Publickey,
/// Shared state across every accepted session.
pub struct SshdState {
pub limiter: Arc<Mutex<RateLimiter<InstantClock>>>,
pub connect_info: SshConnectInfo,
impl Server for SshdState {
type Handler = Session_;
fn new_client(&mut self, peer_addr: Option<SocketAddr>) -> Self::Handler {
Session_ {
gauge: None,
authenticated: watch::channel(false).0,
peer: peer_addr,
limiter: Arc::clone(&self.limiter),
connect_info: self.connect_info.clone(),
user_id: None,
user_name: None,
auth_method: None,
pubkey_uploads: HashMap::new(),
tui_channels: HashMap::new(),
eval_channels: HashMap::new(),
pub(crate) fn log_session_error(error: &russh::Error) {
// The Kubernetes TCP probes connect and hang up every few seconds, and a
// client that walks away looks the same; logging those at warn buried
// real session failures under dozens of lines an hour.
if is_peer_hangup(error) {
tracing::debug!("session ended by peer: {error:?}");
} else {
tracing::warn!("session error: {error:?}");
/// Per-connection handler. Odd name because `Session` is taken by
/// russh.
pub struct Session_ {
/// Set on successful auth, so only authenticated sessions are counted.
gauge: Option<SessionGauge>,
/// Turns true on login; the accept loop's pre-auth deadline watches it.
authenticated: watch::Sender<bool>,
peer: Option<SocketAddr>,
limiter: Arc<Mutex<RateLimiter<InstantClock>>>,
connect_info: SshConnectInfo,
user_id: Option<Uuid>,
user_name: Option<String>,
auth_method: Option<AuthMethod>,
/// Buffers for `exec` channels that ssh-copy-id is feeding pubkey
/// lines through. Drained on `channel_eof`.
pubkey_uploads: HashMap<ChannelId, Vec<u8>>,
/// Per-channel TUI bridge state. Disjoint from `pubkey_uploads`:
/// a channel is either an ssh-copy-id upload or a TUI session,
/// never both.
tui_channels: HashMap<ChannelId, TuiChannelState>,
/// Per-channel state for the `nomisync-eval` subsystem. Disjoint
/// from `pubkey_uploads` and `tui_channels`: a channel commits
/// to one channel-type on its first request. Created in
/// `subsystem_request`, fed in `data`, input ended in `channel_eof` and
/// `channel_close`; it counts toward the per-connection cap, and stays here,
/// until its replies are sent. `subsystem_request` prunes it then.
eval_channels: HashMap<ChannelId, EvalChannelState>,
mod input;
mod refuse;
mod upload;
impl Session_ {
fn peer_ip(&self) -> std::net::IpAddr {
self.peer
.map_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), |s| {
s.ip()
})
/// Records the authenticated identity and starts counting the session.
pub(crate) fn accept(&mut self, user_id: Uuid, user: &str, method: AuthMethod) {
self.user_id = Some(user_id);
self.user_name = Some(user.to_string());
self.auth_method = Some(method);
self.gauge.get_or_insert_with(SessionGauge::open);
self.authenticated.send_replace(true);
pub(crate) fn authenticated(&self) -> watch::Receiver<bool> {
self.authenticated.subscribe()
impl Handler for Session_ {
type Error = russh::Error;
async fn auth_publickey(
&mut self,
user: &str,
key: VerifiedPublicKey<'_>,
) -> Result<Auth, Self::Error> {
let fingerprint = key.public_key.fingerprint(HashAlg::Sha256).to_string();
let outcome = authenticate_publickey(user, &fingerprint, self.peer_ip(), &self.limiter)
.await
.map_err(|_| russh::Error::Disconnect)?;
match outcome {
Outcome::Accept(uid) => {
self.accept(uid, user, AuthMethod::Publickey);
Ok(Auth::Accept)
Outcome::Reject => Ok(Auth::reject()),
async fn auth_password(&mut self, user: &str, password: &str) -> Result<Auth, Self::Error> {
let outcome = authenticate_password(user, password, self.peer_ip(), &self.limiter)
self.accept(uid, user, AuthMethod::Password);
async fn channel_open_session(
_channel: Channel<russh::server::Msg>,
reply: ChannelOpenHandle,
_session: &mut Session,
) -> Result<(), Self::Error> {
reply.accept().await;
Ok(())
async fn pty_request(
channel: ChannelId,
term: &str,
col_width: u32,
row_height: u32,
pix_width: u32,
pix_height: u32,
_modes: &[(Pty, u32)],
self.tui_channels.insert(
channel,
TuiChannelState::new(term, col_width, row_height, pix_width, pix_height),
);
async fn shell_request(
session: &mut Session,
let Some(uid) = self.user_id else {
tracing::warn!("shell_request without authenticated user; rejecting");
session.close(channel)?;
return Err(russh::Error::Disconnect);
};
if self
.refuse_if_withheld(uid, channel, session, "shell")
.await?
{
return Ok(());
let Some(state) = self.tui_channels.get_mut(&channel) else {
tracing::warn!("shell_request without prior pty-req on channel {channel:?}; rejecting");
let auto_depth = tvui::ColorDepth::detect(state.term.as_deref(), None);
let cli = tui::CliConfig::default();
let mut app = match tui::App::new(uid, cli, auto_depth) {
Ok(app) => app,
Err(err) => {
tracing::error!("tui theme unavailable: {err}");
tracing::info!(
"shell_request accepted user_id={uid} peer={:?} term={:?} cols={} rows={}",
self.peer,
state.term,
state.geometry().cols,
state.geometry().rows,
let (input_tx, input_rx) = mpsc::channel::<RawEvent>(TUI_INPUT_EVENTS);
state.input_tx = Some(input_tx);
let term = state.term.clone();
let geometry = state.subscribe();
let handle = session.handle();
let close_handle = session.handle();
let runtime = tokio::runtime::Handle::current();
let runtime_for_spawn = runtime.clone();
let runtime_for_close = runtime.clone();
let runtime_for_console = runtime.clone();
tokio::task::spawn_blocking(move || {
match SshTransport::new(handle, channel, runtime_for_spawn, input_rx, term, geometry) {
Ok(mut transport) => {
match tui::ConsoleEval::connect(
&runtime_for_console,
rpc::ScriptCtx::new(uid),
rpc::Session::guarded,
) {
Ok(eval) => app.attach_console(eval),
tracing::warn!("console eval unavailable for user_id={uid}: {err}");
app.set_status(format!("console unavailable: {err}"));
if let Err(err) = tui::run_loop(&mut transport, &mut app) {
tracing::info!("tui session ended: {err}");
tracing::error!("tui transport build failed: {err}");
if runtime_for_close
.block_on(close_handle.close(channel))
.is_err()
tracing::warn!("closing the channel after a transport failure failed");
});
async fn window_change_request(
if let Some(state) = self.tui_channels.get(&channel) {
let Geometry { cols, rows, .. } =
state.resize(col_width, row_height, pix_width, pix_height);
if let Some(tx) = &state.input_tx {
let _ = tx.try_send(RawEvent::Resize(cols, rows));
async fn exec_request(
_data: &[u8],
// The only `exec` we accept is the one ssh-copy-id opens to
// append to authorized_keys. Gate is "session authenticated
// via password AND user has zero keys on file" — which is
// exactly the bootstrap window. The requested command string
// is ignored: stdin is consumed verbatim as authorized_keys
// content, deferred to channel_eof.
if !self.is_bootstrap_upload_allowed().await {
self.refuse_request("exec");
"exec_request accepted as ssh-copy-id upload user_id={:?} peer={:?}",
self.user_id,
self.pubkey_uploads.entry(channel).or_default();
async fn data(
data: &[u8],
if self.feed_upload(channel, data, session)? || self.feed_tui(channel, data, session)? {
if let Some(state) = self.eval_channels.get_mut(&channel)
&& state.feed(data).is_err()
session.data(channel, BACKLOG_REPLY.as_bytes().to_vec())?;
state.close();
// Replies are delivered out-of-band by the channel's forwarder via
// the russh server Handle (see `RusshSink`); data() never waits.
async fn channel_eof(
if let Some(buf) = self.pubkey_uploads.remove(&channel) {
let banner = self.process_pubkey_upload(&buf).await;
session.data(channel, banner.into_bytes())?;
self.tui_channels.remove(&channel);
if let Some(state) = self.eval_channels.get_mut(&channel) {
state.end_input();
async fn channel_close(
self.pubkey_uploads.remove(&channel);
// The entry stays: the channel counts toward the cap until its replies are sent.
async fn subsystem_request(
name: &str,
if name != "nomisync-eval" {
self.refuse_request("subsystem");
let Some(user_id) = self.user_id else {
tracing::warn!("nomisync-eval requested before authentication; refusing");
// The eval subsystem runs scripts against the tenant's own database, so
// it is exactly as unsafe as a shell while that database is withheld.
.refuse_if_withheld(user_id, channel, session, "subsystem")
self.eval_channels.retain(|_, state| state.is_live());
if self.eval_channels.len() >= MAX_EVAL_CHANNELS {
tracing::warn!("nomisync-eval refused: {MAX_EVAL_CHANNELS} channels already open");
session.channel_failure(channel)?;
let sink = Box::new(RusshSink::new(session.handle(), channel));
match EvalChannelState::open(ScriptCtx::new(user_id), rpc::Session::guarded, sink) {
Ok(state) => {
self.eval_channels.insert(channel, state);
tracing::error!("nomisync-eval session init failed: {err}");
Err(russh::Error::Disconnect)
async fn channel_open_direct_tcpip(
_host_to_connect: &str,
_port_to_connect: u32,
_originator_address: &str,
_originator_port: u32,
self.refuse_request("direct-tcpip");
reply
.reject(ChannelOpenFailure::AdministrativelyProhibited)
.await;
async fn tcpip_forward(
_address: &str,
_port: &mut u32,
) -> Result<bool, Self::Error> {
self.refuse_request("tcpip-forward");
Ok(false)
/// Whether a session error only means the peer went away.
fn is_peer_hangup(error: &russh::Error) -> bool {
match error {
russh::Error::Disconnect | russh::Error::HUP => true,
russh::Error::IO(e) => matches!(
e.kind(),
std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::UnexpectedEof
| std::io::ErrorKind::BrokenPipe
),
_ => false,
#[cfg(test)]
mod tests;