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    /// Whether the session of `user`, a credential [`Self::verify`] just
107    /// accepted, received the trust files of the proxy's certificate
108    /// authority (ADR-062), so its tunnels to `requests:` hosts may be
109    /// terminated. `false` unless the implementation says so.
110    fn trusted(&self, user: &[u8]) -> bool {
111        let _ = user;
112        false
113    }
114}
115
116/// A request's session, as its credential authenticated it.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct Admitted {
119    /// The audit session id.
120    pub session: String,
121    /// Which tunnels of the session may be terminated.
122    pub trust: Trust,
123}
124
125/// Which of a session's tunnels the proxy may terminate: those whose
126/// clients trust its certificate authority.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum Trust {
130    /// None: the session's commands were not given the CA.
131    None,
132    /// Those to `requests:` hosts (ADR-062): an issued credential whose
133    /// session received the trust files ([`Verify::trusted`]).
134    Requests,
135    /// Every one the proxy terminates: a credential the proxy holds, whose
136    /// commands `openmoat run` gives the trust files (ADR-043).
137    All,
138}
139
140/// What a session was exposed to, read when one of its requests is decided.
141/// The CLI reads it from the audit log; tests pass a fixed map.
142pub trait TaintLookup: Send + Sync {
143    /// The taint of `session`. An error refuses the request: without the
144    /// session's history the proxy cannot tell whether it read a secret.
145    fn taint(&self, session: &str) -> Result<Taint, String>;
146
147    /// A mark that changes whenever a taint may have (the audit log's newest
148    /// event id), so a taint looked up before it changed is not used again.
149    /// `None` when there is none or it cannot be read (the audit log will not
150    /// open): the taint is then looked up again every time, since a new event
151    /// could not be seen.
152    fn version(&self) -> Option<i64> {
153        None
154    }
155}
156
157/// Why a request's credential is refused. The reply does not say whether the
158/// session id or the token was wrong.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
160#[non_exhaustive]
161pub enum AuthError {
162    /// No `Proxy-Authorization` header.
163    #[error("this proxy serves sessions only: the request carries no session credential")]
164    Missing,
165    /// More than one header, a scheme other than `Basic`, or bad base64.
166    #[error("the session credential is malformed")]
167    Malformed,
168    /// No session has this id and token.
169    #[error("the session credential is not valid")]
170    Invalid,
171}
172
173/// A taint as looked up: when, at which [`TaintLookup::version`], and what.
174type Looked = (Instant, Option<i64>, Taint);
175
176/// How many sessions' recent taint is kept before idle ones are forgotten.
177const MAX_RECENT: usize = 1024;
178
179/// A recent taint not used for this long is forgotten once [`MAX_RECENT`] is reached.
180const RECENT_IDLE: Duration = Duration::from_mins(10);
181
182/// Session mode: the credentials the proxy accepts and where their taint is read.
183pub struct Sessions<'a> {
184    credentials: Vec<Credential>,
185    issued: Option<&'a dyn Verify>,
186    /// Serve a request that carries no credential at all, with no session
187    /// (`sandbox.proxy_serve_without_credential`, ADR-044). A wrong or
188    /// malformed credential is refused either way.
189    without_credential: bool,
190    taint: &'a dyn TaintLookup,
191    /// The last taint looked up per session, when, and at which
192    /// [`TaintLookup::version`]: what the open connections are checked against
193    /// again ([`Sessions::taint_within`]).
194    recent: Mutex<HashMap<String, Looked>>,
195}
196
197impl fmt::Debug for Sessions<'_> {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.debug_struct("Sessions")
200            .field("credentials", &self.credentials)
201            .field("issued", &self.issued.is_some())
202            .field("without_credential", &self.without_credential)
203            .finish_non_exhaustive()
204    }
205}
206
207impl<'a> Sessions<'a> {
208    /// Accept `credentials`; look each session's taint up in `taint`.
209    #[must_use]
210    pub fn new(credentials: Vec<Credential>, taint: &'a dyn TaintLookup) -> Self {
211        Self {
212            credentials,
213            issued: None,
214            without_credential: false,
215            taint,
216            recent: Mutex::new(HashMap::new()),
217        }
218    }
219
220    /// Accept the credentials `issued` verifies; look each session's taint up
221    /// in `taint` (the standalone proxy, ADR-044).
222    #[must_use]
223    pub fn issued(issued: &'a dyn Verify, taint: &'a dyn TaintLookup) -> Self {
224        Self {
225            issued: Some(issued),
226            ..Self::new(Vec::new(), taint)
227        }
228    }
229
230    /// Also serve requests that carry no credential, with no session: no
231    /// taint applies to them, and they share one holder's half of the
232    /// connections. A wrong or malformed credential is still refused.
233    #[must_use]
234    pub fn serving_without_credential(mut self) -> Self {
235        self.without_credential = true;
236        self
237    }
238
239    /// Whether a request without any credential is served.
240    #[must_use]
241    pub fn serves_without_credential(&self) -> bool {
242        self.without_credential
243    }
244
245    /// The session that `headers` (every `Proxy-Authorization` value of the
246    /// request) authenticate. Every credential is compared in full, in time
247    /// that does not depend on where a guess first differs.
248    pub fn verify<T: AsRef<[u8]>>(&self, headers: &[T]) -> Result<String, AuthError> {
249        self.admit(headers).map(|admitted| admitted.session)
250    }
251
252    /// [`Self::verify`], with whether the session trusts the proxy's CA.
253    pub fn admit<T: AsRef<[u8]>>(&self, headers: &[T]) -> Result<Admitted, AuthError> {
254        let value = match headers {
255            [] => return Err(AuthError::Missing),
256            [one] => one.as_ref(),
257            _ => return Err(AuthError::Malformed),
258        };
259        let decoded = basic(value).ok_or(AuthError::Malformed)?;
260        let colon = decoded
261            .iter()
262            .position(|b| *b == b':')
263            .ok_or(AuthError::Malformed)?;
264        let (session, token) = (&decoded[..colon], &decoded[colon + 1..]);
265        let mut found = None;
266        for credential in &self.credentials {
267            let id = constant_time_eq(credential.session.as_bytes(), session);
268            let secret = constant_time_eq(&credential.token, token);
269            if id & secret {
270                found = Some(Admitted {
271                    session: credential.session.clone(),
272                    trust: Trust::All,
273                });
274            }
275        }
276        if found.is_none()
277            && let Some(issued) = self.issued
278        {
279            found = issued.verify(session, token).map(|id| Admitted {
280                session: id,
281                trust: if issued.trusted(session) {
282                    Trust::Requests
283                } else {
284                    Trust::None
285                },
286            });
287        }
288        found.ok_or(AuthError::Invalid)
289    }
290
291    /// The taint of `session`, from the lookup.
292    pub fn taint(&self, session: &str) -> Result<Taint, String> {
293        // the mark before the lookup: an event recorded during it changes it
294        let version = self.taint.version();
295        let taint = self.taint.taint(session)?;
296        let mut recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
297        // A standalone proxy serves session after session for days: forget
298        // the ones not looked up for a while, which only costs a lookup.
299        if recent.len() >= MAX_RECENT {
300            recent.retain(|_, (at, _, _)| at.elapsed() < RECENT_IDLE);
301        }
302        recent.insert(session.to_owned(), (Instant::now(), version, taint.clone()));
303        Ok(taint)
304    }
305
306    /// The taint of `session` as looked up at most `max_age` ago and with no
307    /// event recorded since ([`TaintLookup::version`]), else looked up again;
308    /// always looked up again while there is no version to compare.
309    /// Each open connection of a session is checked against its taint every so
310    /// often; this keeps that to one lookup per new event, at most one per
311    /// `max_age`, for the whole session. A new connection uses [`Self::taint`].
312    pub fn taint_within(&self, session: &str, max_age: Duration) -> Result<Taint, String> {
313        let version = self.taint.version();
314        {
315            let recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
316            if let Some((at, seen, taint)) = recent.get(session)
317                && at.elapsed() < max_age
318                && version.is_some()
319                && *seen == version
320            {
321                return Ok(taint.clone());
322            }
323        }
324        self.taint(session)
325    }
326}
327
328/// The decoded `user:password` of a `Basic` credential (RFC 7617); the scheme
329/// is matched without regard to case.
330fn basic(value: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
331    let value = value.trim_ascii();
332    let space = value.iter().position(u8::is_ascii_whitespace)?;
333    let (scheme, rest) = value.split_at(space);
334    if !scheme.eq_ignore_ascii_case(b"basic") {
335        return None;
336    }
337    base64(rest.trim_ascii())
338}
339
340/// Whether `a` and `b` are equal, in time that depends only on their lengths.
341#[must_use]
342pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
343    if a.len() != b.len() {
344        return false;
345    }
346    let diff = a
347        .iter()
348        .zip(b)
349        .fold(0u8, |acc, (x, y)| acc | std::hint::black_box(x ^ y));
350    std::hint::black_box(diff) == 0
351}
352
353/// Standard base64 (RFC 4648 ยง4), padding optional; `None` on any other byte.
354/// The bytes are wiped when dropped: what it decodes is usually a credential.
355#[must_use]
356pub fn base64(input: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
357    let data = input
358        .strip_suffix(b"==")
359        .or_else(|| input.strip_suffix(b"="))
360        .unwrap_or(input);
361    let padded = data.len() != input.len();
362    if data.is_empty() || data.len() % 4 == 1 || (padded && !input.len().is_multiple_of(4)) {
363        return None;
364    }
365    let mut out = Zeroizing::new(Vec::with_capacity(data.len() / 4 * 3 + 2));
366    let mut acc: u32 = 0;
367    let mut bits = 0u32;
368    for &c in data {
369        let v = match c {
370            b'A'..=b'Z' => c - b'A',
371            b'a'..=b'z' => c - b'a' + 26,
372            b'0'..=b'9' => c - b'0' + 52,
373            b'+' => 62,
374            b'/' => 63,
375            _ => return None,
376        };
377        acc = (acc << 6) | u32::from(v);
378        bits += 6;
379        if bits >= 8 {
380            bits -= 8;
381            out.push(u8::try_from((acc >> bits) & 0xff).ok()?);
382            acc &= (1 << bits) - 1;
383        }
384    }
385    Some(out)
386}
387
388#[cfg(test)]
389pub(crate) mod tests;