Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

401 changes: 127 additions & 274 deletions README.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion crates/ressrf-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ workspace = true

[features]
default = ["std"]
std = ["prefix-trie", "ipnet"]
std = ["prefix-trie", "ipnet", "regex"]

[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
prefix-trie = { version = "0.8", optional = true }
ipnet = { version = "2", optional = true }
regex = { version = "1", optional = true }

[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
Expand Down
88 changes: 88 additions & 0 deletions crates/ressrf-core/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# ressrf-core

The foundational SSRF prevention engine. Provides CIDR parsing, IP range management, policy evaluation, URI validation, cloud provider modules, and audit event types. This crate is `no_std`-compatible (with `alloc`) when the `std` feature is disabled, making it suitable for WASM targets.

## Features

- **CIDR engine:** parse v4/v6 notation, IPv4-mapped IPv6 normalization, bitwise containment checks, reject octal/hex/zone-ID tricks
- **Default deny list:** IANA special-purpose registries compiled from `config/ip_ranges.json` via `build.rs`
- **Policy engine:** presets (`ExternalOnly`, `InternalOnly`, `None`), custom allow/deny CIDR lists where allow overrides deny, URL rules (glob + regex), header and protocol rules, immutable after build
- **URL rules:** structured allow/deny rules with scheme, host glob (`*` = single label), path glob (`*`/`**`), optional regex (1MB automaton limit, ReDoS-safe), and per-rule `bypass_ip_check`
- **URI validator:** protocol allowlist, IDN-safe domain matching, userinfo bypass resistance, bare IP detection, cloud domain integration
- **Cloud modules:** AWS (IMDS, ECS, IMDSv2 IPv6), Azure (IMDS, Wireserver, sovereign domains), GCP (metadata, internal DNS). Constants generated from `config/domains_*.json` at build time.
- **Service range trie** (std only): `ServiceRangeTable` backed by `prefix-trie` for O(log n) longest-prefix-match lookups against cloud service IP ranges
- **Audit types:** `AuditEvent` enum with 5 variants, `AuditSink` trait, zero overhead when unused

## Feature Flags

| Feature | Default | Description |
|---------|---------|-------------|
| `std` | yes | Enables `ServiceRangeTable`, `prefix-trie`, `ipnet`, `regex`, and `std::error::Error` impl |

Without `std`, the crate uses `#![no_std]` with `alloc` for WASM and embedded targets.

## Usage

```rust
use ressrf_core::{PolicyBuilder, Preset, UriValidator};

// Create a policy that blocks internal/metadata ranges
let mut builder = PolicyBuilder::external_only();
builder.add_allowed(&["10.42.0.0/16"]); // permit a known internal service
let policy = builder.build();

// Validate IPs
assert!(policy.is_network_allowed(&["93.184.216.34".parse().unwrap()]).is_ok());
assert!(policy.is_network_allowed(&["169.254.169.254".parse().unwrap()]).is_err());

// Validate URLs
let validator = UriValidator::default();
assert!(validator.validate_url("https://example.com", Some(&policy)).is_ok());
```

## Cloud Providers

```rust
use ressrf_core::PolicyBuilder;

let policy = PolicyBuilder::external_only()
.with_cloud("aws")
.with_cloud("azure")
.with_cloud("gcp")
.build();
```

## URL Rules

```rust
use ressrf_core::{PolicyBuilder, UrlRule};

let mut builder = PolicyBuilder::external_only();
builder
.url_allow(UrlRule::glob("https", "*.stripe.com", "/v1/**"))
.url_allow(UrlRule::host("internal-api.company.com").bypass_ip_check())
.url_deny(UrlRule::host("*.internal"))
.url_deny(UrlRule::regex(r"^http://.*$"));
let policy = builder.build();

// Matching allow rule
assert!(policy.validate_url_rules("https://api.stripe.com/v1/charges").is_ok());

// Blocked by deny rule
assert!(policy.validate_url_rules("https://db.internal/query").is_err());
```

## Service Range Lookups

```rust
use ressrf_core::ServiceRangeTable;

let table = ServiceRangeTable::load_all("crates/ressrf-core/config")?;
if let Some(info) = table.lookup("52.94.76.0".parse().unwrap()) {
println!("{} / {}", info.provider, info.service);
}
```

## License

MIT
8 changes: 8 additions & 0 deletions crates/ressrf-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ pub enum DenyReason {
ProtocolNotAllowed { protocol: String },
PlaintextHttpDenied,

// URL rules
UrlRuleDenied { url: String },
UrlRuleNotInAllowList { url: String },

// Catch-all
ExplicitDenyList { cidr: String },
PolicyImmutabilityViolation,
Expand Down Expand Up @@ -168,6 +172,10 @@ impl fmt::Display for DenyReason {
write!(f, "protocol not allowed: {protocol}")
}
Self::PlaintextHttpDenied => write!(f, "plaintext HTTP denied"),
Self::UrlRuleDenied { url } => write!(f, "URL denied by rule: {url}"),
Self::UrlRuleNotInAllowList { url } => {
write!(f, "URL not in allow list: {url}")
}
Self::ExplicitDenyList { cidr } => write!(f, "in explicit deny list: {cidr}"),
Self::PolicyImmutabilityViolation => {
write!(f, "policy mutation after finalization")
Expand Down
2 changes: 2 additions & 0 deletions crates/ressrf-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod policy;
#[cfg(feature = "std")]
pub mod service_ranges;
pub mod uri_validator;
pub mod url_rules;

pub use audit::{AuditEvent, AuditSink};
pub use cidr::Cidr;
Expand All @@ -20,3 +21,4 @@ pub use policy::{Policy, PolicyBuilder, Preset};
#[cfg(feature = "std")]
pub use service_ranges::ServiceRangeTable;
pub use uri_validator::UriValidator;
pub use url_rules::{UrlRule, UrlRuleDecision, UrlRuleset};
110 changes: 105 additions & 5 deletions crates/ressrf-core/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::audit::{AuditEvent, AuditSink};
use crate::cidr::{Cidr, CidrSet};
use crate::error::{DataTier, DenyReason, Error};
use crate::ip_ranges;
use crate::url_rules::{UrlRule, UrlRuleDecision, UrlRuleset};

/// Policy presets that determine default allow/deny behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -52,6 +53,7 @@ pub struct PolicyBuilder {
protocol_rules: ProtocolRules,
cloud_modules: Vec<String>,
audit_sink: Option<Box<dyn AuditSink>>,
url_ruleset: UrlRuleset,
#[cfg(feature = "std")]
service_ranges: Option<crate::service_ranges::ServiceRangeTable>,
}
Expand All @@ -78,6 +80,7 @@ impl PolicyBuilder {
protocol_rules: ProtocolRules::default(),
cloud_modules: Vec::new(),
audit_sink: None,
url_ruleset: UrlRuleset::new(),
#[cfg(feature = "std")]
service_ranges: None,
}
Expand Down Expand Up @@ -159,6 +162,24 @@ impl PolicyBuilder {
self
}

/// Add a URL allow rule.
pub fn url_allow(&mut self, rule: UrlRule) -> &mut Self {
self.url_ruleset.add_allow(rule);
self
}

/// Add a URL deny rule.
pub fn url_deny(&mut self, rule: UrlRule) -> &mut Self {
self.url_ruleset.add_deny(rule);
self
}

/// Set the entire URL ruleset (used by WASM config deserialization).
pub fn url_ruleset(&mut self, ruleset: UrlRuleset) -> &mut Self {
self.url_ruleset = ruleset;
self
}

/// Attach a [`ServiceRangeTable`](crate::service_ranges::ServiceRangeTable)
/// for optional allow-listing decisions based on cloud service IP ranges.
///
Expand All @@ -174,18 +195,26 @@ impl PolicyBuilder {
}

/// Build the immutable policy. After this, no further modifications are possible.
///
/// # Panics
///
/// Panics if a URL rule contains an invalid regex pattern (use `try_build` for
/// fallible construction).
pub fn build(mut self) -> Policy {
// Load default deny set for ExternalOnly preset.
// InternalOnly does not need it since it only checks the allow list,
// but we still load it so that future features (e.g. audit-only deny reporting)
// have the data available without a breaking change.
if self.preset == Preset::ExternalOnly {
let defaults = ip_ranges::default_deny_set();
for cidr in defaults {
self.deny_set.add(cidr);
}
}

#[cfg(feature = "std")]
if !self.url_ruleset.is_empty() {
self.url_ruleset
.compile()
.expect("URL rule regex compilation failed");
}

let deny_count = self.deny_set.len();
let allow_count = self.allow_set.len();

Expand All @@ -197,11 +226,11 @@ impl PolicyBuilder {
protocol_rules: self.protocol_rules,
cloud_modules: self.cloud_modules.clone(),
audit_sink: self.audit_sink,
url_ruleset: self.url_ruleset,
#[cfg(feature = "std")]
service_ranges: self.service_ranges,
};

// Emit PolicyCreated audit event
policy.emit_audit(&AuditEvent::PolicyCreated {
preset: alloc::format!("{:?}", self.preset),
cloud_modules: self.cloud_modules,
Expand All @@ -211,6 +240,46 @@ impl PolicyBuilder {

policy
}

/// Build the policy, returning an error if URL rule regex compilation fails.
pub fn try_build(mut self) -> crate::Result<Policy> {
if self.preset == Preset::ExternalOnly {
let defaults = ip_ranges::default_deny_set();
for cidr in defaults {
self.deny_set.add(cidr);
}
}

#[cfg(feature = "std")]
if !self.url_ruleset.is_empty() {
self.url_ruleset.compile()?;
}

let deny_count = self.deny_set.len();
let allow_count = self.allow_set.len();

let policy = Policy {
preset: self.preset,
deny_set: self.deny_set,
allow_set: self.allow_set,
header_rules: self.header_rules,
protocol_rules: self.protocol_rules,
cloud_modules: self.cloud_modules.clone(),
audit_sink: self.audit_sink,
url_ruleset: self.url_ruleset,
#[cfg(feature = "std")]
service_ranges: self.service_ranges,
};

policy.emit_audit(&AuditEvent::PolicyCreated {
preset: alloc::format!("{:?}", self.preset),
cloud_modules: self.cloud_modules,
deny_count,
allow_count,
});

Ok(policy)
}
}

/// An immutable, finalized policy. All validation calls go through this.
Expand All @@ -222,6 +291,7 @@ pub struct Policy {
protocol_rules: ProtocolRules,
cloud_modules: Vec<String>,
audit_sink: Option<Box<dyn AuditSink>>,
url_ruleset: UrlRuleset,
#[cfg(feature = "std")]
service_ranges: Option<crate::service_ranges::ServiceRangeTable>,
}
Expand Down Expand Up @@ -355,6 +425,36 @@ impl Policy {
&self.protocol_rules
}

/// Evaluate URL rules against the given URL.
///
/// Returns `Ok(true)` if the URL was allowed and IP check should be bypassed.
/// Returns `Ok(false)` if the URL was allowed (or no rules configured) and IP check should proceed.
/// Returns `Err` if the URL was denied by a rule.
pub fn validate_url_rules(&self, url: &str) -> crate::Result<bool> {
if self.url_ruleset.is_empty() {
return Ok(false);
}

match self.url_ruleset.evaluate(url) {
UrlRuleDecision::Denied => Err(Error::Blocked(DenyReason::UrlRuleDenied {
url: String::from(url),
})),
UrlRuleDecision::AllowedBypassIp => Ok(true),
UrlRuleDecision::Allowed | UrlRuleDecision::NoMatch => Ok(false),
}
}

/// Combined validation: check URL rules, then optionally check IP rules.
/// This is the primary entry point for request validation when both URL and
/// IP-level checks are needed.
pub fn is_request_allowed(&self, url: &str, ips: &[IpAddr]) -> crate::Result<()> {
let bypass_ip = self.validate_url_rules(url)?;
if bypass_ip {
return Ok(());
}
self.is_network_allowed(ips)
}

/// Look up which cloud service owns an IP address, if a
/// [`ServiceRangeTable`](crate::service_ranges::ServiceRangeTable) was attached.
///
Expand Down
Loading
Loading