1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub(crate) enum Channel {
35 Plain(u16),
37 Terminated,
39}
40
41struct Held {
43 secret: Secret,
44 placeholder: String,
45 slot: Arc<RwLock<Slot>>,
46}
47
48impl Held {
49 fn live(&self) -> Option<Zeroizing<String>> {
51 read(&self.slot).live().cloned()
52 }
53
54 fn value_in(&self, bytes: &[u8]) -> bool {
56 read(&self.slot)
57 .known()
58 .any(|v| contains(bytes, v.as_bytes()))
59 }
60
61 fn longest_value(&self) -> usize {
63 read(&self.slot).known().map(|v| v.len()).max().unwrap_or(0)
64 }
65
66 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#[derive(Default)]
80pub struct Broker {
81 held: Vec<Held>,
82 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#[derive(Debug, thiserror::Error)]
96#[non_exhaustive]
97pub enum BrokerError {
98 #[error("secret `{0}` is empty")]
100 Empty(String),
101 #[error("secret `{0}` contains a control character")]
104 Control(String),
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum Carried {
110 Placeholder,
112 Value,
114 Decoy,
116}
117
118#[derive(Debug, Clone, Copy)]
120pub struct Leak<'a> {
121 pub id: &'a str,
123 pub owner: &'a str,
125 pub carried: Carried,
127}
128
129impl Leak<'_> {
130 #[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 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 #[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 #[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 #[must_use]
203 pub fn is_empty(&self) -> bool {
204 self.held.is_empty() && self.decoys.is_empty()
205 }
206
207 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 #[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 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 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 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 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 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 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
344fn 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
355pub(crate) struct Watch<'a> {
357 broker: &'a Broker,
358 host: &'a str,
359 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 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
388fn 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
398fn 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
406fn 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
415fn 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;