openmoat_proxy/
session.rs1use std::collections::HashMap;
13use std::fmt;
14use std::net::SocketAddr;
15use std::sync::{Mutex, PoisonError};
16use std::time::{Duration, Instant};
17
18use openmoat_core::Taint;
19use zeroize::Zeroizing;
20
21pub const RULE_SESSION: &str = "proxy-session";
24
25pub const MIN_TOKEN_LEN: usize = 32;
27
28const MAX_SESSION_LEN: usize = 128;
30
31pub struct Credential {
33 session: String,
34 token: Zeroizing<Vec<u8>>,
35}
36
37impl fmt::Debug for Credential {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.debug_struct("Credential")
41 .field("session", &self.session)
42 .finish_non_exhaustive()
43 }
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
48#[non_exhaustive]
49pub enum CredentialError {
50 #[error("a session id is 1 to 128 ASCII letters, digits, `.`, `_` or `-`")]
53 Session,
54 #[error("a session token is at least 32 ASCII letters, digits, `.`, `_` or `-`")]
56 Token,
57}
58
59fn plain(bytes: &[u8]) -> bool {
61 bytes
62 .iter()
63 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
64}
65
66impl Credential {
67 pub fn new(session: &str, token: &[u8]) -> Result<Self, CredentialError> {
69 if session.is_empty() || session.len() > MAX_SESSION_LEN || !plain(session.as_bytes()) {
70 return Err(CredentialError::Session);
71 }
72 if token.len() < MIN_TOKEN_LEN || !plain(token) {
73 return Err(CredentialError::Token);
74 }
75 Ok(Self {
76 session: session.to_owned(),
77 token: Zeroizing::new(token.to_vec()),
78 })
79 }
80
81 #[must_use]
83 pub fn session(&self) -> &str {
84 &self.session
85 }
86
87 #[must_use]
90 pub fn proxy_url(&self, addr: SocketAddr) -> Zeroizing<String> {
91 let token = String::from_utf8_lossy(&self.token);
92 Zeroizing::new(format!("http://{}:{token}@{addr}", self.session))
93 }
94}
95
96pub trait TaintLookup: Send + Sync {
99 fn taint(&self, session: &str) -> Result<Taint, String>;
102
103 fn version(&self) -> Option<i64> {
107 None
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
114#[non_exhaustive]
115pub enum AuthError {
116 #[error("this proxy serves sessions only: the request carries no session credential")]
118 Missing,
119 #[error("the session credential is malformed")]
121 Malformed,
122 #[error("the session credential is not valid")]
124 Invalid,
125}
126
127type Looked = (Instant, Option<i64>, Taint);
129
130pub struct Sessions<'a> {
132 credentials: Vec<Credential>,
133 taint: &'a dyn TaintLookup,
134 recent: Mutex<HashMap<String, Looked>>,
138}
139
140impl fmt::Debug for Sessions<'_> {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.debug_struct("Sessions")
143 .field("credentials", &self.credentials)
144 .finish_non_exhaustive()
145 }
146}
147
148impl<'a> Sessions<'a> {
149 #[must_use]
151 pub fn new(credentials: Vec<Credential>, taint: &'a dyn TaintLookup) -> Self {
152 Self {
153 credentials,
154 taint,
155 recent: Mutex::new(HashMap::new()),
156 }
157 }
158
159 pub fn verify<T: AsRef<[u8]>>(&self, headers: &[T]) -> Result<&str, AuthError> {
163 let value = match headers {
164 [] => return Err(AuthError::Missing),
165 [one] => one.as_ref(),
166 _ => return Err(AuthError::Malformed),
167 };
168 let decoded = basic(value).ok_or(AuthError::Malformed)?;
169 let colon = decoded
170 .iter()
171 .position(|b| *b == b':')
172 .ok_or(AuthError::Malformed)?;
173 let (session, token) = (&decoded[..colon], &decoded[colon + 1..]);
174 let mut found = None;
175 for credential in &self.credentials {
176 let id = constant_time_eq(credential.session.as_bytes(), session);
177 let secret = constant_time_eq(&credential.token, token);
178 if id & secret {
179 found = Some(credential.session.as_str());
180 }
181 }
182 found.ok_or(AuthError::Invalid)
183 }
184
185 pub fn taint(&self, session: &str) -> Result<Taint, String> {
187 let version = self.taint.version();
189 let taint = self.taint.taint(session)?;
190 let mut recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
191 recent.insert(session.to_owned(), (Instant::now(), version, taint.clone()));
192 Ok(taint)
193 }
194
195 pub fn taint_within(&self, session: &str, max_age: Duration) -> Result<Taint, String> {
201 let version = self.taint.version();
202 {
203 let recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
204 if let Some((at, seen, taint)) = recent.get(session)
205 && at.elapsed() < max_age
206 && *seen == version
207 {
208 return Ok(taint.clone());
209 }
210 }
211 self.taint(session)
212 }
213}
214
215fn basic(value: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
218 let value = value.trim_ascii();
219 let space = value.iter().position(u8::is_ascii_whitespace)?;
220 let (scheme, rest) = value.split_at(space);
221 if !scheme.eq_ignore_ascii_case(b"basic") {
222 return None;
223 }
224 base64(rest.trim_ascii())
225}
226
227#[must_use]
229pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
230 if a.len() != b.len() {
231 return false;
232 }
233 let diff = a
234 .iter()
235 .zip(b)
236 .fold(0u8, |acc, (x, y)| acc | std::hint::black_box(x ^ y));
237 std::hint::black_box(diff) == 0
238}
239
240fn base64(input: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
242 let data = input
243 .strip_suffix(b"==")
244 .or_else(|| input.strip_suffix(b"="))
245 .unwrap_or(input);
246 let padded = data.len() != input.len();
247 if data.is_empty() || data.len() % 4 == 1 || (padded && !input.len().is_multiple_of(4)) {
248 return None;
249 }
250 let mut out = Zeroizing::new(Vec::with_capacity(data.len() / 4 * 3 + 2));
251 let mut acc: u32 = 0;
252 let mut bits = 0u32;
253 for &c in data {
254 let v = match c {
255 b'A'..=b'Z' => c - b'A',
256 b'a'..=b'z' => c - b'a' + 26,
257 b'0'..=b'9' => c - b'0' + 52,
258 b'+' => 62,
259 b'/' => 63,
260 _ => return None,
261 };
262 acc = (acc << 6) | u32::from(v);
263 bits += 6;
264 if bits >= 8 {
265 bits -= 8;
266 out.push(u8::try_from((acc >> bits) & 0xff).ok()?);
267 acc &= (1 << bits) - 1;
268 }
269 }
270 Some(out)
271}
272
273#[cfg(test)]
274pub(crate) mod tests;