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