Skip to main content

openmoat_proxy/
server.rs

1//! Accepting connections and deciding each one.
2//!
3//! Order per connection: read the head → (session mode) verify its credential
4//! and take the session's share of the slots → check it for brokered secrets
5//! bound elsewhere → decide the host → (session mode) apply the session's
6//! taint → resolve and check the addresses → connect → (CONNECT) answer 200,
7//! read the `ClientHello` and check its SNI → record → relay, watching a
8//! plain-HTTP body for brokered secrets too, and (session mode) checking the
9//! session's taint again every so often (`recheck.rs`). Nothing reaches the
10//! destination before the record is written; a failed record closes the
11//! connection. Connections refused at accept for capacity are recorded in
12//! coalesced rows (`capacity.rs`).
13
14mod capacity;
15pub(crate) mod helper;
16mod limits;
17mod recheck;
18mod terminate;
19mod unauthenticated;
20mod wire;
21
22use std::io::{self, ErrorKind, Write as _};
23use std::net::{SocketAddr, TcpListener, TcpStream};
24use std::sync::atomic::{AtomicUsize, Ordering};
25use std::thread;
26use std::time::Instant;
27
28use openmoat_core::rule_id::{PROXY_REQUEST, PROXY_SECRET, PROXY_SESSION, PROXY_SNI};
29use openmoat_core::{CompiledPolicy, Decision, Verdict};
30use zeroize::Zeroizing;
31
32use self::capacity::{Full, Refusals};
33pub use self::limits::Limits;
34use self::unauthenticated::{Noise, Unauthenticated};
35pub(crate) use self::wire::response;
36use self::wire::{read_head, read_hello, refuse, respond, summary};
37use crate::audit::{Connection, Recorder};
38use crate::body::{self, BodyEnd, Framing};
39use crate::broker::{Broker, Channel, Echo, Watch, value_came_back};
40use crate::decide;
41use crate::local::{self, LocalService};
42use crate::request::{Request, Target};
43use crate::requests::Requests;
44use crate::session::{Admitted, AuthError, Sessions, Trust};
45use crate::slots::{PENDING, Share, Shares, WITHOUT_CREDENTIAL};
46use crate::tls::Tls;
47use crate::tunnel::{self, Forward};
48use crate::upstream::{self, Refusal, Resolve};
49
50/// Why a request whose chunked body cannot be followed is refused.
51const MALFORMED_CHUNKS: &str = "malformed chunked request body";
52
53/// The proxy: a policy, a resolver, an audit sink and limits.
54#[derive(Clone, Copy)]
55pub struct Proxy<'a> {
56    /// The policy hosts are decided by.
57    pub policy: &'a CompiledPolicy<'a>,
58    /// Name resolution.
59    pub resolver: &'a dyn Resolve,
60    /// Where every decision is recorded.
61    pub recorder: &'a dyn Recorder,
62    /// Resource limits.
63    pub limits: &'a Limits,
64    /// Brokered secrets; [`Broker::default`] for none.
65    pub broker: &'a Broker,
66    /// Loopback addresses the proxy may connect to despite the loopback ban.
67    /// Empty in `moat proxy`; integration tests list their local server.
68    pub loopback_ok: &'a [SocketAddr],
69    /// Forward a `ClientHello` that carries an encrypted server name (ECH,
70    /// ESNI); refused when false (`sandbox.proxy_allow_ech`).
71    pub allow_ech: bool,
72    /// Session mode (ADR-027, ADR-044): every request must carry one of these
73    /// credentials, and is decided with that session's taint and connection
74    /// share. `None` serves any local client with no session; `moat run` and
75    /// `moat proxy` always serve sessions.
76    pub sessions: Option<&'a Sessions<'a>>,
77    /// A service of this process that shares the port (ADR-028): `moat run`
78    /// answers its sandboxed hooks here. `None` in `moat proxy`.
79    pub local: Option<&'a dyn LocalService>,
80    /// TLS termination (ADR-043): a CONNECT to the host of a secret that says
81    /// `tls: terminate` is decrypted, and each request in it checked, given
82    /// the value and recorded. `None`: every tunnel is relayed as it is, as
83    /// in `moat proxy`, whose clients cannot be made to trust the CA.
84    pub tls: Option<&'a Tls>,
85    /// Method and path rules of hosts with no secret (ADR-062 step 0):
86    /// with [`Proxy::tls`] set, a CONNECT to one of their hosts is terminated
87    /// too, and a plain-HTTP request to one is checked. [`Requests::default`]
88    /// for none.
89    pub requests: &'a Requests,
90}
91
92impl std::fmt::Debug for Proxy<'_> {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_struct("Proxy")
95            .field("limits", &self.limits)
96            .field("broker", &self.broker)
97            .field("requests", &self.requests)
98            .field("loopback_ok", &self.loopback_ok)
99            .field("allow_ech", &self.allow_ech)
100            .field("sessions", &self.sessions)
101            .field("local", &self.local.is_some())
102            .field("tls", &self.tls.is_some())
103            .finish_non_exhaustive()
104    }
105}
106
107/// What every connection of one [`Proxy::serve`] shares.
108struct Served<'s> {
109    addresses: &'s CompiledPolicy<'s>,
110    /// [`decide::port_policy`] of the policy, compiled.
111    ports: &'s CompiledPolicy<'s>,
112    shares: Shares,
113    /// Refusals before a credential was verified, recorded at a bounded rate.
114    noise: Noise,
115}
116
117/// One connection's session (`None` without session mode) and start time,
118/// which each of its audit rows carries.
119#[derive(Clone, Copy)]
120struct Turn<'s> {
121    session: Option<&'s str>,
122    /// Which of the session's tunnels may be terminated.
123    trust: Trust,
124    started: Instant,
125}
126
127impl Proxy<'_> {
128    /// Serve connections from `listener` until accepting fails.
129    /// Fails at once when the [`Limits`] are zero or too large.
130    pub fn serve(&self, listener: &TcpListener) -> io::Result<()> {
131        self.limits.check()?;
132        let address_policy = decide::address_policy(self.policy.policy());
133        let addresses = CompiledPolicy::compile(&address_policy, self.policy.context())
134            .map_err(io::Error::other)?;
135        let port_policy = decide::port_policy(self.policy.policy());
136        let ports = CompiledPolicy::compile(&port_policy, self.policy.context())
137            .map_err(io::Error::other)?;
138        let served = Served {
139            addresses: &addresses,
140            ports: &ports,
141            shares: Shares::new(self.limits.max_connections),
142            noise: Noise::default(),
143        };
144        let served = &served;
145        let active = AtomicUsize::new(0);
146        let refusals = Refusals::default();
147        thread::scope(|scope| {
148            loop {
149                let client = match listener.accept() {
150                    Ok((client, _)) => client,
151                    Err(e) if is_transient(&e) => continue,
152                    Err(e) => return Err(e),
153                };
154                refusals.flush(self.recorder, Instant::now());
155                served.noise.flush(self.recorder, Instant::now());
156                let _ = client.set_write_timeout(Some(self.limits.handshake_timeout));
157                let full = |kind: Full| {
158                    respond(&client, 503, kind.reply());
159                    refusals.refused(kind, self.recorder, Instant::now());
160                };
161                let slot = Slot::take(&active, self.limits.max_connections);
162                let Some(slot) = slot else {
163                    full(Full::Slots);
164                    continue;
165                };
166                // Until it authenticates, a connection counts against the
167                // share of all such connections (#555).
168                let pending = if self.sessions.is_some() {
169                    let Some(share) = served.shares.take(PENDING) else {
170                        full(Full::Pending);
171                        continue;
172                    };
173                    Some(share)
174                } else {
175                    None
176                };
177                // A thread that cannot start drops (closes) this connection;
178                // `scope.spawn` would panic and take the proxy down instead.
179                let _ = thread::Builder::new().spawn_scoped(scope, move || {
180                    let _slot = slot;
181                    self.handle(&client, served, pending);
182                });
183            }
184        })
185    }
186
187    fn handle(&self, client: &TcpStream, served: &Served<'_>, pending: Option<Share<'_>>) {
188        let started = Instant::now();
189        let timeout = Some(self.limits.handshake_timeout);
190        if client.set_read_timeout(timeout).is_err() || client.set_write_timeout(timeout).is_err() {
191            return;
192        }
193        // The head may hold the session's credential: zeroed once dropped.
194        let mut buf = Zeroizing::new(Vec::new());
195        let deadline = started + self.limits.handshake_timeout;
196        // A tool's local helper asking for a secret (ADR-118); it carries
197        // the session credential in its line.
198        if local::starts_with(client, helper::HELPER_PREFIX, deadline) {
199            self.helper(client, started);
200            return;
201        }
202        // Still counted as waiting to authenticate: the service checks its own token.
203        if let Some(local) = self.local
204            && !local.prefix().is_empty()
205            && local::starts_with(client, local.prefix(), deadline)
206        {
207            local.serve(client);
208            return;
209        }
210        let request = match read_head(client, &mut buf, self.limits.max_head_bytes, deadline) {
211            Ok(request) => request,
212            Err(why) => {
213                let decision = Decision::single(Verdict::Deny, PROXY_REQUEST, why);
214                let turn = Turn {
215                    session: None,
216                    trust: Trust::None,
217                    started,
218                };
219                // Before any credential: counted, not one row each.
220                if let Some(row) = served.noise.row(Unauthenticated::Head, &decision, started) {
221                    self.record(turn, None, &row);
222                }
223                refuse(client, 400, &decision.reasons[0]);
224                return;
225            }
226        };
227        let Some((session, _share)) = self.admit(client, &request, served, started) else {
228            return;
229        };
230        drop(pending);
231        let turn = Turn {
232            session: session.as_ref().map(|a| a.session.as_str()),
233            trust: session.as_ref().map_or(Trust::None, |a| a.trust),
234            started,
235        };
236        // `buf` holds the head and any body bytes read with it. Watching all of
237        // it before `rest` is split off leaves its end in the watch's tail, so a
238        // secret split between `rest` and the next body chunk is still found.
239        let mut watch = Watch::new(self.broker, request.host());
240        if let Some(leak) = watch.next(&buf) {
241            let decision = leak.decision(request.host());
242            self.record(turn, Some(&request), &decision);
243            refuse(client, 403, &summary(&decision));
244            return;
245        }
246        let rest = Zeroizing::new(buf.split_off(request.head_len));
247        let mut decision =
248            decide::host_port(self.policy, served.ports, request.host(), request.port());
249        if decision.verdict != Verdict::Allow {
250            self.record(turn, Some(&request), &decision);
251            refuse(client, 403, &summary(&decision));
252            return;
253        }
254        // The session's taint, and whether a `requests:` host can be terminated.
255        let reads_only = match self.gate(turn, &request, &mut decision) {
256            Ok(reads_only) => reads_only,
257            Err(refusal) => {
258                self.record(turn, Some(&request), &refusal);
259                refuse(client, 403, &summary(&refusal));
260                return;
261            }
262        };
263        // The host's request rules (ADR-062), then a secret's `allow` rules
264        // (ADR-043), before anything goes upstream.
265        let routed = match &request.target {
266            Target::Http { head, host, port } => {
267                let checked = self.requests.check(host, head).and_then(|ruled| {
268                    let admitted = self.broker.admit(host, Channel::Plain(*port), head)?;
269                    Ok(ruled.into_iter().chain(admitted).collect())
270                });
271                match checked {
272                    Ok(reasons) => reasons,
273                    Err(refusal) => {
274                        self.record(turn, Some(&request), &refusal);
275                        refuse(client, 403, &summary(&refusal));
276                        return;
277                    }
278                }
279            }
280            Target::Connect { .. } => Vec::new(),
281        };
282        if let Target::Connect { host, .. } = &request.target
283            && let Some(tls) = self.terminating(host, turn)
284        {
285            let tunnel = terminate::Opened {
286                allowed: &decision,
287                rest: rest.to_vec(),
288                reads_only,
289            };
290            self.terminate(client, &request, turn, tunnel, served, tls);
291            return;
292        }
293        // A plain-HTTP request is one request: its body is forwarded, and
294        // nothing the client sends after it (body.rs). A tunnel carries TLS,
295        // where the proxy cannot see a secret or a second request.
296        let mut body = BodyEnd::new(match &request.target {
297            Target::Http { head, .. } => body::framing(head),
298            Target::Connect { .. } => Framing::None,
299        });
300        let Ok(body_in_rest) = body.feed(&rest) else {
301            let decision = Decision::single(Verdict::Deny, PROXY_REQUEST, MALFORMED_CHUNKS);
302            self.record(turn, Some(&request), &decision);
303            refuse(client, 400, MALFORMED_CHUNKS);
304            return;
305        };
306        let upstream = match upstream::connect(
307            self.resolver,
308            request.host(),
309            request.port(),
310            served.addresses,
311            self.loopback_ok,
312            self.limits.connect_timeout,
313        ) {
314            Ok(upstream) => upstream,
315            Err(refusal) => {
316                let decision = refusal.decision(request.host());
317                self.record(turn, Some(&request), &decision);
318                let status = if matches!(refusal, Refusal::Address(..) | Refusal::Denied(..)) {
319                    403
320                } else {
321                    502
322                };
323                refuse(client, status, &summary(&decision));
324                return;
325            }
326        };
327        // The body keeps being watched for brokered secrets as it goes by.
328        let mut inspect = |chunk: &[u8]| {
329            let Ok(n) = body.feed(chunk) else {
330                // The allow row is already written; this one says it was cut.
331                let decision = Decision::single(Verdict::Deny, PROXY_REQUEST, MALFORMED_CHUNKS);
332                self.record(turn, Some(&request), &decision);
333                return Forward::Stop;
334            };
335            if let Some(leak) = watch.next(&chunk[..n]) {
336                self.record(turn, Some(&request), &leak.decision(request.host()));
337                return Forward::Stop;
338            }
339            if n < chunk.len() || body.done() {
340                Forward::Part(n)
341            } else {
342                Forward::All
343            }
344        };
345        let mut echo = None;
346        let (first_bytes, inspect) = match &request.target {
347            Target::Connect { host, .. } => {
348                match self.check_tunnel(client, host, rest.to_vec(), &decision, &request, turn) {
349                    Some(hello) => (Zeroizing::new(hello), None),
350                    None => return,
351                }
352            }
353            Target::Http { head, host, port } => {
354                let mut decision = decision.clone();
355                decision.reasons.extend(self.broker.withheld(host, *port));
356                decision.reasons.extend(routed);
357                if !self.record(turn, Some(&request), &decision) {
358                    refuse(client, 403, "audit log unavailable");
359                    return;
360                }
361                let inspect: tunnel::Inspect<'_> = &mut inspect;
362                // Only the owner host's head carries a value; it is zeroed
363                // with `first_bytes` once written.
364                let injected = self.broker.inject(host, Channel::Plain(*port), head);
365                // An answer to a request a value went into is searched for
366                // it, as a terminated tunnel's is (`broker/echo.rs`).
367                let request = &request;
368                echo = injected.as_ref().map(|_| {
369                    Echo::new(self.broker, move |id: &str| {
370                        let why = value_came_back(host, id);
371                        let refused = Decision::single(Verdict::Deny, PROXY_SECRET, why);
372                        self.record(turn, Some(request), &refused);
373                    })
374                });
375                let head = injected.as_deref().map_or(head.as_slice(), Vec::as_slice);
376                let body_bytes = &rest[..body_in_rest];
377                (Zeroizing::new([head, body_bytes].concat()), Some(inspect))
378            }
379        };
380        if (&upstream).write_all(&first_bytes).is_ok() {
381            let still_allowed = || self.still_untainted(turn, &request);
382            let recheck = turn.session.map(|_| tunnel::Recheck {
383                every: self.limits.taint_recheck,
384                still_allowed: &still_allowed,
385            });
386            let answer = echo.as_mut().map(|e| e as &mut dyn tunnel::Answer);
387            tunnel::relay(
388                client,
389                &upstream,
390                self.limits.idle_timeout,
391                (inspect, answer),
392                recheck,
393            );
394        }
395    }
396
397    /// The connection's session and its share of the slots, or `None` once
398    /// the request has been refused and recorded: a missing or invalid
399    /// credential gets `407`, a session holding its share `503`. Without
400    /// session mode every request is admitted, with no session; where the
401    /// sessions serve requests without a credential, one that carries none
402    /// is admitted with no session, in the share of all such requests.
403    fn admit<'s>(
404        &'s self,
405        client: &TcpStream,
406        request: &Request,
407        served: &'s Served<'_>,
408        started: Instant,
409    ) -> Option<(Option<Admitted>, Option<Share<'s>>)> {
410        let unnamed = Turn {
411            session: None,
412            trust: Trust::None,
413            started,
414        };
415        let Some(sessions) = self.sessions else {
416            return Some((None, None));
417        };
418        let (session, holder) = match sessions.admit(&request.credentials) {
419            Ok(admitted) => {
420                let holder = admitted.session.clone();
421                (Some(admitted), holder)
422            }
423            Err(AuthError::Missing) if sessions.serves_without_credential() => {
424                (None, WITHOUT_CREDENTIAL.to_owned())
425            }
426            Err(why) => {
427                let decision = Decision::single(Verdict::Deny, PROXY_SESSION, why.to_string());
428                // Before any credential: counted, not one row each.
429                if let Some(row) = served
430                    .noise
431                    .row(Unauthenticated::Credential, &decision, started)
432                {
433                    self.record(unnamed, Some(request), &row);
434                }
435                refuse(client, 407, &summary(&decision));
436                return None;
437            }
438        };
439        if let Some(share) = served.shares.take(&holder) {
440            return Some((session, Some(share)));
441        }
442        let turn = Turn {
443            session: session.as_ref().map(|a| a.session.as_str()),
444            trust: Trust::None,
445            started,
446        };
447        let holder = if session.is_some() {
448            "the session already holds"
449        } else {
450            "requests without a credential already hold"
451        };
452        let decision = Decision::single(
453            Verdict::Deny,
454            PROXY_SESSION,
455            format!(
456                "{holder} {} connections, half of the proxy's",
457                served.shares.cap()
458            ),
459        );
460        self.record(turn, Some(request), &decision);
461        refuse(client, 503, &summary(&decision));
462        None
463    }
464
465    /// Answer the CONNECT, then hold the tunnel's first bytes until its SNI
466    /// is known to name the CONNECT host. Returns the bytes to forward. Every
467    /// outcome is recorded, a client that cannot be answered too: the
468    /// upstream connection is already open.
469    fn check_tunnel(
470        &self,
471        client: &TcpStream,
472        host: &str,
473        mut hello: Vec<u8>,
474        allowed: &Decision,
475        request: &Request,
476        turn: Turn<'_>,
477    ) -> Option<Vec<u8>> {
478        let answered = (&*client).write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
479        let deadline = Instant::now() + self.limits.handshake_timeout;
480        let read = answered
481            .map_err(|e| format!("answering the CONNECT: {e}"))
482            .and_then(|()| read_hello(client, &mut hello, deadline));
483        let refusal = match read {
484            // With ECH the server acts on the encrypted inner name, which may
485            // be another site behind the same provider as the allowed host.
486            Ok((_, true)) if !self.allow_ech => Some(format!(
487                "TLS ClientHello for CONNECT {host} carries an encrypted server name (ECH), \
488                 so the server may serve another site; `sandbox.proxy_allow_ech: true` \
489                 in the policy allows it"
490            )),
491            Ok((Some(name), _)) if name == host => None,
492            Ok((Some(name), _)) => Some(format!(
493                "TLS server name {name} does not match CONNECT {host}"
494            )),
495            // An IP literal is never sent as SNI (RFC 6066 §3). The bytes are
496            // still a complete `ClientHello`: anything else is an `Err`.
497            Ok((None, _)) if host.parse::<std::net::IpAddr>().is_ok() => None,
498            Ok((None, _)) => Some(format!(
499                "TLS ClientHello for CONNECT {host} has no server name"
500            )),
501            Err(why) => Some(why),
502        };
503        if let Some(why) = refusal {
504            let decision = Decision::single(Verdict::Deny, PROXY_SNI, why);
505            self.record(turn, Some(request), &decision);
506            return None;
507        }
508        self.record(turn, Some(request), allowed).then_some(hello)
509    }
510
511    /// Record a decision; `false` when it could not be recorded, which the
512    /// caller must treat as a deny.
513    fn record(&self, turn: Turn<'_>, request: Option<&Request>, decision: &Decision) -> bool {
514        let connection = Connection {
515            session: turn.session,
516            method: request.map(|r| r.method.as_str()),
517            destination: request.map(|r| (r.host(), r.port())),
518            terminated: false,
519            decision,
520            latency_us: u64::try_from(turn.started.elapsed().as_micros()).unwrap_or(u64::MAX),
521        };
522        self.write_row(&connection)
523    }
524
525    /// Record `connection`; `false` when it could not be recorded.
526    fn write_row(&self, connection: &Connection<'_>) -> bool {
527        match self.recorder.record(connection) {
528            Ok(()) => true,
529            Err(error) => {
530                // The caller refuses the connection; the recorder reports the
531                // failure elsewhere, since the audit log is what failed.
532                self.recorder.unrecorded(&error);
533                false
534            }
535        }
536    }
537}
538
539/// One of the `max_connections` slots, released when dropped, even if the
540/// connection's thread panics.
541struct Slot<'a>(&'a AtomicUsize);
542
543impl<'a> Slot<'a> {
544    fn take(active: &'a AtomicUsize, max: usize) -> Option<Self> {
545        // A slot taken over the cap is given back at once; the count never
546        // stays above `max`.
547        let slot = Self(active);
548        (active.fetch_add(1, Ordering::AcqRel) < max).then_some(slot)
549    }
550}
551
552impl Drop for Slot<'_> {
553    fn drop(&mut self) {
554        self.0.fetch_sub(1, Ordering::AcqRel);
555    }
556}
557
558fn is_transient(e: &io::Error) -> bool {
559    matches!(
560        e.kind(),
561        ErrorKind::Interrupted | ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset
562    )
563}
564
565#[cfg(test)]
566mod tests;