Skip to content

Commit 7cfa0c0

Browse files
authored
fix(network): require explicit grants for private IP literals (#5522)
* test(network): cover private literal destination grants Signed-off-by: Adrien Langou <alangou@nvidia.com> * fix(network): require explicit grants for private IP literals Signed-off-by: Adrien Langou <alangou@nvidia.com> --------- Signed-off-by: Adrien Langou <alangou@nvidia.com>
1 parent 5d9a9cd commit 7cfa0c0

4 files changed

Lines changed: 296 additions & 14 deletions

File tree

‎crates/openshell-supervisor-network/src/policy_dns/mod.rs‎

Lines changed: 104 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ pub(crate) use store::{
3333
};
3434

3535
use crate::opa::OpaEngine;
36-
use crate::proxy::destination::{build_validation_plan, filter_resolved_addresses};
36+
use crate::proxy::destination::{
37+
DestinationDenialKind, build_validation_plan, filter_resolved_addresses,
38+
};
3739
use crate::proxy::is_host_gateway_alias;
3840
use crate::telemetry::egress_emit;
3941
use openshell_core::host_pattern::HostSelector;
@@ -378,15 +380,18 @@ fn eligible_endpoints(
378380
&& pattern == name.as_str()
379381
&& value_field(&endpoint.endpoint, "advisor_proposed")
380382
!= Some(&regorus::Value::Bool(true));
381-
let destination_plan = build_validation_plan(
383+
let destination_plan = match build_validation_plan(
382384
name.as_str(),
383385
name.as_str(),
384386
trusted_host_gateway,
385387
None,
386388
&raw_allowed_ips,
387389
exact_declared_host,
388-
)
389-
.map_err(|error| PolicyDnsError::Policy(error.reason))?;
390+
) {
391+
Ok(plan) => plan,
392+
Err(error) if error.kind == DestinationDenialKind::InternalAddress => continue,
393+
Err(error) => return Err(PolicyDnsError::Policy(error.reason)),
394+
};
390395
eligible.push(EligibleEndpoint {
391396
endpoint_id: PolicyEndpointId {
392397
policy_name: endpoint.policy_name.clone(),
@@ -1131,6 +1136,101 @@ process: { run_as_user: sandbox, run_as_group: sandbox }
11311136
assert!(matches!(result, Err(PolicyDnsError::NoValidAddress)));
11321137
}
11331138

1139+
#[tokio::test]
1140+
async fn numeric_private_name_keeps_only_the_exact_endpoint_contract() {
1141+
let wildcard = " - { host: '**.*.*', port: 443, protocol: tcp }";
1142+
let exact = " - { host: 10.2.3.4, port: 8443, protocol: tcp }";
1143+
for endpoints in [
1144+
format!("{wildcard}\n{exact}"),
1145+
format!("{exact}\n{wildcard}"),
1146+
] {
1147+
let yaml = BASE_POLICY.replace(
1148+
" - { host: db.example, port: 5432, protocol: tcp }",
1149+
&endpoints,
1150+
);
1151+
let ip = "10.2.3.4".parse::<IpAddr>().unwrap();
1152+
let service = service(&yaml, vec![ip]);
1153+
let now = Instant::now();
1154+
let answer = service
1155+
.answer_query("10.2.3.4.", AddressFamily::Ipv4, now)
1156+
.await
1157+
.expect("the exact endpoint must retain its private address grant");
1158+
let mapping = service
1159+
.store
1160+
.lookup(answer.address, 8443, answer.policy_generation, now)
1161+
.unwrap();
1162+
assert_eq!(mapping.record.contracts.len(), 1);
1163+
assert_eq!(mapping.record.contracts[0].pinned_addresses, [ip]);
1164+
assert!(matches!(
1165+
service
1166+
.store
1167+
.lookup(answer.address, 443, answer.policy_generation, now),
1168+
Err(MappingLookupError::PortMismatch)
1169+
));
1170+
}
1171+
}
1172+
1173+
#[tokio::test]
1174+
async fn wildcard_numeric_private_name_has_no_egress_contract() {
1175+
let yaml = BASE_POLICY.replace("db.example", "'**.*.*'");
1176+
for address in ["10.2.3.4", "8.8.8.8"] {
1177+
let service = service(&yaml, vec![address.parse().unwrap()]);
1178+
let now = Instant::now();
1179+
let answer = service
1180+
.answer_query("10.2.3.4.", AddressFamily::Ipv4, now)
1181+
.await
1182+
.expect("an ineligible numeric name can only stage an observation");
1183+
assert!(matches!(
1184+
service
1185+
.store
1186+
.lookup(answer.address, 5432, answer.policy_generation, now),
1187+
Err(MappingLookupError::PortMismatch)
1188+
));
1189+
let intent = service
1190+
.store
1191+
.lookup_intent(answer.address, 5432, answer.policy_generation, now)
1192+
.unwrap();
1193+
assert!(intent.record.is_observation());
1194+
assert_eq!(service.resolver.calls.load(Ordering::SeqCst), 0);
1195+
}
1196+
}
1197+
1198+
#[tokio::test]
1199+
async fn numeric_public_name_keeps_literal_address_and_control_plane_port_checks() {
1200+
for (port, address) in [(5432, "1.1.1.1"), (6443, "8.8.8.8")] {
1201+
let yaml = BASE_POLICY
1202+
.replace("db.example", "'**.*.*'")
1203+
.replace("port: 5432", &format!("port: {port}"));
1204+
let service = service(&yaml, vec![address.parse().unwrap()]);
1205+
assert!(matches!(
1206+
service
1207+
.answer_query("8.8.8.8.", AddressFamily::Ipv4, Instant::now())
1208+
.await,
1209+
Err(PolicyDnsError::NoValidAddress)
1210+
));
1211+
}
1212+
}
1213+
1214+
#[test]
1215+
fn malformed_allowed_ips_remains_a_policy_error() {
1216+
let endpoints = [crate::opa::MatchedEndpoint {
1217+
policy_name: "database".to_string(),
1218+
endpoint_index: 0,
1219+
endpoint: regorus::Value::from_json_str(
1220+
r#"{"host":"db.example","ports":[5432],"allowed_ips":["not-an-ip"]}"#,
1221+
)
1222+
.unwrap(),
1223+
}];
1224+
assert!(matches!(
1225+
eligible_endpoints(
1226+
&endpoints,
1227+
&NormalizedName::parse("db.example").unwrap(),
1228+
None
1229+
),
1230+
Err(PolicyDnsError::Policy(_))
1231+
));
1232+
}
1233+
11341234
#[tokio::test]
11351235
async fn advisor_endpoints_filter_private_answers_without_losing_public_or_explicit_ips() {
11361236
for protocol in [

‎crates/openshell-supervisor-network/src/proxy.rs‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4244,14 +4244,6 @@ fn query_endpoint_credential_guard(
42444244
})
42454245
}
42464246

4247-
/// When the policy endpoint host is a literal IP address, the user has
4248-
/// explicitly declared intent to allow that destination. Synthesize an
4249-
/// `allowed_ips` entry so the existing allowlist-validation path is used
4250-
/// instead of the blanket internal-IP rejection.
4251-
///
4252-
/// Always-blocked addresses (loopback, link-local, unspecified) are skipped
4253-
/// — synthesizing an `allowed_ips` entry for them would be silently
4254-
/// un-enforceable at runtime.
42554247
fn implicit_allowed_ips_for_ip_host(host: &str) -> Vec<String> {
42564248
let lookup_host = normalize_host_lookup_key(host);
42574249
if let Ok(ip) = lookup_host.parse::<IpAddr>() {
@@ -6349,8 +6341,6 @@ async fn handle_forward_proxy(
63496341
// - If the endpoint is an exact declared hostname: allow private IPs,
63506342
// but still reject always-blocked addresses and control-plane ports.
63516343
// - Otherwise: reject internal IPs, allow public IPs through.
6352-
// When the policy host is already a literal IP address, treat it as
6353-
// implicitly allowed — the user explicitly declared the destination.
63546344
match hydrate_destination_plan(&mut decision, *backend_host_gateway, *trusted_host_gateway) {
63556345
Ok(()) => {}
63566346
Err(denial) => {
@@ -7331,6 +7321,7 @@ fn is_benign_relay_error(err: &miette::Report) -> bool {
73317321
reason = "Test code: test fixtures and explicit control-flow markers are idiomatic in tests."
73327322
)]
73337323
mod tests {
7324+
mod destination_policy;
73347325
mod ipv4_mapped;
73357326

73367327
#[test]

‎crates/openshell-supervisor-network/src/proxy/destination.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,14 @@ pub(crate) fn build_validation_plan(
114114
.first()
115115
.and_then(|raw| raw.parse::<IpAddr>().ok())
116116
{
117+
if is_internal_ip(ip) && !exact_declared_endpoint_host {
118+
return Err(DestinationDenial::new(
119+
DestinationDenialKind::InternalAddress,
120+
format!(
121+
"{host} is an internal IP literal without an exact declared endpoint or allowed_ips"
122+
),
123+
));
124+
}
117125
AddressAuthorization::ImplicitIpLiteral(ip)
118126
} else if exact_declared_endpoint_host {
119127
AddressAuthorization::ExactDeclaredHost
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
use super::*;
5+
6+
fn authorize_destination(
7+
declared_host: &str,
8+
host: &str,
9+
port: u16,
10+
allowed_ips: &[&str],
11+
) -> EgressDecision {
12+
let policy = serde_json::json!({
13+
"network_policies": {
14+
"egress": {
15+
"name": "egress",
16+
"endpoints": [{
17+
"host": declared_host,
18+
"port": port,
19+
"tls": "skip",
20+
"allowed_ips": allowed_ips,
21+
}],
22+
"binaries": [{ "path": "/usr/bin/curl" }],
23+
},
24+
},
25+
});
26+
let engine = native_identity_engine(
27+
include_str!("../../../data/sandbox-policy.rego"),
28+
&policy.to_string(),
29+
)
30+
.expect("load destination policy");
31+
let (open, _completion) = staged_curl_open(
32+
"10.23.45.67:443".parse().unwrap(),
33+
engine.current_generation(),
34+
);
35+
let decision = authorize_supplied_identity(
36+
&engine,
37+
&BinaryIdentityCache::new(),
38+
EgressIntent::connect(host.to_string(), port),
39+
&open.binary_identity,
40+
);
41+
assert!(matches!(decision.action, NetworkAction::Allow { .. }));
42+
assert_eq!(decision.endpoint.exact_declared_host, declared_host == host);
43+
assert_eq!(
44+
query_allowed_ips(&decision),
45+
allowed_ips
46+
.iter()
47+
.map(ToString::to_string)
48+
.collect::<Vec<_>>()
49+
);
50+
decision
51+
}
52+
53+
fn accepted_addresses(
54+
decision: &mut EgressDecision,
55+
ip: IpAddr,
56+
) -> std::result::Result<Vec<IpAddr>, DestinationDenial> {
57+
hydrate_destination_plan(decision, None, None)?;
58+
filter_resolved_addresses(
59+
decision.endpoint.destination.as_ref().unwrap(),
60+
&decision.intent.destination.host,
61+
decision.intent.destination.port,
62+
&[ip],
63+
)
64+
}
65+
66+
#[test]
67+
fn glob_requires_grant_for_private_literal() {
68+
let glob = "**.*.*";
69+
let host = "10.23.45.67";
70+
let mut decision = authorize_destination(glob, host, 443, &[]);
71+
let result = accepted_addresses(&mut decision, host.parse().unwrap());
72+
assert!(
73+
result.is_err(),
74+
"glob {glob} without allowed_ips admitted private literal {host}: {result:?}"
75+
);
76+
assert_eq!(
77+
result.unwrap_err().kind,
78+
DestinationDenialKind::InternalAddress
79+
);
80+
}
81+
82+
#[test]
83+
fn planner_requires_grant_for_private_ipv6_literals() {
84+
for (host, ip) in [
85+
("fd00::1234", "fd00::1234"),
86+
("[fd00::1234]", "fd00::1234"),
87+
("::ffff:10.23.45.67", "::ffff:10.23.45.67"),
88+
] {
89+
let ip = ip.parse().unwrap();
90+
let result = build_validation_plan(host, host, None, None, &[], false)
91+
.and_then(|plan| filter_resolved_addresses(&plan, host, 443, &[ip]));
92+
assert!(
93+
result.is_err(),
94+
"planner admitted private literal {host} without an explicit grant: {result:?}"
95+
);
96+
assert_eq!(
97+
result.unwrap_err().kind,
98+
DestinationDenialKind::InternalAddress
99+
);
100+
}
101+
}
102+
103+
#[test]
104+
fn glob_hostname_still_rejects_private_resolution() {
105+
let mut decision = authorize_destination("**.*.*", "fixture.example.test", 443, &[]);
106+
let denial = accepted_addresses(&mut decision, "10.23.45.67".parse().unwrap())
107+
.expect_err("a glob hostname must not admit private resolved addresses");
108+
assert_eq!(denial.kind, DestinationDenialKind::InternalAddress);
109+
}
110+
111+
#[test]
112+
fn preserves_explicit_private_grants_and_public_targets() {
113+
let private_allowlist: &[&str] = &["10.23.45.0/24"];
114+
let no_allowlist: &[&str] = &[];
115+
for (declared_host, host, allowed_ips, ip) in [
116+
("10.23.45.67", "10.23.45.67", no_allowlist, "10.23.45.67"),
117+
(
118+
"fixture.example.test",
119+
"fixture.example.test",
120+
no_allowlist,
121+
"10.23.45.67",
122+
),
123+
("**.*.*", "10.23.45.67", private_allowlist, "10.23.45.67"),
124+
(
125+
"**.*.*",
126+
"fixture.example.test",
127+
private_allowlist,
128+
"10.23.45.67",
129+
),
130+
("**.*.*", "8.8.8.8", no_allowlist, "8.8.8.8"),
131+
("**.*.*", "fixture.example.test", no_allowlist, "8.8.8.8"),
132+
] {
133+
let ip: IpAddr = ip.parse().unwrap();
134+
let mut decision = authorize_destination(declared_host, host, 443, allowed_ips);
135+
assert_eq!(
136+
accepted_addresses(&mut decision, ip).unwrap(),
137+
vec![ip],
138+
"{declared_host} must retain its grant for {host}"
139+
);
140+
}
141+
}
142+
143+
#[test]
144+
fn explicit_allowlist_constrains_exact_and_glob_hosts() {
145+
for declared_host in ["10.23.45.67", "**.*.*"] {
146+
let mut decision =
147+
authorize_destination(declared_host, "10.23.45.67", 443, &["8.8.8.8/32"]);
148+
let denial = accepted_addresses(&mut decision, "10.23.45.67".parse().unwrap())
149+
.expect_err("an explicit allowlist must constrain the requested IP literal");
150+
assert_eq!(denial.kind, DestinationDenialKind::AllowedIps);
151+
}
152+
}
153+
154+
#[test]
155+
fn public_literal_keeps_control_plane_port_block() {
156+
let mut decision = authorize_destination("**.*.*", "8.8.8.8", 6443, &[]);
157+
accepted_addresses(&mut decision, "8.8.8.8".parse().unwrap())
158+
.expect_err("a glob-authorized public IP literal must retain the port 6443 block");
159+
}
160+
161+
#[test]
162+
fn private_grants_keep_hard_address_and_port_blocks() {
163+
for ip in [
164+
"127.0.0.1",
165+
"169.254.169.254",
166+
"0.0.0.0",
167+
"::1",
168+
"fe80::1",
169+
"::",
170+
] {
171+
let mut decision =
172+
authorize_destination("fixture.example.test", "fixture.example.test", 443, &[]);
173+
accepted_addresses(&mut decision, ip.parse().unwrap())
174+
.expect_err("exact hostname declarations must reject always-blocked addresses");
175+
}
176+
for (declared_host, allowed_ips) in
177+
[("10.23.45.67", &[][..]), ("**.*.*", &["10.23.45.0/24"][..])]
178+
{
179+
let mut decision = authorize_destination(declared_host, "10.23.45.67", 6443, allowed_ips);
180+
accepted_addresses(&mut decision, "10.23.45.67".parse().unwrap())
181+
.expect_err("private grants must retain the port 6443 block");
182+
}
183+
}

0 commit comments

Comments
 (0)