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