Skip to main content

openmoat_proxy/
session.rs

1//! Per-session proxy credentials (ADR-027, ADR-044).
2//!
3//! In session mode every request carries a `Basic` proxy credential whose user
4//! name names the audit session and whose password only that session's
5//! processes were given. Clients send it when their proxy URL has userinfo
6//! (`http://<user>:<password>@127.0.0.1:<port>`). A request without a valid
7//! credential is refused (`proxy-session`) before its host is decided.
8//!
9//! Two kinds of credential are accepted:
10//!
11//! - [`Credential`]s the proxy holds: `moat run` makes one for its run.
12//! - Credentials a [`Verify`] accepts: the standalone `moat proxy` checks the
13//!   ones the agent's session-start hook issued, which it never saw (ADR-044).
14//!
15//! The session id then selects the session's taint ([`TaintLookup`]) and its
16//! share of the connections (`slots.rs`).
17
18use std::collections::HashMap;
19use std::fmt;
20use std::net::SocketAddr;
21use std::sync::{Mutex, PoisonError};
22use std::time::{Duration, Instant};
23
24use openmoat_core::Taint;
25use zeroize::Zeroizing;
26
27/// Shortest token a [`Credential`] accepts, in characters.
28pub const MIN_TOKEN_LEN: usize = 32;
29
30/// Longest session id a [`Credential`] accepts.
31const MAX_SESSION_LEN: usize = 128;
32
33/// One session's credential: its audit session id and its token.
34pub struct Credential {
35    session: String,
36    token: Zeroizing<Vec<u8>>,
37}
38
39impl fmt::Debug for Credential {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        // The token never appears in a log line or panic message.
42        f.debug_struct("Credential")
43            .field("session", &self.session)
44            .finish_non_exhaustive()
45    }
46}
47
48/// Why a [`Credential`] cannot be made.
49#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
50#[non_exhaustive]
51pub enum CredentialError {
52    /// The session id is empty, too long, or holds a character other than
53    /// ASCII letters, digits, `.`, `_` and `-`.
54    #[error("a session id is 1 to 128 ASCII letters, digits, `.`, `_` or `-`")]
55    Session,
56    /// The token is shorter than [`MIN_TOKEN_LEN`] or holds such a character.
57    #[error("a session token is at least 32 ASCII letters, digits, `.`, `_` or `-`")]
58    Token,
59}
60
61/// Characters that need no escaping in a URL's userinfo or a Basic credential.
62fn plain(bytes: &[u8]) -> bool {
63    bytes
64        .iter()
65        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
66}
67
68impl Credential {
69    /// The credential of `session`, which presents `token`.
70    pub fn new(session: &str, token: &[u8]) -> Result<Self, CredentialError> {
71        if session.is_empty() || session.len() > MAX_SESSION_LEN || !plain(session.as_bytes()) {
72            return Err(CredentialError::Session);
73        }
74        if token.len() < MIN_TOKEN_LEN || !plain(token) {
75            return Err(CredentialError::Token);
76        }
77        Ok(Self {
78            session: session.to_owned(),
79            token: Zeroizing::new(token.to_vec()),
80        })
81    }
82
83    /// The audit session id.
84    #[must_use]
85    pub fn session(&self) -> &str {
86        &self.session
87    }
88
89    /// `http://<session>:<token>@<addr>`: what the session's `HTTP_PROXY` and
90    /// `HTTPS_PROXY` hold. Zeroed when dropped.
91    #[must_use]
92    pub fn proxy_url(&self, addr: SocketAddr) -> Zeroizing<String> {
93        let token = String::from_utf8_lossy(&self.token);
94        Zeroizing::new(format!("http://{}:{token}@{addr}", self.session))
95    }
96}
97
98/// Checks credentials the proxy does not hold: those the standalone proxy's
99/// sessions were issued after it started (ADR-044). The CLI implements it.
100pub trait Verify: Send + Sync {
101    /// The audit session that `user` and `password` authenticate, or `None`.
102    /// The comparison must take time that does not depend on where a guess
103    /// first differs from a valid credential.
104    fn verify(&self, user: &[u8], password: &[u8]) -> Option<String>;
105}
106
107/// What a session was exposed to, read when one of its requests is decided.
108/// The CLI reads it from the audit log; tests pass a fixed map.
109pub trait TaintLookup: Send + Sync {
110    /// The taint of `session`. An error refuses the request: without the
111    /// session's history the proxy cannot tell whether it read a secret.
112    fn taint(&self, session: &str) -> Result<Taint, String>;
113
114    /// A mark that changes whenever a taint may have (the audit log's newest
115    /// event id), so a taint looked up before it changed is not used again.
116    /// `None` when there is none or it cannot be read (the audit log will not
117    /// open): the taint is then looked up again every time, since a new event
118    /// could not be seen.
119    fn version(&self) -> Option<i64> {
120        None
121    }
122}
123
124/// Why a request's credential is refused. The reply does not say whether the
125/// session id or the token was wrong.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
127#[non_exhaustive]
128pub enum AuthError {
129    /// No `Proxy-Authorization` header.
130    #[error("this proxy serves sessions only: the request carries no session credential")]
131    Missing,
132    /// More than one header, a scheme other than `Basic`, or bad base64.
133    #[error("the session credential is malformed")]
134    Malformed,
135    /// No session has this id and token.
136    #[error("the session credential is not valid")]
137    Invalid,
138}
139
140/// A taint as looked up: when, at which [`TaintLookup::version`], and what.
141type Looked = (Instant, Option<i64>, Taint);
142
143/// How many sessions' recent taint is kept before idle ones are forgotten.
144const MAX_RECENT: usize = 1024;
145
146/// A recent taint not used for this long is forgotten once [`MAX_RECENT`] is reached.
147const RECENT_IDLE: Duration = Duration::from_mins(10);
148
149/// Session mode: the credentials the proxy accepts and where their taint is read.
150pub struct Sessions<'a> {
151    credentials: Vec<Credential>,
152    issued: Option<&'a dyn Verify>,
153    /// Serve a request that carries no credential at all, with no session
154    /// (`sandbox.proxy_serve_without_credential`, ADR-044). A wrong or
155    /// malformed credential is refused either way.
156    without_credential: bool,
157    taint: &'a dyn TaintLookup,
158    /// The last taint looked up per session, when, and at which
159    /// [`TaintLookup::version`]: what the open connections are checked against
160    /// again ([`Sessions::taint_within`]).
161    recent: Mutex<HashMap<String, Looked>>,
162}
163
164impl fmt::Debug for Sessions<'_> {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("Sessions")
167            .field("credentials", &self.credentials)
168            .field("issued", &self.issued.is_some())
169            .field("without_credential", &self.without_credential)
170            .finish_non_exhaustive()
171    }
172}
173
174impl<'a> Sessions<'a> {
175    /// Accept `credentials`; look each session's taint up in `taint`.
176    #[must_use]
177    pub fn new(credentials: Vec<Credential>, taint: &'a dyn TaintLookup) -> Self {
178        Self {
179            credentials,
180            issued: None,
181            without_credential: false,
182            taint,
183            recent: Mutex::new(HashMap::new()),
184        }
185    }
186
187    /// Accept the credentials `issued` verifies; look each session's taint up
188    /// in `taint` (the standalone proxy, ADR-044).
189    #[must_use]
190    pub fn issued(issued: &'a dyn Verify, taint: &'a dyn TaintLookup) -> Self {
191        Self {
192            issued: Some(issued),
193            ..Self::new(Vec::new(), taint)
194        }
195    }
196
197    /// Also serve requests that carry no credential, with no session: no
198    /// taint applies to them, and they share one holder's half of the
199    /// connections. A wrong or malformed credential is still refused.
200    #[must_use]
201    pub fn serving_without_credential(mut self) -> Self {
202        self.without_credential = true;
203        self
204    }
205
206    /// Whether a request without any credential is served.
207    #[must_use]
208    pub fn serves_without_credential(&self) -> bool {
209        self.without_credential
210    }
211
212    /// The session that `headers` (every `Proxy-Authorization` value of the
213    /// request) authenticate. Every credential is compared in full, in time
214    /// that does not depend on where a guess first differs.
215    pub fn verify<T: AsRef<[u8]>>(&self, headers: &[T]) -> Result<String, AuthError> {
216        let value = match headers {
217            [] => return Err(AuthError::Missing),
218            [one] => one.as_ref(),
219            _ => return Err(AuthError::Malformed),
220        };
221        let decoded = basic(value).ok_or(AuthError::Malformed)?;
222        let colon = decoded
223            .iter()
224            .position(|b| *b == b':')
225            .ok_or(AuthError::Malformed)?;
226        let (session, token) = (&decoded[..colon], &decoded[colon + 1..]);
227        let mut found = None;
228        for credential in &self.credentials {
229            let id = constant_time_eq(credential.session.as_bytes(), session);
230            let secret = constant_time_eq(&credential.token, token);
231            if id & secret {
232                found = Some(credential.session.clone());
233            }
234        }
235        if found.is_none()
236            && let Some(issued) = self.issued
237        {
238            found = issued.verify(session, token);
239        }
240        found.ok_or(AuthError::Invalid)
241    }
242
243    /// The taint of `session`, from the lookup.
244    pub fn taint(&self, session: &str) -> Result<Taint, String> {
245        // the mark before the lookup: an event recorded during it changes it
246        let version = self.taint.version();
247        let taint = self.taint.taint(session)?;
248        let mut recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
249        // A standalone proxy serves session after session for days: forget
250        // the ones not looked up for a while, which only costs a lookup.
251        if recent.len() >= MAX_RECENT {
252            recent.retain(|_, (at, _, _)| at.elapsed() < RECENT_IDLE);
253        }
254        recent.insert(session.to_owned(), (Instant::now(), version, taint.clone()));
255        Ok(taint)
256    }
257
258    /// The taint of `session` as looked up at most `max_age` ago and with no
259    /// event recorded since ([`TaintLookup::version`]), else looked up again;
260    /// always looked up again while there is no version to compare.
261    /// Each open connection of a session is checked against its taint every so
262    /// often; this keeps that to one lookup per new event, at most one per
263    /// `max_age`, for the whole session. A new connection uses [`Self::taint`].
264    pub fn taint_within(&self, session: &str, max_age: Duration) -> Result<Taint, String> {
265        let version = self.taint.version();
266        {
267            let recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
268            if let Some((at, seen, taint)) = recent.get(session)
269                && at.elapsed() < max_age
270                && version.is_some()
271                && *seen == version
272            {
273                return Ok(taint.clone());
274            }
275        }
276        self.taint(session)
277    }
278}
279
280/// The decoded `user:password` of a `Basic` credential (RFC 7617); the scheme
281/// is matched without regard to case.
282fn basic(value: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
283    let value = value.trim_ascii();
284    let space = value.iter().position(u8::is_ascii_whitespace)?;
285    let (scheme, rest) = value.split_at(space);
286    if !scheme.eq_ignore_ascii_case(b"basic") {
287        return None;
288    }
289    base64(rest.trim_ascii())
290}
291
292/// Whether `a` and `b` are equal, in time that depends only on their lengths.
293#[must_use]
294pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
295    if a.len() != b.len() {
296        return false;
297    }
298    let diff = a
299        .iter()
300        .zip(b)
301        .fold(0u8, |acc, (x, y)| acc | std::hint::black_box(x ^ y));
302    std::hint::black_box(diff) == 0
303}
304
305/// Standard base64 (RFC 4648 ยง4), padding optional; `None` on any other byte.
306/// The bytes are wiped when dropped: what it decodes is usually a credential.
307#[must_use]
308pub fn base64(input: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
309    let data = input
310        .strip_suffix(b"==")
311        .or_else(|| input.strip_suffix(b"="))
312        .unwrap_or(input);
313    let padded = data.len() != input.len();
314    if data.is_empty() || data.len() % 4 == 1 || (padded && !input.len().is_multiple_of(4)) {
315        return None;
316    }
317    let mut out = Zeroizing::new(Vec::with_capacity(data.len() / 4 * 3 + 2));
318    let mut acc: u32 = 0;
319    let mut bits = 0u32;
320    for &c in data {
321        let v = match c {
322            b'A'..=b'Z' => c - b'A',
323            b'a'..=b'z' => c - b'a' + 26,
324            b'0'..=b'9' => c - b'0' + 52,
325            b'+' => 62,
326            b'/' => 63,
327            _ => return None,
328        };
329        acc = (acc << 6) | u32::from(v);
330        bits += 6;
331        if bits >= 8 {
332            bits -= 8;
333            out.push(u8::try_from((acc >> bits) & 0xff).ok()?);
334            acc &= (1 << bits) - 1;
335        }
336    }
337    Some(out)
338}
339
340#[cfg(test)]
341pub(crate) mod tests;