Skip to main content

openmoat_proxy/
broker.rs

1//! The secrets broker (ADR-020): values the proxy holds for the policy's
2//! `secrets:` list, and where they may go.
3//!
4//! A brokered secret's placeholder and value may be sent to its own host only.
5//! A plain-HTTP request to that host (`plain_http`), or one read inside a
6//! terminated tunnel (`tls: terminate`, ADR-043), gets the value in the
7//! secret's header ([`Broker::inject`]); the agent never needs it. A secret
8//! with `allow` rules goes only into the requests they name; any other request
9//! that would get it is refused before anything is sent (`route.rs`). Any
10//! other request that carries the placeholder or the value, in its head or a
11//! body the proxy reads, is refused and recorded. The check matches exact bytes: it catches a token
12//! sent by mistake or by a naive script, not one that was encoded or split
13//! across requests (`docs/THREAT_MODEL.md`). What keeps a secret safe is that
14//! the agent never holds the value.
15//!
16//! Values are zeroed when dropped and never formatted: [`Debug`] and every
17//! reason this module writes name the secret's id and host only.
18
19use std::sync::{Arc, RwLock};
20
21use openmoat_core::rule_id::PROXY_SECRET;
22use openmoat_core::{Decision, Secret, Verdict};
23use zeroize::Zeroizing;
24
25use self::value::{Slot, read};
26
27/// Where a request to a secret's host travels, which decides whether the
28/// secret goes in.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(crate) enum Channel {
31    /// Plain HTTP to this port: secrets with `plain_http` on it.
32    Plain(u16),
33    /// Read inside a tunnel the proxy terminated: secrets with `tls: terminate`.
34    Terminated,
35}
36
37/// One secret and its value.
38struct Held {
39    secret: Secret,
40    placeholder: String,
41    slot: Arc<RwLock<Slot>>,
42}
43
44impl Held {
45    /// The value to put in now; `None` once it expired unrenewed.
46    fn live(&self) -> Option<Zeroizing<String>> {
47        read(&self.slot).live().cloned()
48    }
49
50    /// Whether `bytes` hold a value of this secret, current or replaced.
51    fn value_in(&self, bytes: &[u8]) -> bool {
52        read(&self.slot)
53            .known()
54            .any(|v| contains(bytes, v.as_bytes()))
55    }
56
57    /// The length of the longest value the checks look for.
58    fn longest_value(&self) -> usize {
59        read(&self.slot).known().map(|v| v.len()).max().unwrap_or(0)
60    }
61
62    /// Whether a request to `host` over `channel` gets this secret.
63    fn injects(&self, host: &str, channel: Channel) -> bool {
64        self.secret.host == host
65            && match channel {
66                Channel::Plain(port) => {
67                    self.secret.plain_http && self.secret.plain_http_port() == port
68                }
69                Channel::Terminated => self.secret.terminates(),
70            }
71    }
72}
73
74/// The brokered secrets of one proxy run. [`Broker::default`] holds none.
75#[derive(Default)]
76pub struct Broker {
77    held: Vec<Held>,
78}
79
80impl std::fmt::Debug for Broker {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_list()
83            .entries(self.held.iter().map(|h| (&h.secret.id, &h.secret.host)))
84            .finish()
85    }
86}
87
88/// A secret value the broker cannot use.
89#[derive(Debug, thiserror::Error)]
90#[non_exhaustive]
91pub enum BrokerError {
92    /// The value is empty.
93    #[error("secret `{0}` is empty")]
94    Empty(String),
95    /// The value holds a control character, which could end the header it is
96    /// put in and start another.
97    #[error("secret `{0}` contains a control character")]
98    Control(String),
99}
100
101/// Which form of a secret a request carried.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum Carried {
104    /// The placeholder the agent holds.
105    Placeholder,
106    /// The value itself.
107    Value,
108}
109
110/// A brokered secret found in a request to another host.
111#[derive(Debug, Clone, Copy)]
112pub struct Leak<'a> {
113    /// The secret's id.
114    pub id: &'a str,
115    /// The only host that may receive it.
116    pub owner: &'a str,
117    /// Placeholder or value.
118    pub carried: Carried,
119}
120
121impl Leak<'_> {
122    /// The deny recorded for a request to `host` that carried this secret.
123    #[must_use]
124    pub fn decision(&self, host: &str) -> Decision {
125        let what = match self.carried {
126            Carried::Placeholder => "placeholder",
127            Carried::Value => "value",
128        };
129        Decision::single(
130            Verdict::Deny,
131            PROXY_SECRET,
132            format!(
133                "request to {host} carries the {what} of secret `{}`, which only {} may receive",
134                self.id, self.owner
135            ),
136        )
137    }
138}
139
140impl Broker {
141    /// A broker for `secrets`, each with its value. The policy has already
142    /// validated the entries; this checks the values.
143    pub fn new(secrets: Vec<(Secret, Zeroizing<String>)>) -> Result<Self, BrokerError> {
144        let mut held = Vec::with_capacity(secrets.len());
145        for (secret, value) in secrets {
146            usable(&secret.id, &value)?;
147            held.push(Held {
148                placeholder: secret.placeholder(),
149                secret,
150                slot: Slot::fixed(value),
151            });
152        }
153        Ok(Self { held })
154    }
155
156    /// The handle that renews secret `id`'s value while the proxy runs, and
157    /// gives it a deadline (ADR-087). `None` for an id the broker does not hold.
158    #[must_use]
159    pub fn rotation(&self, id: &str) -> Option<Rotation> {
160        self.held
161            .iter()
162            .find(|h| h.secret.id == id)
163            .map(|h| Rotation::new(id, &h.slot))
164    }
165
166    /// True when no secret is brokered.
167    #[must_use]
168    pub fn is_empty(&self) -> bool {
169        self.held.is_empty()
170    }
171
172    /// Whether a secret of `host` says `tls: terminate`.
173    pub(crate) fn terminates(&self, host: &str) -> bool {
174        self.held
175            .iter()
176            .any(|h| h.secret.host == host && h.secret.terminates())
177    }
178
179    /// The first secret whose placeholder or value occurs in `bytes`, sent
180    /// towards `host`, that `host` may not receive.
181    #[must_use]
182    pub fn leak(&self, host: &str, bytes: &[u8]) -> Option<Leak<'_>> {
183        self.held
184            .iter()
185            .filter(|h| h.secret.host != host)
186            .find_map(|h| {
187                let carried = if contains(bytes, h.placeholder.as_bytes()) {
188                    Carried::Placeholder
189                } else if h.value_in(bytes) {
190                    Carried::Value
191                } else {
192                    return None;
193                };
194                Some(Leak {
195                    id: &h.secret.id,
196                    owner: &h.secret.host,
197                    carried,
198                })
199            })
200    }
201
202    /// Why each secret `host` owns is not put into a plain-HTTP request to
203    /// `port`: its policy entry does not set `plain_http`, or names another
204    /// port (80 when it names none).
205    pub(crate) fn withheld(&self, host: &str, port: u16) -> Vec<String> {
206        self.held
207            .iter()
208            .filter(|h| h.secret.host == host)
209            .filter_map(|h| {
210                let id = &h.secret.id;
211                if !h.secret.plain_http {
212                    Some(format!(
213                        "secret `{id}` not injected: plain HTTP needs `plain_http: true`"
214                    ))
215                } else if h.secret.plain_http_port() != port {
216                    Some(format!(
217                        "secret `{id}` not injected: it goes to port {} only, not {port}",
218                        h.secret.plain_http_port()
219                    ))
220                } else {
221                    None
222                }
223            })
224            .collect()
225    }
226
227    /// `head` (a request head the proxy wrote, lines ending in CRLF) to
228    /// `host` over `channel`, with the secrets of `host` that channel carries
229    /// ([`Channel`]) put in: in each header a secret names, the placeholder
230    /// becomes the value; a secret whose header is absent, or holds no
231    /// placeholder, gets its own header line. `None` when there is no such
232    /// secret. The caller has checked the request against their `allow` rules
233    /// and deadlines ([`Broker::admit`]); a value that expired since is left
234    /// out, never put in.
235    pub(crate) fn inject(
236        &self,
237        host: &str,
238        channel: Channel,
239        head: &[u8],
240    ) -> Option<Zeroizing<Vec<u8>>> {
241        let owned: Vec<(&Held, Zeroizing<String>)> = self
242            .held
243            .iter()
244            .filter(|h| h.injects(host, channel))
245            .filter_map(|h| Some((h, h.live()?)))
246            .collect();
247        // Each line keeps its `\r`; only the `\n`s are split on and re-added.
248        let lines = head.strip_suffix(b"\n\r\n")?;
249        if owned.is_empty() || echoed(head) {
250            return None;
251        }
252        let mut out = Zeroizing::new(Vec::with_capacity(head.len() + 256));
253        let mut placed = vec![false; owned.len()];
254        // The first line is the request line; the rest are `Name: value`.
255        for (n, line) in lines.split(|b| *b == b'\n').enumerate() {
256            let named = header_name(line).filter(|_| n > 0).and_then(|name| {
257                owned
258                    .iter()
259                    .position(|(h, _)| name.eq_ignore_ascii_case(h.secret.header.as_bytes()))
260            });
261            match named {
262                None => out.extend_from_slice(line),
263                Some(i) if contains(line, owned[i].0.placeholder.as_bytes()) => {
264                    placed[i] = true;
265                    let (h, value) = &owned[i];
266                    replace(line, h.placeholder.as_bytes(), value.as_bytes(), &mut out);
267                }
268                // A value the client chose would reach the owner in place of
269                // the secret: it is dropped, and the secret's line added below.
270                Some(_) => continue,
271            }
272            out.extend_from_slice(b"\n");
273        }
274        for ((h, value), _) in owned.iter().zip(&placed).filter(|(_, p)| !**p) {
275            out.extend_from_slice(format!("{}: ", h.secret.header).as_bytes());
276            out.extend_from_slice(value.as_bytes());
277            out.extend_from_slice(b"\r\n");
278        }
279        out.extend_from_slice(b"\r\n");
280        Some(out)
281    }
282
283    /// Length of the longest placeholder or value: a stream watched in chunks
284    /// keeps one byte less than this from the previous chunk, so a secret
285    /// split across two reads is still found.
286    fn longest(&self) -> usize {
287        self.held
288            .iter()
289            .map(|h| h.placeholder.len().max(h.longest_value()))
290            .max()
291            .unwrap_or(0)
292    }
293}
294
295/// Refuse a value that would break the header it goes in.
296fn usable(id: &str, value: &str) -> Result<(), BrokerError> {
297    if value.is_empty() {
298        return Err(BrokerError::Empty(id.to_owned()));
299    }
300    if value.chars().any(char::is_control) {
301        return Err(BrokerError::Control(id.to_owned()));
302    }
303    Ok(())
304}
305
306/// Watches one client stream towards `host`, chunk by chunk.
307pub(crate) struct Watch<'a> {
308    broker: &'a Broker,
309    host: &'a str,
310    /// The end of the bytes seen so far, kept to find a secret split across
311    /// chunks. It may hold part of a value the client sent, so it is zeroed.
312    tail: Zeroizing<Vec<u8>>,
313}
314
315impl<'a> Watch<'a> {
316    pub(crate) fn new(broker: &'a Broker, host: &'a str) -> Self {
317        Self {
318            broker,
319            host,
320            tail: Zeroizing::new(Vec::new()),
321        }
322    }
323
324    /// Look at the next `chunk` of the stream, with the end of the previous one.
325    pub(crate) fn next(&mut self, chunk: &[u8]) -> Option<Leak<'a>> {
326        if self.broker.is_empty() {
327            return None;
328        }
329        let mut window = Zeroizing::new(Vec::with_capacity(self.tail.len() + chunk.len()));
330        window.extend_from_slice(&self.tail);
331        window.extend_from_slice(chunk);
332        let keep = self.broker.longest().saturating_sub(1).min(window.len());
333        self.tail.clear();
334        self.tail.extend_from_slice(&window[window.len() - keep..]);
335        self.broker.leak(self.host, &window)
336    }
337}
338
339/// Append `line` to `out` with every `from` replaced by `to`.
340fn replace(mut line: &[u8], from: &[u8], to: &[u8], out: &mut Vec<u8>) {
341    while let Some(at) = line.windows(from.len()).position(|w| w == from) {
342        out.extend_from_slice(&line[..at]);
343        out.extend_from_slice(to);
344        line = &line[at + from.len()..];
345    }
346    out.extend_from_slice(line);
347}
348
349/// Whether `head` is a `TRACE` (or IIS's `TRACK`): the answer is the request as
350/// the server got it, so a value put in would come back to the agent.
351/// Compared without regard to case, as some servers read methods.
352fn echoed(head: &[u8]) -> bool {
353    head.get(..6)
354        .is_some_and(|m| m.eq_ignore_ascii_case(b"TRACE ") || m.eq_ignore_ascii_case(b"TRACK "))
355}
356
357/// The name of a `Name: value` header line.
358fn header_name(line: &[u8]) -> Option<&[u8]> {
359    line.iter().position(|b| *b == b':').map(|at| &line[..at])
360}
361
362fn contains(haystack: &[u8], needle: &[u8]) -> bool {
363    !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
364}
365
366mod echo;
367mod route;
368mod value;
369
370pub(crate) use self::echo::{Echo, Holdback, value_came_back};
371pub use self::value::Rotation;
372
373#[cfg(test)]
374mod tests;