1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub(crate) enum Channel {
31 Plain(u16),
33 Terminated,
35}
36
37struct Held {
39 secret: Secret,
40 placeholder: String,
41 slot: Arc<RwLock<Slot>>,
42}
43
44impl Held {
45 fn live(&self) -> Option<Zeroizing<String>> {
47 read(&self.slot).live().cloned()
48 }
49
50 fn value_in(&self, bytes: &[u8]) -> bool {
52 read(&self.slot)
53 .known()
54 .any(|v| contains(bytes, v.as_bytes()))
55 }
56
57 fn longest_value(&self) -> usize {
59 read(&self.slot).known().map(|v| v.len()).max().unwrap_or(0)
60 }
61
62 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#[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#[derive(Debug, thiserror::Error)]
90#[non_exhaustive]
91pub enum BrokerError {
92 #[error("secret `{0}` is empty")]
94 Empty(String),
95 #[error("secret `{0}` contains a control character")]
98 Control(String),
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum Carried {
104 Placeholder,
106 Value,
108}
109
110#[derive(Debug, Clone, Copy)]
112pub struct Leak<'a> {
113 pub id: &'a str,
115 pub owner: &'a str,
117 pub carried: Carried,
119}
120
121impl Leak<'_> {
122 #[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 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 #[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 #[must_use]
168 pub fn is_empty(&self) -> bool {
169 self.held.is_empty()
170 }
171
172 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 #[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 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 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 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 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 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 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
295fn 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
306pub(crate) struct Watch<'a> {
308 broker: &'a Broker,
309 host: &'a str,
310 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 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
339fn 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
349fn 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
357fn 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;