openmoat-proxy 0.26.0

Default-deny egress proxy for OpenMoat: CONNECT with an SNI check, plain HTTP, its own DNS, an audit record per connection, and opt-in TLS termination for brokered secrets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use openmoat_core::rule_id::{PROXY_SECRET, PROXY_SECRET_ROUTE};
use openmoat_core::{Policy, Verdict};
use zeroize::Zeroizing;

use super::{Broker, BrokerError, Carried, Channel, Watch};

/// A generated stand-in; no real secret is used anywhere in these tests.
const VALUE: &str = "fake-0123456789abcdef";

fn broker(value: &str) -> Result<Broker, BrokerError> {
    broker_with(value, false)
}

fn broker_with(value: &str, plain_http: bool) -> Result<Broker, BrokerError> {
    let policy = Policy::parse(&format!(
        "version: 1\nsecrets:\n  - id: gh\n    host: api.github.com\n    header: Authorization\n    \
         source: {{ env: FAKE_TOKEN }}\n    plain_http: {plain_http}\n",
    ))
    .unwrap();
    let secrets = policy
        .secrets
        .into_iter()
        .map(|s| (s, Zeroizing::new(value.to_owned())))
        .collect();
    Broker::new(secrets)
}

#[test]
fn values_that_could_break_a_header_are_refused() {
    assert!(matches!(broker(""), Err(BrokerError::Empty(id)) if id == "gh"));
    for bad in ["a\r\nX-Evil: 1", "a\nb", "a\0b"] {
        let err = broker(bad).unwrap_err();
        assert!(matches!(err, BrokerError::Control(_)), "{bad:?}");
        assert!(!err.to_string().contains(bad), "{err}");
    }
}

#[test]
fn the_owner_may_receive_both_forms_and_no_other_host_may() {
    let b = broker(VALUE).unwrap();
    let placeholder = b"Authorization: Bearer moat-secret:gh:placeholder";
    let value = format!("POST /x HTTP/1.1\r\n\r\ntoken={VALUE}");
    assert!(b.leak("api.github.com", placeholder).is_none());
    assert!(b.leak("api.github.com", value.as_bytes()).is_none());
    let leak = b.leak("evil.example", placeholder).unwrap();
    assert_eq!(
        (leak.id, leak.owner, leak.carried),
        ("gh", "api.github.com", Carried::Placeholder)
    );
    let leak = b.leak("github.com", value.as_bytes()).unwrap();
    assert_eq!(leak.carried, Carried::Value);
    let decision = leak.decision("github.com");
    assert_eq!(decision.verdict, Verdict::Deny);
    assert_eq!(decision.rules, [PROXY_SECRET]);
    assert!(!decision.reasons.join(" ").contains(VALUE), "{decision:?}");
    assert!(b.leak("evil.example", b"GET / HTTP/1.1\r\n\r\n").is_none());
}

#[test]
fn a_secret_split_across_chunks_is_found() {
    let b = broker(VALUE).unwrap();
    let stream = format!("{}{VALUE}{}", "x".repeat(5000), "y".repeat(100));
    for cut in 1..VALUE.len() {
        let at = 5000 + cut;
        let mut watch = Watch::new(&b, "evil.example");
        assert!(watch.next(&stream.as_bytes()[..at]).is_none(), "{cut}");
        assert!(watch.next(&stream.as_bytes()[at..]).is_some(), "{cut}");
    }
    let mut owner = Watch::new(&b, "api.github.com");
    assert!(owner.next(stream.as_bytes()).is_none());
}

#[test]
fn nothing_brokered_finds_nothing() {
    let b = Broker::default();
    assert!(
        Watch::new(&b, "evil.example")
            .next(VALUE.as_bytes())
            .is_none()
    );
}

#[test]
fn debug_names_ids_and_hosts_never_values() {
    let shown = format!("{:?}", broker(VALUE).unwrap());
    assert!(
        shown.contains("gh") && shown.contains("api.github.com"),
        "{shown}"
    );
    assert!(!shown.contains(VALUE), "{shown}");
}

#[test]
fn the_owner_head_gets_the_value_in_place_of_the_placeholder() {
    let b = broker_with(VALUE, true).unwrap();
    let head = b"GET /moat-secret:gh:placeholder HTTP/1.1\r\nHost: api.github.com\r\n\
                 authorization: Bearer moat-secret:gh:placeholder\r\n\
                 X-Other: moat-secret:gh:placeholder\r\nConnection: close\r\n\r\n";
    let out = b
        .inject("api.github.com", Channel::Plain(80), head)
        .unwrap();
    assert_eq!(
        String::from_utf8(out.to_vec()).unwrap(),
        format!(
            "GET /moat-secret:gh:placeholder HTTP/1.1\r\nHost: api.github.com\r\n\
             authorization: Bearer {VALUE}\r\nX-Other: moat-secret:gh:placeholder\r\n\
             Connection: close\r\n\r\n"
        )
    );
}

#[test]
fn a_missing_header_is_added_and_other_hosts_get_nothing() {
    let b = broker_with(VALUE, true).unwrap();
    let head = b"GET / HTTP/1.1\r\nHost: api.github.com\r\nConnection: close\r\n\r\n";
    let out = b
        .inject("api.github.com", Channel::Plain(80), head)
        .unwrap();
    let added = format!("Connection: close\r\nAuthorization: {VALUE}\r\n\r\n");
    assert!(out.ends_with(added.as_bytes()));
    assert!(b.inject("github.com", Channel::Plain(80), head).is_none());
    assert!(
        Broker::default()
            .inject("api.github.com", Channel::Plain(80), head)
            .is_none()
    );
    assert_eq!(b.withheld("api.github.com", 80), Vec::<String>::new());
}

#[test]
fn without_plain_http_the_owner_head_is_left_alone() {
    let b = broker(VALUE).unwrap();
    let head = b"GET / HTTP/1.1\r\nAuthorization: moat-secret:gh:placeholder\r\n\r\n";
    assert!(
        b.inject("api.github.com", Channel::Plain(80), head)
            .is_none()
    );
    assert_eq!(
        b.withheld("api.github.com", 80),
        ["secret `gh` not injected: plain HTTP needs `plain_http: true`"]
    );
    assert_eq!(b.withheld("github.com", 80), Vec::<String>::new());
}

#[test]
fn a_request_the_server_echoes_back_gets_no_value() {
    // A TRACE answer (and IIS's TRACK) is the request as the server got it,
    // so a value put in would come back to the agent.
    let b = broker_with(VALUE, true).unwrap();
    for method in ["TRACE", "TRACK", "trace"] {
        let head = format!(
            "{method} / HTTP/1.1\r\nHost: api.github.com\r\n\
             Authorization: moat-secret:gh:placeholder\r\n\r\n"
        );
        assert!(
            b.inject("api.github.com", Channel::Plain(80), head.as_bytes())
                .is_none(),
            "{method}"
        );
    }
    let head = b"TRACEX / HTTP/1.1\r\nHost: api.github.com\r\n\r\n";
    assert!(
        b.inject("api.github.com", Channel::Plain(80), head)
            .is_some()
    );
}

#[test]
fn a_secret_header_without_the_placeholder_is_replaced_by_the_secret() {
    let b = broker_with(VALUE, true).unwrap();
    let head = b"GET / HTTP/1.1\r\nAuthorization: Bearer chosen-by-client\r\n\
                 authorization: Bearer moat-secret:gh:placeholder\r\nX-Other: 1\r\n\r\n";
    let out = String::from_utf8(
        b.inject("api.github.com", Channel::Plain(80), head)
            .unwrap()
            .to_vec(),
    )
    .unwrap();
    assert_eq!(
        out,
        format!("GET / HTTP/1.1\r\nauthorization: Bearer {VALUE}\r\nX-Other: 1\r\n\r\n")
    );
    let head = b"GET / HTTP/1.1\r\nAUTHORIZATION: chosen-by-client\r\n\r\n";
    let out = String::from_utf8(
        b.inject("api.github.com", Channel::Plain(80), head)
            .unwrap()
            .to_vec(),
    )
    .unwrap();
    assert_eq!(
        out,
        format!("GET / HTTP/1.1\r\nAuthorization: {VALUE}\r\n\r\n")
    );
}

/// Plain-HTTP injection is bound to a port: 80, or the one the secret names.
/// Another port of the owner host keeps the placeholder; it is not refused.
#[test]
fn only_the_secrets_port_gets_the_value() {
    let head = b"GET / HTTP/1.1\r\nAuthorization: moat-secret:gh:placeholder\r\n\r\n";
    let default = broker_with(VALUE, true).unwrap();
    assert!(
        default
            .inject("api.github.com", Channel::Plain(80), head)
            .is_some()
    );
    assert!(
        default
            .inject("api.github.com", Channel::Plain(8080), head)
            .is_none()
    );
    assert_eq!(
        default.withheld("api.github.com", 8080),
        ["secret `gh` not injected: it goes to port 80 only, not 8080"]
    );
    assert!(default.leak("api.github.com", head).is_none());
    let policy = Policy::parse(
        "version: 1\nsecrets:\n  - id: gh\n    host: api.github.com\n    header: Authorization\n    \
         source: { env: FAKE_TOKEN }\n    plain_http: true\n    port: 8080\n",
    )
    .unwrap();
    let secrets = policy
        .secrets
        .into_iter()
        .map(|s| (s, Zeroizing::new(VALUE.to_owned())))
        .collect();
    let named = Broker::new(secrets).unwrap();
    let out = named
        .inject("api.github.com", Channel::Plain(8080), head)
        .unwrap();
    assert!(String::from_utf8_lossy(&out).contains(VALUE));
    assert!(
        named
            .inject("api.github.com", Channel::Plain(80), head)
            .is_none()
    );
    assert_eq!(named.withheld("api.github.com", 8080), Vec::<String>::new());
}

fn routed(extra: &str) -> Broker {
    let policy = Policy::parse(&format!(
        "version: 1\nsecrets:\n  - id: gh\n    host: api.github.com\n    header: Authorization\n    \
         source: {{ env: FAKE_TOKEN }}\n{extra}    allow:\n      - GET /repos/**\n      \
         - POST /repos/*/*/issues\n",
    ))
    .unwrap();
    let secrets = policy
        .secrets
        .into_iter()
        .map(|s| (s, Zeroizing::new(VALUE.to_owned())))
        .collect();
    Broker::new(secrets).unwrap()
}

#[test]
fn a_request_the_rules_do_not_name_is_refused_before_the_value_goes_in() {
    let plain = routed("    plain_http: true\n");
    let tls = routed("    tls: terminate\n");
    let head = |line: &str, extra: &str| format!("{line}\r\nHost: api.github.com\r\n{extra}\r\n");
    for (b, channel) in [(&plain, Channel::Plain(80)), (&tls, Channel::Terminated)] {
        let ok = b
            .admit(
                "api.github.com",
                channel,
                head("GET /repos/o/r HTTP/1.1", "").as_bytes(),
            )
            .unwrap();
        assert_eq!(
            ok,
            ["secret `gh` goes in: the request matches `GET /repos/**`"]
        );
        for (line, extra, why) in [
            ("DELETE /repos/o/r HTTP/1.1", "", "matches none"),
            ("GET /user/keys HTTP/1.1", "", "matches none"),
            ("GET /repos/../user/keys HTTP/1.1", "", "`..`"),
            ("GET /repos/%2e%2e/user HTTP/1.1", "", "`..`"),
            ("GET /repos/x%2f..%2fuser HTTP/1.1", "", "decodes to `/`"),
            (
                "POST /repos/o/r/issues HTTP/1.1",
                "X-HTTP-Method-Override: DELETE\r\n",
                "another method",
            ),
            (
                "POST /repos/o/r/issues?_method=DELETE HTTP/1.1",
                "",
                "`_method`",
            ),
        ] {
            let refused = b
                .admit("api.github.com", channel, head(line, extra).as_bytes())
                .unwrap_err();
            assert_eq!(refused.verdict, Verdict::Deny);
            assert_eq!(refused.rules, [PROXY_SECRET_ROUTE]);
            assert!(refused.reasons[0].contains(why), "{line}: {refused:?}");
            assert!(!refused.reasons[0].contains("user"), "no path: {refused:?}");
        }
    }
    // Another channel, another host: the secret does not go in, so no rule applies.
    let other = head("DELETE /x HTTP/1.1", "");
    assert_eq!(
        plain
            .admit("api.github.com", Channel::Plain(8080), other.as_bytes())
            .unwrap(),
        Vec::<String>::new()
    );
    assert_eq!(
        plain
            .admit("api.github.com", Channel::Terminated, other.as_bytes())
            .unwrap(),
        Vec::<String>::new()
    );
    assert_eq!(
        tls.admit("api.github.com", Channel::Plain(80), other.as_bytes())
            .unwrap(),
        Vec::<String>::new()
    );
    assert_eq!(
        tls.admit("github.com", Channel::Terminated, other.as_bytes())
            .unwrap(),
        Vec::<String>::new()
    );
}

#[test]
fn a_terminated_secret_goes_into_tunnel_requests_only() {
    let tls = routed("    tls: terminate\n");
    let head = b"GET /repos/o HTTP/1.1\r\nHost: api.github.com\r\n\r\n";
    let out = tls
        .inject("api.github.com", Channel::Terminated, head)
        .unwrap();
    assert!(String::from_utf8_lossy(&out).contains(&format!("Authorization: {VALUE}\r\n")));
    assert!(
        tls.inject("api.github.com", Channel::Plain(80), head)
            .is_none()
    );
    assert!(
        tls.inject("github.com", Channel::Terminated, head)
            .is_none()
    );
}

/// A plain-HTTP answer passes the same search as a terminated one: a value
/// that comes back, whole or split between reads, closes the connection
/// before it is sent and is reported once; any other answer is sent whole.
#[test]
fn a_plain_answer_is_stopped_before_a_value_it_echoes() {
    use crate::tunnel::Answer as _;
    let b = broker_with(VALUE, true).unwrap();
    let answer = format!("HTTP/1.1 200 OK\r\n\r\nyou sent {VALUE} to us");
    for cut in 0..answer.len() {
        let mut leaked = Vec::new();
        let mut echo = super::Echo::new(&b, |id: &str| leaked.push(id.to_owned()));
        let mut sent = Vec::new();
        let mut stopped = false;
        for part in [&answer.as_bytes()[..cut], &answer.as_bytes()[cut..]] {
            let Some(out) = echo.pass(part) else {
                stopped = true;
                break;
            };
            sent.extend_from_slice(&out);
        }
        if !stopped {
            sent.extend_from_slice(&echo.end());
        }
        drop(echo);
        assert!(stopped, "cut {cut}");
        assert_eq!(leaked, ["gh"], "cut {cut}");
        let sent = String::from_utf8_lossy(&sent);
        assert!(!sent.contains(VALUE), "cut {cut}: {sent}");
    }
    let benign = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
    let mut echo = super::Echo::new(&b, |_: &str| panic!("nothing leaked"));
    let mut sent = echo.pass(benign.as_bytes()).unwrap().to_vec();
    sent.extend_from_slice(&echo.end());
    assert_eq!(sent, benign.as_bytes());
}

/// A decoy value as `openmoat init` plants one (ADR-106), built at run time.
fn decoy() -> String {
    format!("{}_{}{}", "npm", "OpenMoatDecoy", "Hq3Wz8Kp1Lr6Nt9Vb4Xc2Mf")
}

#[test]
fn a_decoy_is_refused_towards_every_host_in_any_case_and_split_across_chunks() {
    let value = decoy();
    let b = Broker::default().with_decoys([Zeroizing::new(value.clone())]);
    assert!(!b.is_empty());
    for host in ["registry.npmjs.org", "evil.example", "api.github.com"] {
        let body = format!("POST /x HTTP/1.1\r\n\r\nt={value}");
        let leak = b.leak(host, body.as_bytes()).unwrap();
        assert_eq!(leak.carried, Carried::Decoy);
        let decision = leak.decision(host);
        assert_eq!(decision.verdict, Verdict::Deny);
        assert_eq!(decision.rules, [openmoat_core::rule_id::CANARY]);
        assert!(!decision.reasons.join(" ").contains(&value), "{decision:?}");
    }
    let lowered = format!(
        "CONNECT {}.evil.example:443 HTTP/1.1\r\n\r\n",
        value.to_lowercase()
    );
    assert!(b.leak("x", lowered.as_bytes()).is_some());
    let (first, second) = value.split_at(10);
    let mut watch = Watch::new(&b, "evil.example");
    assert!(watch.next(format!("GET /?t={first}").as_bytes()).is_none());
    assert!(watch.next(second.as_bytes()).is_some());
    assert!(b.leak("evil.example", b"GET / HTTP/1.1\r\n\r\n").is_none());
}

#[test]
fn a_short_decoy_value_is_not_watched_for() {
    let b = Broker::default().with_decoys([Zeroizing::new("admin".to_owned())]);
    assert!(b.is_empty());
    assert!(b.leak("x", b"user=admin").is_none());
}