Skip to main content

openmoat_proxy/server/
helper.rs

1//! The proxy's answer to a tool's local helper (ADR-118), on the proxy's port.
2//!
3//! `openmoat credential`, started by git or the AWS CLI inside the sandbox,
4//! connects to the port the agent's proxy variables name and sends one line:
5//!
6//! ```text
7//! MOAT-HELPER/1 <tool> <secret-id> <host or -> <base64 of session:token>
8//! ```
9//!
10//! with the session credential from those variables, so only the session's
11//! processes can ask. The answer is one line, `OK <user or -> <value>` or
12//! `NO <reason>`. The broker decides ([`Broker::hand_out`]); the decision is
13//! recorded before the value is sent, and a row that cannot be written
14//! sends nothing.
15
16use std::io::{Read as _, Write as _};
17use std::net::TcpStream;
18use std::time::Instant;
19
20use openmoat_core::rule_id::{PROXY_HELPER, PROXY_SESSION};
21use openmoat_core::{Decision, Verdict};
22use zeroize::Zeroizing;
23
24use super::Proxy;
25use crate::audit::Connection;
26use crate::broker::Broker;
27
28/// What a helper's request starts with; no HTTP method does.
29pub const HELPER_PREFIX: &[u8] = b"MOAT-HELPER/1 ";
30
31/// The longest request line read.
32const MAX_LINE: usize = 4096;
33
34/// The request line a helper sends: `tool` asks for secret `id` for `host`
35/// (`None` for a helper that names no host), with the session's proxy
36/// credential `basic` (base64 of `session:token`).
37#[must_use]
38pub fn helper_request(tool: &str, id: &str, host: Option<&str>, basic: &str) -> Zeroizing<Vec<u8>> {
39    let line = format!(
40        "{}{tool} {id} {} {basic}\n",
41        String::from_utf8_lossy(HELPER_PREFIX),
42        host.unwrap_or("-")
43    );
44    Zeroizing::new(line.into_bytes())
45}
46
47/// The fields of one request line.
48struct Asked<'a> {
49    tool: &'a str,
50    id: &'a str,
51    host: Option<&'a str>,
52    basic: &'a str,
53}
54
55fn parse(line: &str) -> Option<Asked<'_>> {
56    let rest = line.strip_prefix(std::str::from_utf8(HELPER_PREFIX).ok()?)?;
57    let mut words = rest.trim_end_matches(['\r', '\n']).split(' ');
58    let asked = Asked {
59        tool: words.next().filter(|w| !w.is_empty())?,
60        id: words.next().filter(|w| !w.is_empty())?,
61        host: words.next().filter(|w| *w != "-"),
62        basic: words.next().filter(|w| !w.is_empty())?,
63    };
64    words.next().is_none().then_some(asked)
65}
66
67/// The line the helper sent, up to its newline; `None` for one too long,
68/// cut short or not UTF-8.
69fn read_line(client: &TcpStream) -> Option<Zeroizing<String>> {
70    let mut line = Zeroizing::new(Vec::with_capacity(256));
71    let mut byte = [0u8; 1];
72    let mut reader = client;
73    while line.len() < MAX_LINE {
74        match reader.read(&mut byte) {
75            Ok(1) if byte[0] == b'\n' => {
76                return String::from_utf8(line.to_vec()).ok().map(Zeroizing::new);
77            }
78            Ok(1) => line.push(byte[0]),
79            _ => return None,
80        }
81    }
82    None
83}
84
85impl Proxy<'_> {
86    /// Answer one helper connection.
87    pub(super) fn helper(&self, client: &TcpStream, started: Instant) {
88        let deny = |rule: &str, why: String| Decision::single(Verdict::Deny, rule, why);
89        let Some(line) = read_line(client) else {
90            let decision = deny(
91                PROXY_HELPER,
92                "a helper request that could not be read".into(),
93            );
94            self.helper_row(None, None, &decision, started);
95            answer(client, None, &decision);
96            return;
97        };
98        let Some(asked) = parse(&line) else {
99            let decision = deny(
100                PROXY_HELPER,
101                "a helper request that is not well formed".into(),
102            );
103            self.helper_row(None, None, &decision, started);
104            answer(client, None, &decision);
105            return;
106        };
107        // Only the session's own processes, which hold its proxy credential.
108        let session = self
109            .sessions
110            .map(|sessions| sessions.admit(&[format!("Basic {}", asked.basic)]));
111        let session = match session {
112            Some(Ok(admitted)) => admitted.session,
113            Some(Err(error)) => {
114                let decision = deny(PROXY_SESSION, format!("helper request refused: {error}"));
115                self.helper_row(None, asked.host, &decision, started);
116                answer(client, None, &decision);
117                return;
118            }
119            None => {
120                let decision = deny(
121                    PROXY_HELPER,
122                    "this proxy serves no sessions, so it hands nothing to helpers".into(),
123                );
124                self.helper_row(None, asked.host, &decision, started);
125                answer(client, None, &decision);
126                return;
127            }
128        };
129        let broker: &Broker = self.broker;
130        match broker.hand_out(asked.tool, asked.id, asked.host) {
131            Ok(out) => {
132                if self.helper_row(Some(&session), Some(out.host), &out.decision, started) {
133                    answer(client, Some((out.username, &out.value)), &out.decision);
134                } else {
135                    let decision = deny(PROXY_HELPER, "the audit log is unavailable".into());
136                    answer(client, None, &decision);
137                }
138            }
139            Err(decision) => {
140                self.helper_row(Some(&session), asked.host, &decision, started);
141                answer(client, None, &decision);
142            }
143        }
144    }
145
146    fn helper_row(
147        &self,
148        session: Option<&str>,
149        host: Option<&str>,
150        decision: &Decision,
151        started: Instant,
152    ) -> bool {
153        self.write_row(&Connection {
154            session,
155            method: Some("HELPER"),
156            destination: host.map(|h| (h, 443)),
157            terminated: false,
158            decision,
159            latency_us: u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),
160        })
161    }
162}
163
164/// Write the answer: `OK <user or -> <value>` when `given`, else `NO <reason>`.
165fn answer(mut client: &TcpStream, given: Option<(Option<&str>, &str)>, decision: &Decision) {
166    let line = if let Some((user, value)) = given {
167        Zeroizing::new(format!("OK {} {value}\n", user.unwrap_or("-")))
168    } else {
169        let why = decision.reasons.first().map_or("refused", String::as_str);
170        Zeroizing::new(format!("NO {}\n", why.replace(['\r', '\n'], " ")))
171    };
172    // Nothing more to do for a helper that went away: the row is written.
173    let _ = client
174        .write_all(line.as_bytes())
175        .and_then(|()| client.flush());
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn a_request_line_round_trips() {
184        let line = helper_request("git", "gh-git", Some("github.com"), "c2VzczpzZWNyZXQ=");
185        let text = String::from_utf8(line.to_vec()).unwrap();
186        assert_eq!(
187            text,
188            "MOAT-HELPER/1 git gh-git github.com c2VzczpzZWNyZXQ=\n"
189        );
190        let asked = parse(&text).unwrap();
191        assert_eq!(
192            (asked.tool, asked.id, asked.host),
193            ("git", "gh-git", Some("github.com"))
194        );
195        assert_eq!(asked.basic, "c2VzczpzZWNyZXQ=");
196        let aws = String::from_utf8(helper_request("aws", "s3", None, "eA==").to_vec()).unwrap();
197        assert_eq!(parse(&aws).unwrap().host, None);
198    }
199
200    #[test]
201    fn a_malformed_line_is_not_read() {
202        for bad in [
203            "GET / HTTP/1.1\n",
204            "MOAT-HELPER/1 git\n",
205            "MOAT-HELPER/1 git id host\n",
206            "MOAT-HELPER/1 git id host cred extra\n",
207            "MOAT-HELPER/1  id host cred\n",
208        ] {
209            assert!(parse(bad).is_none(), "{bad:?}");
210        }
211    }
212}