openmoat-proxy 0.28.0

Default-deny egress proxy for OpenMoat: CONNECT with an SNI check, plain HTTP, its own DNS, an audit record per connection, and opt-in TLS termination for brokered secrets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! The secrets broker (ADR-020): values the proxy holds for the policy's
//! `secrets:` list, and where they may go.
//!
//! A brokered secret's placeholder and value may be sent to its own host only.
//! A plain-HTTP request to that host (`plain_http`), or one read inside a
//! terminated tunnel (`tls: terminate`, ADR-043), gets the value in the
//! secret's header ([`Broker::inject`]); the agent never needs it. A secret
//! with `allow` rules goes only into the requests they name; any other request
//! that would get it is refused before anything is sent (`route.rs`). Any
//! other request that carries the placeholder or the value, in its head or a
//! body the proxy reads, is refused and recorded. The check matches exact bytes: it catches a token
//! sent by mistake or by a naive script, not one that was encoded or split
//! across requests (`docs/THREAT_MODEL.md`). What keeps a secret safe is that
//! the agent never holds the value.
//!
//! Decoy keys `openmoat init` planted (ADR-106) are watched for the same
//! way, towards every host: no request has a reason to carry one, so one that
//! does is refused with rule `canary` ([`Broker::with_decoys`]).
//!
//! Values are zeroed when dropped and never formatted: [`Debug`] and every
//! reason this module writes name the secret's id and host only.

use std::sync::{Arc, RwLock};

use openmoat_core::rule_id::{CANARY, PROXY_SECRET};
use openmoat_core::{Decision, Secret, Verdict};
use zeroize::Zeroizing;

use self::value::{Slot, read};

/// Where a request to a secret's host travels, which decides whether the
/// secret goes in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Channel {
    /// Plain HTTP to this port: secrets with `plain_http` on it.
    Plain(u16),
    /// Read inside a tunnel the proxy terminated: secrets with `tls: terminate`.
    Terminated,
}

/// One secret and its value.
struct Held {
    secret: Secret,
    placeholder: String,
    slot: Arc<RwLock<Slot>>,
}

impl Held {
    /// The value to put in now; `None` once it expired unrenewed.
    fn live(&self) -> Option<Zeroizing<String>> {
        read(&self.slot).live().cloned()
    }

    /// Whether `bytes` hold a value of this secret, current or replaced.
    fn value_in(&self, bytes: &[u8]) -> bool {
        read(&self.slot)
            .known()
            .any(|v| contains(bytes, v.as_bytes()))
    }

    /// The length of the longest value the checks look for.
    fn longest_value(&self) -> usize {
        read(&self.slot).known().map(|v| v.len()).max().unwrap_or(0)
    }

    /// Whether a request to `host` over `channel` gets this secret.
    fn injects(&self, host: &str, channel: Channel) -> bool {
        self.secret.host == host
            && match channel {
                Channel::Plain(port) => {
                    self.secret.plain_http && self.secret.plain_http_port() == port
                }
                Channel::Terminated => self.secret.terminates(),
            }
    }
}

/// The brokered secrets of one proxy run. [`Broker::default`] holds none.
#[derive(Default)]
pub struct Broker {
    held: Vec<Held>,
    /// The decoy values no request may carry, to any host.
    decoys: Vec<Zeroizing<String>>,
}

impl std::fmt::Debug for Broker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list()
            .entries(self.held.iter().map(|h| (&h.secret.id, &h.secret.host)))
            .finish()
    }
}

/// A secret value the broker cannot use.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BrokerError {
    /// The value is empty.
    #[error("secret `{0}` is empty")]
    Empty(String),
    /// The value holds a control character, which could end the header it is
    /// put in and start another.
    #[error("secret `{0}` contains a control character")]
    Control(String),
}

/// Which form of a secret a request carried.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Carried {
    /// The placeholder the agent holds.
    Placeholder,
    /// The value itself.
    Value,
    /// A decoy key's value (ADR-106), which no host may receive.
    Decoy,
}

/// A brokered secret found in a request to another host.
#[derive(Debug, Clone, Copy)]
pub struct Leak<'a> {
    /// The secret's id.
    pub id: &'a str,
    /// The only host that may receive it.
    pub owner: &'a str,
    /// Placeholder or value.
    pub carried: Carried,
}

impl Leak<'_> {
    /// The deny recorded for a request to `host` that carried this secret.
    #[must_use]
    pub fn decision(&self, host: &str) -> Decision {
        let what = match self.carried {
            Carried::Placeholder => "placeholder",
            Carried::Value => "value",
            Carried::Decoy => {
                return Decision::single(
                    Verdict::Deny,
                    CANARY,
                    format!(
                        "request to {host} carries the value of a decoy key OpenMoat planted; \
                         nothing real was sent, but whatever sent it read a decoy"
                    ),
                );
            }
        };
        Decision::single(
            Verdict::Deny,
            PROXY_SECRET,
            format!(
                "request to {host} carries the {what} of secret `{}`, which only {} may receive",
                self.id, self.owner
            ),
        )
    }
}

impl Broker {
    /// A broker for `secrets`, each with its value. The policy has already
    /// validated the entries; this checks the values.
    pub fn new(secrets: Vec<(Secret, Zeroizing<String>)>) -> Result<Self, BrokerError> {
        let mut held = Vec::with_capacity(secrets.len());
        for (secret, value) in secrets {
            usable(&secret.id, &value)?;
            held.push(Held {
                placeholder: secret.placeholder(),
                secret,
                slot: Slot::fixed(value),
            });
        }
        Ok(Self {
            held,
            decoys: Vec::new(),
        })
    }

    /// This broker, also refusing any request that carries one of `values`
    /// (the decoy keys of ADR-106), whatever its host. A value shorter than
    /// [`openmoat_core::canary::MIN_VALUE_LEN`] is not looked for: it would
    /// occur in ordinary traffic.
    #[must_use]
    pub fn with_decoys(mut self, values: impl IntoIterator<Item = Zeroizing<String>>) -> Self {
        self.decoys.extend(
            values
                .into_iter()
                .filter(|v| v.len() >= openmoat_core::canary::MIN_VALUE_LEN),
        );
        self
    }

    /// The handle that renews secret `id`'s value while the proxy runs, and
    /// gives it a deadline (ADR-087). `None` for an id the broker does not hold.
    #[must_use]
    pub fn rotation(&self, id: &str) -> Option<Rotation> {
        self.held
            .iter()
            .find(|h| h.secret.id == id)
            .map(|h| Rotation::new(id, &h.slot))
    }

    /// True when no secret is brokered and no decoy watched for.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.held.is_empty() && self.decoys.is_empty()
    }

    /// Whether a secret of `host` says `tls: terminate`.
    pub(crate) fn terminates(&self, host: &str) -> bool {
        self.held
            .iter()
            .any(|h| h.secret.host == host && h.secret.terminates())
    }

    /// The first secret whose placeholder or value occurs in `bytes`, sent
    /// towards `host`, that `host` may not receive; first of all a decoy,
    /// which no host may.
    #[must_use]
    pub fn leak(&self, host: &str, bytes: &[u8]) -> Option<Leak<'_>> {
        if self
            .decoys
            .iter()
            .any(|v| contains_any_case(bytes, v.as_bytes()))
        {
            return Some(Leak {
                id: "decoy",
                owner: "",
                carried: Carried::Decoy,
            });
        }
        self.held
            .iter()
            .filter(|h| h.secret.host != host)
            .find_map(|h| {
                let carried = if contains(bytes, h.placeholder.as_bytes()) {
                    Carried::Placeholder
                } else if h.value_in(bytes) {
                    Carried::Value
                } else {
                    return None;
                };
                Some(Leak {
                    id: &h.secret.id,
                    owner: &h.secret.host,
                    carried,
                })
            })
    }

    /// Why each secret `host` owns is not put into a plain-HTTP request to
    /// `port`: its policy entry does not set `plain_http`, or names another
    /// port (80 when it names none).
    pub(crate) fn withheld(&self, host: &str, port: u16) -> Vec<String> {
        self.held
            .iter()
            .filter(|h| h.secret.host == host)
            .filter_map(|h| {
                let id = &h.secret.id;
                if !h.secret.plain_http {
                    Some(format!(
                        "secret `{id}` not injected: plain HTTP needs `plain_http: true`"
                    ))
                } else if h.secret.plain_http_port() != port {
                    Some(format!(
                        "secret `{id}` not injected: it goes to port {} only, not {port}",
                        h.secret.plain_http_port()
                    ))
                } else {
                    None
                }
            })
            .collect()
    }

    /// `head` (a request head the proxy wrote, lines ending in CRLF) to
    /// `host` over `channel`, with the secrets of `host` that channel carries
    /// ([`Channel`]) put in: in each header a secret names, the placeholder
    /// becomes the value; a secret whose header is absent, or holds no
    /// placeholder, gets its own header line. `None` when there is no such
    /// secret. The caller has checked the request against their `allow` rules
    /// and deadlines ([`Broker::admit`]); a value that expired since is left
    /// out, never put in.
    pub(crate) fn inject(
        &self,
        host: &str,
        channel: Channel,
        head: &[u8],
    ) -> Option<Zeroizing<Vec<u8>>> {
        let owned: Vec<(&Held, Zeroizing<String>)> = self
            .held
            .iter()
            .filter(|h| h.injects(host, channel))
            .filter_map(|h| Some((h, h.live()?)))
            .collect();
        // Each line keeps its `\r`; only the `\n`s are split on and re-added.
        let lines = head.strip_suffix(b"\n\r\n")?;
        if owned.is_empty() || echoed(head) {
            return None;
        }
        let mut out = Zeroizing::new(Vec::with_capacity(head.len() + 256));
        let mut placed = vec![false; owned.len()];
        // The first line is the request line; the rest are `Name: value`.
        for (n, line) in lines.split(|b| *b == b'\n').enumerate() {
            let named = header_name(line).filter(|_| n > 0).and_then(|name| {
                owned
                    .iter()
                    .position(|(h, _)| name.eq_ignore_ascii_case(h.secret.header.as_bytes()))
            });
            match named {
                None => out.extend_from_slice(line),
                Some(i) if contains(line, owned[i].0.placeholder.as_bytes()) => {
                    placed[i] = true;
                    let (h, value) = &owned[i];
                    replace(line, h.placeholder.as_bytes(), value.as_bytes(), &mut out);
                }
                // A value the client chose would reach the owner in place of
                // the secret: it is dropped, and the secret's line added below.
                Some(_) => continue,
            }
            out.extend_from_slice(b"\n");
        }
        for ((h, value), _) in owned.iter().zip(&placed).filter(|(_, p)| !**p) {
            out.extend_from_slice(format!("{}: ", h.secret.header).as_bytes());
            out.extend_from_slice(value.as_bytes());
            out.extend_from_slice(b"\r\n");
        }
        out.extend_from_slice(b"\r\n");
        Some(out)
    }

    /// Length of the longest placeholder or value: a stream watched in chunks
    /// keeps one byte less than this from the previous chunk, so a secret
    /// split across two reads is still found.
    fn longest(&self) -> usize {
        let decoys = self.decoys.iter().map(|v| v.len());
        self.held
            .iter()
            .map(|h| h.placeholder.len().max(h.longest_value()))
            .chain(decoys)
            .max()
            .unwrap_or(0)
    }
}

/// Refuse a value that would break the header it goes in.
fn usable(id: &str, value: &str) -> Result<(), BrokerError> {
    if value.is_empty() {
        return Err(BrokerError::Empty(id.to_owned()));
    }
    if value.chars().any(char::is_control) {
        return Err(BrokerError::Control(id.to_owned()));
    }
    Ok(())
}

/// Watches one client stream towards `host`, chunk by chunk.
pub(crate) struct Watch<'a> {
    broker: &'a Broker,
    host: &'a str,
    /// The end of the bytes seen so far, kept to find a secret split across
    /// chunks. It may hold part of a value the client sent, so it is zeroed.
    tail: Zeroizing<Vec<u8>>,
}

impl<'a> Watch<'a> {
    pub(crate) fn new(broker: &'a Broker, host: &'a str) -> Self {
        Self {
            broker,
            host,
            tail: Zeroizing::new(Vec::new()),
        }
    }

    /// Look at the next `chunk` of the stream, with the end of the previous one.
    pub(crate) fn next(&mut self, chunk: &[u8]) -> Option<Leak<'a>> {
        if self.broker.is_empty() {
            return None;
        }
        let mut window = Zeroizing::new(Vec::with_capacity(self.tail.len() + chunk.len()));
        window.extend_from_slice(&self.tail);
        window.extend_from_slice(chunk);
        let keep = self.broker.longest().saturating_sub(1).min(window.len());
        self.tail.clear();
        self.tail.extend_from_slice(&window[window.len() - keep..]);
        self.broker.leak(self.host, &window)
    }
}

/// Append `line` to `out` with every `from` replaced by `to`.
fn replace(mut line: &[u8], from: &[u8], to: &[u8], out: &mut Vec<u8>) {
    while let Some(at) = line.windows(from.len()).position(|w| w == from) {
        out.extend_from_slice(&line[..at]);
        out.extend_from_slice(to);
        line = &line[at + from.len()..];
    }
    out.extend_from_slice(line);
}

/// Whether `head` is a `TRACE` (or IIS's `TRACK`): the answer is the request as
/// the server got it, so a value put in would come back to the agent.
/// Compared without regard to case, as some servers read methods.
fn echoed(head: &[u8]) -> bool {
    head.get(..6)
        .is_some_and(|m| m.eq_ignore_ascii_case(b"TRACE ") || m.eq_ignore_ascii_case(b"TRACK "))
}

/// The name of a `Name: value` header line.
fn header_name(line: &[u8]) -> Option<&[u8]> {
    line.iter().position(|b| *b == b':').map(|at| &line[..at])
}

fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
}

/// [`contains`] in any ASCII letter case: a host name reaches the proxy
/// lowercased, or in whatever case the client chose.
fn contains_any_case(haystack: &[u8], needle: &[u8]) -> bool {
    !needle.is_empty()
        && haystack
            .windows(needle.len())
            .any(|w| w.eq_ignore_ascii_case(needle))
}

mod echo;
mod helper;
mod route;
mod value;

pub(crate) use self::echo::{Echo, Holdback, value_came_back};
pub use self::helper::HandOut;
pub use self::value::Rotation;

#[cfg(test)]
mod tests;