-
Notifications
You must be signed in to change notification settings - Fork 590
Expand file tree
/
Copy pathproxy.rs
More file actions
2973 lines (2706 loc) · 101 KB
/
proxy.rs
File metadata and controls
2973 lines (2706 loc) · 101 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! HTTP CONNECT proxy with OPA policy evaluation and process-identity binding.
use crate::denial_aggregator::DenialEvent;
use crate::identity::BinaryIdentityCache;
use crate::l7::tls::ProxyTlsState;
use crate::opa::{NetworkAction, OpaEngine};
use crate::policy::ProxyPolicy;
use crate::secrets::{SecretResolver, rewrite_header_line};
use miette::{IntoDiagnostic, Result};
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
const MAX_HEADER_BYTES: usize = 8192;
const INFERENCE_LOCAL_HOST: &str = "inference.local";
/// Maximum total bytes for a streaming inference response body (32 MiB).
const MAX_STREAMING_BODY: usize = 32 * 1024 * 1024;
/// Idle timeout per chunk when relaying streaming inference responses.
const CHUNK_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
/// Result of a proxy CONNECT policy decision.
struct ConnectDecision {
action: NetworkAction,
/// Resolved binary path.
binary: Option<PathBuf>,
/// PID owning the socket.
binary_pid: Option<u32>,
/// Ancestor binary paths from process tree walk.
ancestors: Vec<PathBuf>,
/// Cmdline-derived absolute paths (for script detection).
cmdline_paths: Vec<PathBuf>,
}
/// Outcome of an inference interception attempt.
///
/// Returned by [`handle_inference_interception`] so the call site can emit
/// a structured CONNECT deny log when the connection is not successfully routed.
enum InferenceOutcome {
/// At least one request was successfully routed to a local inference backend.
Routed,
/// The connection was denied (TLS failure, non-inference request, etc.).
Denied { reason: String },
}
/// Inference routing context for sandbox-local execution.
///
/// Holds a `Router` (HTTP client) and cached sets of resolved routes.
/// User routes serve `inference.local` traffic; system routes are consumed
/// in-process by the supervisor for platform functions (e.g. agent harness).
pub struct InferenceContext {
pub patterns: Vec<crate::l7::inference::InferenceApiPattern>,
router: openshell_router::Router,
/// Routes for the user-facing `inference.local` endpoint.
routes: Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>>,
/// Routes for supervisor-only system inference (`sandbox-system`).
system_routes: Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>>,
}
impl InferenceContext {
pub fn new(
patterns: Vec<crate::l7::inference::InferenceApiPattern>,
router: openshell_router::Router,
routes: Vec<openshell_router::config::ResolvedRoute>,
system_routes: Vec<openshell_router::config::ResolvedRoute>,
) -> Self {
Self {
patterns,
router,
routes: Arc::new(tokio::sync::RwLock::new(routes)),
system_routes: Arc::new(tokio::sync::RwLock::new(system_routes)),
}
}
/// Get a handle to the user route cache for background refresh.
pub fn route_cache(
&self,
) -> Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>> {
self.routes.clone()
}
/// Get a handle to the system route cache for background refresh.
pub fn system_route_cache(
&self,
) -> Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>> {
self.system_routes.clone()
}
/// Make an inference call using system routes (supervisor-only).
///
/// This is the in-process API for platform functions. It bypasses the
/// CONNECT proxy entirely — the supervisor calls the router directly
/// from the host network namespace.
pub async fn system_inference(
&self,
protocol: &str,
method: &str,
path: &str,
headers: Vec<(String, String)>,
body: bytes::Bytes,
) -> Result<openshell_router::ProxyResponse, openshell_router::RouterError> {
let routes = self.system_routes.read().await;
self.router
.proxy_with_candidates(protocol, method, path, headers, body, &routes)
.await
}
}
#[derive(Debug)]
pub struct ProxyHandle {
#[allow(dead_code)]
http_addr: Option<SocketAddr>,
join: JoinHandle<()>,
}
impl ProxyHandle {
/// Start the proxy with OPA engine for policy evaluation.
///
/// The proxy uses OPA for network decisions with process-identity binding
/// via `/proc/net/tcp`. All connections are evaluated through OPA policy.
#[allow(clippy::too_many_arguments)]
pub async fn start_with_bind_addr(
policy: &ProxyPolicy,
bind_addr: Option<SocketAddr>,
opa_engine: Arc<OpaEngine>,
identity_cache: Arc<BinaryIdentityCache>,
entrypoint_pid: Arc<AtomicU32>,
tls_state: Option<Arc<ProxyTlsState>>,
inference_ctx: Option<Arc<InferenceContext>>,
secret_resolver: Option<Arc<SecretResolver>>,
denial_tx: Option<mpsc::UnboundedSender<DenialEvent>>,
) -> Result<Self> {
// Use override bind_addr, fall back to policy http_addr, then default
// to loopback:3128. The default allows the proxy to function when no
// network namespace is available (e.g. missing CAP_NET_ADMIN) and the
// policy doesn't specify an explicit address.
let default_addr: SocketAddr = ([127, 0, 0, 1], 3128).into();
let http_addr = bind_addr.or(policy.http_addr).unwrap_or(default_addr);
// Only enforce loopback restriction when not using network namespace override
if bind_addr.is_none() && !http_addr.ip().is_loopback() {
return Err(miette::miette!(
"Proxy http_addr must be loopback-only: {http_addr}"
));
}
let listener = TcpListener::bind(http_addr).await.into_diagnostic()?;
let local_addr = listener.local_addr().into_diagnostic()?;
info!(addr = %local_addr, "Proxy listening (tcp)");
let join = tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, _addr)) => {
let opa = opa_engine.clone();
let cache = identity_cache.clone();
let spid = entrypoint_pid.clone();
let tls = tls_state.clone();
let inf = inference_ctx.clone();
let resolver = secret_resolver.clone();
let dtx = denial_tx.clone();
tokio::spawn(async move {
if let Err(err) = handle_tcp_connection(
stream, opa, cache, spid, tls, inf, resolver, dtx,
)
.await
{
warn!(error = %err, "Proxy connection error");
}
});
}
Err(err) => {
warn!(error = %err, "Proxy accept error");
break;
}
}
}
});
Ok(Self {
http_addr: Some(local_addr),
join,
})
}
#[allow(dead_code)]
pub const fn http_addr(&self) -> Option<SocketAddr> {
self.http_addr
}
}
impl Drop for ProxyHandle {
fn drop(&mut self) {
self.join.abort();
}
}
/// Emit a denial event to the aggregator channel (if configured).
/// Used by `handle_tcp_connection` which owns `Option<Sender>`.
fn emit_denial(
tx: &Option<mpsc::UnboundedSender<DenialEvent>>,
host: &str,
port: u16,
binary: &str,
decision: &ConnectDecision,
reason: &str,
stage: &str,
) {
if let Some(tx) = tx {
let _ = tx.send(DenialEvent {
host: host.to_string(),
port,
binary: binary.to_string(),
ancestors: decision
.ancestors
.iter()
.map(|p| p.display().to_string())
.collect(),
deny_reason: reason.to_string(),
denial_stage: stage.to_string(),
l7_method: None,
l7_path: None,
});
}
}
/// Emit a denial event from a borrowed sender reference.
/// Used by `handle_forward_proxy` which borrows `Option<&Sender>`.
fn emit_denial_simple(
tx: Option<&mpsc::UnboundedSender<DenialEvent>>,
host: &str,
port: u16,
binary: &str,
decision: &ConnectDecision,
reason: &str,
stage: &str,
) {
if let Some(tx) = tx {
let _ = tx.send(DenialEvent {
host: host.to_string(),
port,
binary: binary.to_string(),
ancestors: decision
.ancestors
.iter()
.map(|p| p.display().to_string())
.collect(),
deny_reason: reason.to_string(),
denial_stage: stage.to_string(),
l7_method: None,
l7_path: None,
});
}
}
async fn handle_tcp_connection(
mut client: TcpStream,
opa_engine: Arc<OpaEngine>,
identity_cache: Arc<BinaryIdentityCache>,
entrypoint_pid: Arc<AtomicU32>,
tls_state: Option<Arc<ProxyTlsState>>,
inference_ctx: Option<Arc<InferenceContext>>,
secret_resolver: Option<Arc<SecretResolver>>,
denial_tx: Option<mpsc::UnboundedSender<DenialEvent>>,
) -> Result<()> {
let mut buf = vec![0u8; MAX_HEADER_BYTES];
let mut used = 0usize;
loop {
if used == buf.len() {
respond(
&mut client,
b"HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n",
)
.await?;
return Ok(());
}
let n = client.read(&mut buf[used..]).await.into_diagnostic()?;
if n == 0 {
return Ok(());
}
used += n;
if buf[..used].windows(4).any(|win| win == b"\r\n\r\n") {
break;
}
}
let request = String::from_utf8_lossy(&buf[..used]);
let mut lines = request.split("\r\n");
let request_line = lines.next().unwrap_or("");
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("");
let target = parts.next().unwrap_or("");
if method != "CONNECT" {
return handle_forward_proxy(
method,
target,
&buf[..],
used,
&mut client,
opa_engine,
identity_cache,
entrypoint_pid,
secret_resolver,
denial_tx.as_ref(),
)
.await;
}
let (host, port) = parse_target(target)?;
let host_lc = host.to_ascii_lowercase();
if host_lc == INFERENCE_LOCAL_HOST {
respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?;
let outcome = handle_inference_interception(
client,
INFERENCE_LOCAL_HOST,
port,
tls_state.as_ref(),
inference_ctx.as_ref(),
)
.await?;
if let InferenceOutcome::Denied { reason } = outcome {
info!(action = "deny", reason = %reason, host = INFERENCE_LOCAL_HOST, "Inference interception denied");
}
return Ok(());
}
let peer_addr = client.peer_addr().into_diagnostic()?;
let local_addr = client.local_addr().into_diagnostic()?;
// Evaluate OPA policy with process-identity binding.
// Wrapped in spawn_blocking because identity resolution does heavy sync I/O:
// /proc scanning + SHA256 hashing of binaries (e.g. node at 124MB).
let opa_clone = opa_engine.clone();
let cache_clone = identity_cache.clone();
let pid_clone = entrypoint_pid.clone();
let host_clone = host_lc.clone();
let decision = tokio::task::spawn_blocking(move || {
evaluate_opa_tcp(
peer_addr,
&opa_clone,
&cache_clone,
&pid_clone,
&host_clone,
port,
)
})
.await
.map_err(|e| miette::miette!("identity resolution task panicked: {e}"))?;
// Extract action string and matched policy for logging
let (matched_policy, deny_reason) = match &decision.action {
NetworkAction::Allow { matched_policy } => (matched_policy.clone(), String::new()),
NetworkAction::Deny { reason } => (None, reason.clone()),
};
// Build log context fields (shared by deny log below and deferred allow log after L7 check)
let binary_str = decision
.binary
.as_ref()
.map_or_else(|| "-".to_string(), |p| p.display().to_string());
let pid_str = decision
.binary_pid
.map_or_else(|| "-".to_string(), |p| p.to_string());
let ancestors_str = if decision.ancestors.is_empty() {
"-".to_string()
} else {
decision
.ancestors
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(" -> ")
};
let cmdline_str = if decision.cmdline_paths.is_empty() {
"-".to_string()
} else {
decision
.cmdline_paths
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
};
let policy_str = matched_policy.as_deref().unwrap_or("-");
// Log denied connections immediately — they never reach L7.
// Allowed connections are logged after the L7 config check (below)
// so we can distinguish CONNECT (L4-only) from CONNECT_L7 (L7 follows).
if matches!(decision.action, NetworkAction::Deny { .. }) {
info!(
src_addr = %peer_addr.ip(),
src_port = peer_addr.port(),
proxy_addr = %local_addr,
dst_host = %host_lc,
dst_port = port,
binary = %binary_str,
binary_pid = %pid_str,
ancestors = %ancestors_str,
cmdline = %cmdline_str,
action = "deny",
engine = "opa",
policy = "-",
reason = %deny_reason,
"CONNECT",
);
emit_denial(
&denial_tx,
&host_lc,
port,
&binary_str,
&decision,
&deny_reason,
"connect",
);
respond(&mut client, b"HTTP/1.1 403 Forbidden\r\n\r\n").await?;
return Ok(());
}
// Query allowed_ips from the matched endpoint config (if any).
// When present, the SSRF check validates resolved IPs against this
// allowlist instead of blanket-blocking all private IPs.
// When the policy host is already a literal IP address, treat it as
// implicitly allowed — the user explicitly declared the destination.
let mut raw_allowed_ips = query_allowed_ips(&opa_engine, &decision, &host_lc, port);
if raw_allowed_ips.is_empty() {
raw_allowed_ips = implicit_allowed_ips_for_ip_host(&host);
}
// Defense-in-depth: resolve DNS and reject connections to internal IPs.
let dns_connect_start = std::time::Instant::now();
let mut upstream = if !raw_allowed_ips.is_empty() {
// allowed_ips mode: validate resolved IPs against CIDR allowlist.
// Loopback and link-local are still always blocked.
match parse_allowed_ips(&raw_allowed_ips) {
Ok(nets) => match resolve_and_check_allowed_ips(&host, port, &nets).await {
Ok(addrs) => TcpStream::connect(addrs.as_slice())
.await
.into_diagnostic()?,
Err(reason) => {
warn!(
dst_host = %host_lc,
dst_port = port,
reason = %reason,
"CONNECT blocked: allowed_ips check failed"
);
emit_denial(
&denial_tx,
&host_lc,
port,
&binary_str,
&decision,
&reason,
"ssrf",
);
respond(&mut client, b"HTTP/1.1 403 Forbidden\r\n\r\n").await?;
return Ok(());
}
},
Err(reason) => {
warn!(
dst_host = %host_lc,
dst_port = port,
reason = %reason,
"CONNECT blocked: invalid allowed_ips in policy"
);
emit_denial(
&denial_tx,
&host_lc,
port,
&binary_str,
&decision,
&reason,
"ssrf",
);
respond(&mut client, b"HTTP/1.1 403 Forbidden\r\n\r\n").await?;
return Ok(());
}
}
} else {
// Default: reject all internal IPs (loopback, RFC 1918, link-local).
match resolve_and_reject_internal(&host, port).await {
Ok(addrs) => TcpStream::connect(addrs.as_slice())
.await
.into_diagnostic()?,
Err(reason) => {
warn!(
dst_host = %host_lc,
dst_port = port,
reason = %reason,
"CONNECT blocked: internal address"
);
emit_denial(
&denial_tx,
&host_lc,
port,
&binary_str,
&decision,
&reason,
"ssrf",
);
respond(&mut client, b"HTTP/1.1 403 Forbidden\r\n\r\n").await?;
return Ok(());
}
}
};
debug!(
"handle_tcp_connection dns_resolve_and_tcp_connect: {}ms host={host_lc}",
dns_connect_start.elapsed().as_millis()
);
respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?;
// Check if endpoint has L7 config for protocol-aware inspection
let l7_config = query_l7_config(&opa_engine, &decision, &host_lc, port);
// Log the allowed CONNECT — use CONNECT_L7 when L7 inspection follows,
// so log consumers can distinguish L4-only decisions from tunnel lifecycle events.
let connect_msg = if l7_config.is_some() {
"CONNECT_L7"
} else {
"CONNECT"
};
info!(
src_addr = %peer_addr.ip(),
src_port = peer_addr.port(),
proxy_addr = %local_addr,
dst_host = %host_lc,
dst_port = port,
binary = %binary_str,
binary_pid = %pid_str,
ancestors = %ancestors_str,
cmdline = %cmdline_str,
action = "allow",
engine = "opa",
policy = %policy_str,
reason = "",
"{connect_msg}",
);
// Determine effective TLS mode. Check the raw endpoint config for
// `tls: skip` independently of L7 config (which requires `protocol`).
let effective_tls_skip =
query_tls_mode(&opa_engine, &decision, &host_lc, port) == crate::l7::TlsMode::Skip;
// Build L7 eval context (shared by TLS-terminated and plaintext paths).
let ctx = crate::l7::relay::L7EvalContext {
host: host_lc.clone(),
port,
policy_name: matched_policy.clone().unwrap_or_default(),
binary_path: decision
.binary
.as_ref()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default(),
ancestors: decision
.ancestors
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect(),
cmdline_paths: decision
.cmdline_paths
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect(),
secret_resolver: secret_resolver.clone(),
};
if effective_tls_skip {
// tls: skip — raw tunnel, no termination, no credential injection.
debug!(
host = %host_lc,
port = port,
"tls: skip — bypassing TLS auto-detection, raw tunnel"
);
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream)
.await
.into_diagnostic()?;
return Ok(());
}
// Auto-detect TLS by peeking the first bytes.
let mut peek_buf = [0u8; 8];
let n = client.peek(&mut peek_buf).await.into_diagnostic()?;
if n == 0 {
return Ok(());
}
let is_tls = crate::l7::tls::looks_like_tls(&peek_buf[..n]);
let is_http = crate::l7::rest::looks_like_http(&peek_buf[..n]);
if is_tls {
// TLS detected — terminate unconditionally.
if let Some(ref tls) = tls_state {
let tls_result = async {
let mut tls_client =
crate::l7::tls::tls_terminate_client(client, tls, &host_lc).await?;
let mut tls_upstream =
crate::l7::tls::tls_connect_upstream(upstream, &host_lc, tls.upstream_config())
.await?;
if let Some(ref l7_config) = l7_config {
// L7 inspection on terminated TLS traffic.
let tunnel_engine =
opa_engine.clone_engine_for_tunnel().unwrap_or_else(|e| {
warn!(error = %e, "Failed to clone OPA engine for L7, falling back to relay-only");
regorus::Engine::new()
});
crate::l7::relay::relay_with_inspection(
l7_config,
std::sync::Mutex::new(tunnel_engine),
&mut tls_client,
&mut tls_upstream,
&ctx,
)
.await
} else {
// No L7 config — relay with credential injection only.
crate::l7::relay::relay_passthrough_with_credentials(
&mut tls_client,
&mut tls_upstream,
&ctx,
)
.await
}
};
if let Err(e) = tls_result.await {
if is_benign_relay_error(&e) {
debug!(
host = %host_lc,
port = port,
error = %e,
"TLS connection closed"
);
} else {
warn!(
host = %host_lc,
port = port,
error = %e,
"TLS relay error"
);
}
}
} else {
warn!(
host = %host_lc,
port = port,
"TLS detected but TLS state not configured, falling back to raw tunnel"
);
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream)
.await
.into_diagnostic()?;
}
} else if is_http {
// Plaintext HTTP detected.
if let Some(ref l7_config) = l7_config {
let tunnel_engine = opa_engine.clone_engine_for_tunnel().unwrap_or_else(|e| {
warn!(error = %e, "Failed to clone OPA engine for L7, falling back to relay-only");
regorus::Engine::new()
});
if let Err(e) = crate::l7::relay::relay_with_inspection(
l7_config,
std::sync::Mutex::new(tunnel_engine),
&mut client,
&mut upstream,
&ctx,
)
.await
{
if is_benign_relay_error(&e) {
debug!(host = %host_lc, port = port, error = %e, "L7 connection closed");
} else {
warn!(host = %host_lc, port = port, error = %e, "L7 relay error");
}
}
} else {
// Plaintext HTTP, no L7 config — relay with credential injection.
if let Err(e) = crate::l7::relay::relay_passthrough_with_credentials(
&mut client,
&mut upstream,
&ctx,
)
.await
{
if is_benign_relay_error(&e) {
debug!(host = %host_lc, port = port, error = %e, "HTTP relay closed");
} else {
warn!(host = %host_lc, port = port, error = %e, "HTTP relay error");
}
}
}
} else {
// Neither TLS nor HTTP — raw binary relay.
debug!(
host = %host_lc,
port = port,
"Non-TLS non-HTTP traffic detected, raw tunnel"
);
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream)
.await
.into_diagnostic()?;
}
Ok(())
}
/// Evaluate OPA policy for a TCP connection with identity binding via /proc/net/tcp.
#[cfg(target_os = "linux")]
fn evaluate_opa_tcp(
peer_addr: SocketAddr,
engine: &OpaEngine,
identity_cache: &BinaryIdentityCache,
entrypoint_pid: &AtomicU32,
host: &str,
port: u16,
) -> ConnectDecision {
use crate::opa::NetworkInput;
use std::sync::atomic::Ordering;
let deny = |reason: String,
binary: Option<PathBuf>,
binary_pid: Option<u32>,
ancestors: Vec<PathBuf>,
cmdline_paths: Vec<PathBuf>|
-> ConnectDecision {
ConnectDecision {
action: NetworkAction::Deny { reason },
binary,
binary_pid,
ancestors,
cmdline_paths,
}
};
let pid = entrypoint_pid.load(Ordering::Acquire);
if pid == 0 {
return deny(
"entrypoint process not yet spawned".into(),
None,
None,
vec![],
vec![],
);
}
let total_start = std::time::Instant::now();
let peer_port = peer_addr.port();
let (bin_path, binary_pid) = match crate::procfs::resolve_tcp_peer_identity(pid, peer_port) {
Ok(r) => r,
Err(e) => {
return deny(
format!("failed to resolve peer binary: {e}"),
None,
None,
vec![],
vec![],
);
}
};
// TOFU verify the immediate binary
let bin_hash = match identity_cache.verify_or_cache(&bin_path) {
Ok(h) => h,
Err(e) => {
return deny(
format!("binary integrity check failed: {e}"),
Some(bin_path),
Some(binary_pid),
vec![],
vec![],
);
}
};
// Walk the process tree upward to collect ancestor binaries
let ancestors = crate::procfs::collect_ancestor_binaries(binary_pid, pid);
for ancestor in &ancestors {
if let Err(e) = identity_cache.verify_or_cache(ancestor) {
return deny(
format!(
"ancestor integrity check failed for {}: {e}",
ancestor.display()
),
Some(bin_path),
Some(binary_pid),
ancestors.clone(),
vec![],
);
}
}
// Collect cmdline paths for script-based binary detection.
let mut exclude = ancestors.clone();
exclude.push(bin_path.clone());
let cmdline_paths = crate::procfs::collect_cmdline_paths(binary_pid, pid, &exclude);
let input = NetworkInput {
host: host.to_string(),
port,
binary_path: bin_path.clone(),
binary_sha256: bin_hash,
ancestors: ancestors.clone(),
cmdline_paths: cmdline_paths.clone(),
};
let result = match engine.evaluate_network_action(&input) {
Ok(action) => ConnectDecision {
action,
binary: Some(bin_path),
binary_pid: Some(binary_pid),
ancestors,
cmdline_paths,
},
Err(e) => deny(
format!("policy evaluation error: {e}"),
Some(bin_path),
Some(binary_pid),
ancestors,
cmdline_paths,
),
};
debug!(
"evaluate_opa_tcp TOTAL: {}ms host={host} port={port}",
total_start.elapsed().as_millis()
);
result
}
/// Non-Linux stub: OPA identity binding requires /proc.
#[cfg(not(target_os = "linux"))]
fn evaluate_opa_tcp(
_peer_addr: SocketAddr,
_engine: &OpaEngine,
_identity_cache: &BinaryIdentityCache,
_entrypoint_pid: &AtomicU32,
_host: &str,
_port: u16,
) -> ConnectDecision {
ConnectDecision {
action: NetworkAction::Deny {
reason: "identity binding unavailable on this platform".into(),
},
binary: None,
binary_pid: None,
ancestors: vec![],
cmdline_paths: vec![],
}
}
/// Maximum buffer size for inference request parsing (10 MiB).
const MAX_INFERENCE_BUF: usize = 10 * 1024 * 1024;
/// Initial buffer size for inference request parsing (64 KiB).
const INITIAL_INFERENCE_BUF: usize = 65536;
/// Handle an intercepted connection for inference routing.
///
/// TLS-terminates the client connection, parses HTTP requests, and executes
/// inference API calls locally via `openshell-router`.
/// Non-inference requests are denied with 403.
///
/// Returns [`InferenceOutcome::Routed`] if at least one request was successfully
/// routed, or [`InferenceOutcome::Denied`] with a reason for all denial cases.
async fn handle_inference_interception(
client: TcpStream,
host: &str,
_port: u16,
tls_state: Option<&Arc<ProxyTlsState>>,
inference_ctx: Option<&Arc<InferenceContext>>,
) -> Result<InferenceOutcome> {
use crate::l7::inference::{ParseResult, format_http_response, try_parse_http_request};
let Some(ctx) = inference_ctx else {
return Ok(InferenceOutcome::Denied {
reason: "cluster inference context not configured".to_string(),
});
};
let Some(tls) = tls_state else {
return Ok(InferenceOutcome::Denied {
reason: "missing TLS state".to_string(),
});
};
// TLS-terminate the client side (present a cert for the target host)
let mut tls_client = match crate::l7::tls::tls_terminate_client(client, tls, host).await {
Ok(c) => c,
Err(e) => {
return Ok(InferenceOutcome::Denied {
reason: format!("TLS handshake failed: {e}"),
});
}
};
// Read and process HTTP requests from the tunnel.
// Track whether any request was successfully routed so that a late denial
// on a keep-alive connection still counts as "routed".
let mut buf = vec![0u8; INITIAL_INFERENCE_BUF];
let mut used = 0usize;
let mut routed_any = false;
loop {
let n = match tls_client.read(&mut buf[used..]).await {
Ok(n) => n,
Err(e) => {
if routed_any {
break;
}
return Ok(InferenceOutcome::Denied {
reason: format!("I/O error: {e}"),
});
}
};
if n == 0 {
if routed_any {
break;
}
return Ok(InferenceOutcome::Denied {
reason: "client closed connection".to_string(),
});
}
used += n;
// Try to parse a complete HTTP request
match try_parse_http_request(&buf[..used]) {
ParseResult::Complete(request, consumed) => {
let was_routed = route_inference_request(&request, ctx, &mut tls_client).await?;
if was_routed {
routed_any = true;
} else if !routed_any {
return Ok(InferenceOutcome::Denied {
reason: "connection not allowed by policy".to_string(),
});
}
// Shift buffer for next request
buf.copy_within(consumed..used, 0);
used -= consumed;
}
ParseResult::Incomplete => {
// Need more data — grow buffer if full
if used == buf.len() {
if buf.len() >= MAX_INFERENCE_BUF {
let response = format_http_response(413, &[], b"Payload Too Large");
write_all(&mut tls_client, &response).await?;
if routed_any {
break;
}
return Ok(InferenceOutcome::Denied {
reason: "payload too large".to_string(),
});
}
buf.resize((buf.len() * 2).min(MAX_INFERENCE_BUF), 0);
}
}
ParseResult::Invalid(reason) => {
warn!(reason = %reason, "rejecting malformed inference request");
let response = format_http_response(400, &[], b"Bad Request");
write_all(&mut tls_client, &response).await?;
return Ok(InferenceOutcome::Denied { reason });
}
}
}
Ok(InferenceOutcome::Routed)
}
/// Route a parsed inference request locally via the sandbox router, or deny it.
///
/// Returns `Ok(true)` if the request was routed to an inference backend,
/// `Ok(false)` if it was denied as a non-inference request.
async fn route_inference_request(
request: &crate::l7::inference::ParsedHttpRequest,
ctx: &InferenceContext,
tls_client: &mut (impl tokio::io::AsyncWrite + Unpin),
) -> Result<bool> {
use crate::l7::inference::{detect_inference_pattern, format_http_response};
let normalized_path = normalize_inference_path(&request.path);
if let Some(pattern) =
detect_inference_pattern(&request.method, &normalized_path, &ctx.patterns)
{