1
//! Authentication handler for the SSH daemon.
2
//!
3
//! Implements the two paths the threat model permits:
4
//!
5
//! - **Publickey** (preferred). Fingerprint the offered key, look
6
//!   it up via `LookupUserBySshKey`; the server command already
7
//!   gates on `ssh_enabled = TRUE`.
8
//! - **Password** (opt-in, rate-limited). Consult the per-IP and
9
//!   per-account limiters, call `verify_user_password`, and require
10
//!   the resolved user has `ssh_enabled = TRUE`.
11
//!
12
//! Every accept / reject decision logs `peer_ip`, `user`, `method`,
13
//! `outcome` at `info` so operators can audit attempts.
14

            
15
use crate::rate_limit::{Clock, Decision, RateLimiter};
16
use server::command::CmdResult;
17
use server::command::ssh_key::{LookupUserBySshKey, UserHasSshKey};
18
use server::command::user::{VerifiedUser, verify_user_password};
19
use sqlx::types::Uuid;
20
use std::net::IpAddr;
21
use std::sync::Arc;
22
use tokio::sync::Mutex;
23

            
24
/// Outcome the SSH server loop acts on — map this to
25
/// `russh::server::Auth::{Accept, reject()}` at the call site.
26
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27
pub enum Outcome {
28
    Accept(Uuid),
29
    Reject,
30
}
31

            
32
/// Public-key authentication. Always respects the `ssh_enabled`
33
/// gate (that's enforced server-side by `LookupUserBySshKey`).
34
/// Consults the per-IP pubkey bucket of the rate limiter so a
35
/// single peer cannot enumerate fingerprints unbounded; the bucket
36
/// is sized for normal clients that offer several identities per
37
/// connection (see [`crate::rate_limit::Config`]).
38
///
39
/// # Errors
40
///
41
/// Returns `Err` on infrastructure failure (DB down).
42
22
pub async fn authenticate_publickey<C: Clock>(
43
22
    user: &str,
44
22
    fingerprint: &str,
45
22
    peer: IpAddr,
46
22
    limiter: &Arc<Mutex<RateLimiter<C>>>,
47
22
) -> Result<Outcome, server::command::CmdError> {
48
    {
49
22
        let mut rl = limiter.lock().await;
50
22
        if rl.check_pubkey_ip(peer) == Decision::Deny {
51
1
            tracing::info!(
52
                "auth reject method=publickey user={user} peer={peer} reason=rate-limit"
53
            );
54
1
            return Ok(Outcome::Reject);
55
21
        }
56
    }
57
    // Logged here because the handler reports this failure as a plain
58
    // `Disconnect`, which is indistinguishable from a probe hanging up and is
59
    // logged at debug: without this line a directory outage that fails every
60
    // key login leaves no trace. The password path logs the same way.
61
21
    let result = LookupUserBySshKey::new()
62
21
        .fingerprint(fingerprint.to_string())
63
21
        .run()
64
21
        .await
65
        .inspect_err(|e| log_auth_error("publickey", user, peer, e))?;
66
21
    if let Some(CmdResult::Uuid(uid)) = result {
67
21
        tracing::info!("auth accept method=publickey user={user} peer={peer} user_id={uid}");
68
21
        Ok(Outcome::Accept(uid))
69
    } else {
70
        tracing::info!("auth reject method=publickey user={user} peer={peer}");
71
        Ok(Outcome::Reject)
72
    }
73
22
}
74

            
75
/// Password authentication. Consults both limiters; records a
76
/// failure on wrong-password; resets counters on success.
77
///
78
/// # Errors
79
///
80
/// Returns `Err` on infrastructure failure (DB down). Denied-by-
81
/// rate-limit, wrong password, and `ssh_enabled=false` all resolve
82
/// to `Ok(Outcome::Reject)` so timing / error shape don't leak
83
/// which one triggered.
84
4
pub async fn authenticate_password<C: Clock>(
85
4
    user: &str,
86
4
    password: &str,
87
4
    peer: IpAddr,
88
4
    limiter: &Arc<Mutex<RateLimiter<C>>>,
89
4
) -> Result<Outcome, server::command::CmdError> {
90
    {
91
4
        let mut rl = limiter.lock().await;
92
4
        if rl.check_ip(peer) == Decision::Deny || rl.check_account(user) == Decision::Deny {
93
2
            tracing::info!("auth reject method=password user={user} peer={peer} reason=rate-limit");
94
2
            return Ok(Outcome::Reject);
95
2
        }
96
    }
97

            
98
2
    match verify_user_password(user, password).await {
99
        Ok(Some(VerifiedUser {
100
            user_id,
101
            ssh_enabled: true,
102
            ..
103
        })) => {
104
            // Bootstrap-only: once any key is on file, password auth
105
            // is permanently rejected for this user. Treat the
106
            // attempt as a failure for limiter accounting so a
107
            // determined attacker can't probe the gate cheaply.
108
            if let Ok(Some(CmdResult::Bool(true))) =
109
2
                UserHasSshKey::new().user_id(user_id).run().await
110
            {
111
                let mut rl = limiter.lock().await;
112
                rl.record_password_failure(user);
113
                tracing::info!(
114
                    "auth reject method=password user={user} peer={peer} reason=key_already_registered"
115
                );
116
                return Ok(Outcome::Reject);
117
2
            }
118
2
            let mut rl = limiter.lock().await;
119
2
            rl.reset_account(user);
120
2
            tracing::info!("auth accept method=password user={user} peer={peer} user_id={user_id}");
121
2
            Ok(Outcome::Accept(user_id))
122
        }
123
        Ok(Some(_) | None) => {
124
            let mut rl = limiter.lock().await;
125
            rl.record_password_failure(user);
126
            tracing::info!("auth reject method=password user={user} peer={peer}");
127
            Ok(Outcome::Reject)
128
        }
129
        Err(e) => {
130
            log_auth_error("password", user, peer, &e);
131
            Err(server::command::CmdError::Args(e.to_string()))
132
        }
133
    }
134
4
}
135

            
136
/// An unreachable database is already logged where the connection was refused.
137
2
fn log_auth_error(method: &str, user: &str, peer: IpAddr, err: &server::command::CmdError) {
138
2
    if !err.is_unavailable() {
139
1
        tracing::error!("auth error method={method} user={user} peer={peer} err={err:?}");
140
1
    }
141
2
}
142

            
143
#[cfg(test)]
144
mod tests {
145
    //! Auth handler tests focus on the rate-limit + outcome-shaping
146
    //! logic. DB-backed flows are covered by the `server::command::
147
    //! user` and `server::command::ssh_key` test suites. These tests
148
    //! don't hit `verify_user_password` / `LookupUserBySshKey`
149
    //! directly — they exercise [`authenticate_password`]'s limiter
150
    //! path via a rigged limiter that always refuses.
151
    use super::*;
152
    use crate::rate_limit::{Config, InstantClock};
153
    use std::net::Ipv4Addr;
154
    use std::time::Duration;
155

            
156
4
    fn loopback() -> IpAddr {
157
4
        IpAddr::V4(Ipv4Addr::LOCALHOST)
158
4
    }
159

            
160
2
    fn limiter_denying_every_ip() -> Arc<Mutex<RateLimiter<InstantClock>>> {
161
        // Zero IP attempts allowed, so the first check always denies.
162
2
        let cfg = Config {
163
2
            max_attempts_per_ip: 0,
164
2
            max_pubkey_attempts_per_ip: 0,
165
2
            window: Duration::from_mins(1),
166
2
            account_lockout_threshold: 100,
167
2
            account_lockout_duration: Duration::from_mins(1),
168
2
        };
169
2
        Arc::new(Mutex::new(RateLimiter::new(cfg, InstantClock)))
170
2
    }
171

            
172
    #[tokio::test]
173
1
    async fn password_rejected_by_rate_limit_without_hitting_verify() {
174
        // If this test reached `verify_user_password`, we'd need a DB
175
        // and would hang / fail. Rate-limit short-circuits it, so the
176
        // call resolves without I/O.
177
1
        let lim = limiter_denying_every_ip();
178
1
        let outcome = authenticate_password("anyone", "any-pw", loopback(), &lim)
179
1
            .await
180
            .unwrap();
181
1
        assert_eq!(outcome, Outcome::Reject);
182
1
    }
183

            
184
    #[tokio::test]
185
1
    async fn publickey_rejected_by_rate_limit_without_hitting_db() {
186
        // Same shape as the password test: a saturated pubkey
187
        // limiter must short-circuit before LookupUserBySshKey would
188
        // need a connection.
189
1
        let lim = limiter_denying_every_ip();
190
1
        let outcome = authenticate_publickey("anyone", "SHA256:never-considered", loopback(), &lim)
191
1
            .await
192
            .unwrap();
193
1
        assert_eq!(outcome, Outcome::Reject);
194
1
    }
195

            
196
    #[test]
197
1
    fn only_a_fault_the_connection_did_not_log_is_logged_here() {
198
1
        let captured = server::log_capture::Captured::default();
199
1
        let _logs = tracing::subscriber::set_default(captured.subscriber());
200
1
        let unavailable = server::command::CmdError::from(server::db::DBError::TenantDisabled);
201
1
        let fault = server::command::CmdError::from(server::db::DBError::MissingUrl);
202

            
203
1
        log_auth_error("password", "u", loopback(), &unavailable);
204
1
        assert_eq!(captured.error_lines(), 0);
205

            
206
1
        log_auth_error("password", "u", loopback(), &fault);
207
1
        assert_eq!(captured.error_lines(), 1);
208
1
    }
209
}