diff --git a/.cargo/audit.toml b/.cargo/audit.toml index 612847a..ec37f42 100644 --- a/.cargo/audit.toml +++ b/.cargo/audit.toml @@ -5,7 +5,7 @@ ignore = [ # RUSTSEC-2026-0459: libsqlite3-sys 0.37.0 (C SQLite CVE-2026-119375), fixed in >= 0.39.0. # https://rustsec.org/advisories/RUSTSEC-2026-0459 - tracked in https://github.com/ilanh/openshell-annotate/issues/76 - # Transitive and not upgradable from this repo: OpenShell v0.1.7 and v0.1.8 openshell-crypto -> sqlx 0.9.0 -> sqlx-sqlite =0.9.0 + # Transitive and not upgradable from this repo: OpenShell v0.1.7 to v0.1.9 openshell-crypto -> sqlx 0.9.0 -> sqlx-sqlite =0.9.0 # (exact pin) -> libsqlite3-sys 0.37.0. openshell-annotate does not use SQLite itself. # Remove this entry once an OpenShell release bumps sqlx/libsqlite3-sys and we move the pin to it. "RUSTSEC-2026-0459", diff --git a/AGENTS.md b/AGENTS.md index 96420cd..8b8aeb2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ subprocesses; add directives with reasons; run `scan`, `generate`, `lint`, `drif ## When changing this tool - Build/test: `cargo build && cargo test` (Rust 1.94+). The schema crate is a git dependency pinned to the - OpenShell `v0.1.8` tag (see `Cargo.toml`, `Cargo.lock` pins the commit). Update the tag deliberately and re-run + OpenShell `v0.1.9` tag (see `Cargo.toml`, `Cargo.lock` pins the commit). Update the tag deliberately and re-run the golden tests. `openshell-next` builds against the newest upstream tag, prereleases included, and is moved by `.github/workflows/openshell-next.yml`; fixes that need the newer OpenShell go there, fixes valid on the current pin go to `main` (see `docs/DEVELOPING.md`, "Tracking the next OpenShell release"). diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f73bd1..a9307b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ version section and adds the squash-merged PR titles since the previous tag. Ver ## [Unreleased] +- chore(deps): build against OpenShell v0.1.9 (`openshell-policy-schema`, `openshell-policy`, commit ce58cf8); docs, generated policy headers and the `diff-logs`/`--image` notes now name v0.1.9 (#107) +- feat(lint): warn when a wildcard host in an `egress` directive or a `--policy` endpoint without `allowed_ips` can match a private IP literal (`10.*.*.*`, `**.*.*`): since OpenShell v0.1.9 a wildcard endpoint no longer allows private IP literals on its own (#107) +- test: the gateway validator rejects middleware selectors with a port (OpenShell v0.1.9); `diff-logs` skips gateway API Activity denials in both the old (`type_uid` 600399) and the new Create/Update/Delete shape (#107) - chore(deps): update `url` to 2.5.9 (and `form_urlencoded` to 1.2.3) in `Cargo.lock` for RUSTSEC-2026-0592, a stack overflow in `Url::origin()` on nested `blob:` URLs; `url` comes in through OpenShell's crates (#111) - chore(deps): OpenShell moved to `ai-openshell/openshell`: the git dependencies, `Cargo.lock` sources (same v0.1.8 commit), `deny.toml` `allow-git`, the pin/tag/compat/openshell-next scripts and workflows, and upstream links in the docs use the new URL instead of the `NVIDIA/OpenShell` redirect (#105) - ci: the `Security` checks `actionlint`, `gitleaks`, `cargo-deny` and `openshell-pin` are required status checks on `main`, next to `check` and `audit` (`protect-main` ruleset, #103) diff --git a/Cargo.lock b/Cargo.lock index 3ee8415..50b974a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2111,7 +2111,7 @@ dependencies = [ [[package]] name = "openshell-core" version = "0.0.0" -source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.8#f3d976590d3eb1379690a2abaf0f0e26c21d487d" +source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.9#ce58cf8e9b953281352d98a637e41616295b1318" dependencies = [ "async-trait", "base64 0.22.1", @@ -2146,7 +2146,7 @@ dependencies = [ [[package]] name = "openshell-crypto" version = "0.0.0" -source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.8#f3d976590d3eb1379690a2abaf0f0e26c21d487d" +source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.9#ce58cf8e9b953281352d98a637e41616295b1318" dependencies = [ "aws-lc-rs", "jsonwebtoken", @@ -2164,7 +2164,7 @@ dependencies = [ [[package]] name = "openshell-extension-core" version = "0.0.0" -source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.8#f3d976590d3eb1379690a2abaf0f0e26c21d487d" +source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.9#ce58cf8e9b953281352d98a637e41616295b1318" dependencies = [ "hyper-util", "serde", @@ -2177,7 +2177,7 @@ dependencies = [ [[package]] name = "openshell-policy" version = "0.0.0" -source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.8#f3d976590d3eb1379690a2abaf0f0e26c21d487d" +source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.9#ce58cf8e9b953281352d98a637e41616295b1318" dependencies = [ "hickory-proto", "miette", @@ -2191,7 +2191,7 @@ dependencies = [ [[package]] name = "openshell-policy-schema" version = "0.0.0" -source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.8#f3d976590d3eb1379690a2abaf0f0e26c21d487d" +source = "git+https://github.com/ai-openshell/openshell?tag=v0.1.9#ce58cf8e9b953281352d98a637e41616295b1318" dependencies = [ "miette", "noyalib", diff --git a/Cargo.toml b/Cargo.toml index 7d1b80c..35a3e81 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,10 +10,10 @@ repository = "https://github.com/ilanh/openshell-annotate" authors = ["Ilan Harel"] [dependencies] -# Pinned to the OpenShell v0.1.8 tag; Cargo.lock records the exact commit. -openshell-policy-schema = { git = "https://github.com/ai-openshell/openshell", tag = "v0.1.8" } +# Pinned to the OpenShell v0.1.9 tag; Cargo.lock records the exact commit. +openshell-policy-schema = { git = "https://github.com/ai-openshell/openshell", tag = "v0.1.9" } # Same tag. Schema parsing accepts policies the gateway later rejects; this crate is that validator. -openshell-policy = { git = "https://github.com/ai-openshell/openshell", tag = "v0.1.8" } +openshell-policy = { git = "https://github.com/ai-openshell/openshell", tag = "v0.1.9" } anyhow = "1" clap = { version = "4", features = ["derive"] } ignore = "0.4" diff --git a/Dockerfile b/Dockerfile index ababfbe..b717113 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ # syntax=docker/dockerfile:1.7 # Build: scripts/docker-build.sh (or: docker build -t openshell-annotate:dev .) # -# `openshell-policy-schema` is a git dependency on https://github.com/ai-openshell/openshell (tag v0.1.8, commit pinned +# `openshell-policy-schema` is a git dependency on https://github.com/ai-openshell/openshell (tag v0.1.9, commit pinned # in Cargo.lock), fetched by cargo during the build, so no local OpenShell checkout is needed. FROM rust:1.94-bookworm AS build WORKDIR /build diff --git a/README.md b/README.md index 24ef48a..be6867e 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ un-annotated calls, and gates CI on drift. > **Independent community project.** openshell-annotate is not affiliated with, endorsed by, or sponsored by > NVIDIA. It uses NVIDIA OpenShell's public policy schema crate (Apache-2.0) to validate what it generates. -Early pre-release **v0.1.0-rc.3** (targets OpenShell policy schema v1, `openshell-policy-schema` @ v0.1.8). +Early pre-release **v0.1.0-rc.3** (targets OpenShell policy schema v1, `openshell-policy-schema` @ v0.1.9). Licensed under Apache-2.0. ## Try it in two minutes @@ -136,7 +136,7 @@ stderr. Exit codes and `--deny-warnings` do not depend on the format. ### Files the image keeps outside OpenShell's baseline (`generate --image`) -OpenShell 0.1.8 only lets the sandbox read `/usr /lib /etc /app /var/log /proc /dev/urandom` (plus the workspace when +OpenShell 0.1.9 only lets the sandbox read `/usr /lib /etc /app /var/log /proc /dev/urandom` (plus the workspace when `include_workdir` is on) once a `filesystem_policy` exists, and it does not log filesystem denials ([ai-openshell/openshell#4270](https://github.com/ai-openshell/openshell/issues/4270)), so an application under `/opt/` fails with a bare `EACCES`. `generate --image IMAGE` inspects the image (docker, then podman: WORKDIR, ENTRYPOINT, CMD, and the directory @@ -355,8 +355,14 @@ the rule; a profile bound to other binaries (the bundled `github` profile is for (it is evaluated as IPv4, ai-openshell/openshell#5101). A WebSocket client with a computed URL or behind an SDK is not seen. Filesystem policy paths that go through a symlink inside a writable directory now fail sandbox launch (ai-openshell/openshell#5278); the symlink lives in the image, so lint cannot see it: put the symlink's target in `@openshell fs`. +- OpenShell v0.1.9 changes: a wildcard endpoint no longer allows a private IP literal (RFC 1918, CGNAT, TEST-NET and + similar) on its own (ai-openshell/openshell#5522), so lint warns when a wildcard host in a directive or a `--policy` file + can match one (`10.*.*.*`, `**.*.*`); declare each private address as its own endpoint, or give the policy endpoint + `allowed_ips`. Middleware selectors (`network_middlewares.*.endpoints`) can no longer include a port + (ai-openshell/openshell#4359); annotate does not generate middlewares, but `lint --policy`, `drift` and `generate` run + the gateway validator on committed policies and report it. - Filesystem/process/landlock are startup-only in OpenShell; drift labels them `startup`. -- `diff-logs` only sees network and L7 events: OpenShell 0.1.8 does not log Landlock/filesystem denials (upstream #4270), log +- `diff-logs` only sees network and L7 events: OpenShell 0.1.9 does not log Landlock/filesystem denials (upstream #4270), log delivery is batched and best-effort (wait a few seconds after the workload; absence of an event is not proof), and `NET:REFUSE` lines carry no binary. A helper spawned by an allowed binary (git -> git-remote-http) is matched through its parent. - Semantic checks mirror `openshell-policy::validate_sandbox_policy` (documented rules) but the authoritative diff --git a/ROADMAP.md b/ROADMAP.md index 175e5ae..e8a6fbd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -18,7 +18,7 @@ Order matters: each milestone builds on the previous one. Nothing is published ( ## 2. Docker image (publish) - **Scope:** small runtime image with the binary (tree-sitter grammars compiled in; distroless/cc base, 34.9 MB), entrypoint `openshell-annotate`, workdir `/src`. - **Deliverables:** multi-stage `Dockerfile`, `scripts/docker-build.sh` (local tag `openshell-annotate:dev`, no OpenShell checkout needed), then, after approval, a publish workflow to a registry (ghcr.io) with version tags. -- **Depends on:** a public home for the repo (the `openshell-policy-schema` dependency now resolves from the public OpenShell repo at tag v0.1.8, so the build is portable). Publishing to a registry needs the maintainer's approval. +- **Depends on:** a public home for the repo (the `openshell-policy-schema` dependency now resolves from the public OpenShell repo at tag v0.1.9, so the build is portable). Publishing to a registry needs the maintainer's approval. ## 3. GitHub Action + GitLab CI template - **Scope:** run `lint --deny-warnings` and `drift --policy openshell/policy.yaml` on every pull/merge request; fail with annotations. diff --git a/docs/DEVELOPING.md b/docs/DEVELOPING.md index 01ec5f7..727b65b 100644 --- a/docs/DEVELOPING.md +++ b/docs/DEVELOPING.md @@ -8,10 +8,10 @@ build that downloads crates takes longer. | Needed for | What | |---|---| -| everything | Git, a C compiler (`build-essential` / Xcode command line tools: the tree-sitter grammars are C), network access to crates.io and github.com (the OpenShell schema crate is a git dependency pinned to the `v0.1.8` tag) | +| everything | Git, a C compiler (`build-essential` / Xcode command line tools: the tree-sitter grammars are C), network access to crates.io and github.com (the OpenShell schema crate is a git dependency pinned to the `v0.1.9` tag) | | build and test | Rust **1.94** or newer through [rustup](https://rustup.rs). CI pins 1.94 | | Docker image (optional) | Docker with BuildKit | -| sandbox flow (optional) | the `openshell` CLI and `openshell-prover` at 0.1.8, a running OpenShell gateway, and Docker (see section 7) | +| sandbox flow (optional) | the `openshell` CLI and `openshell-prover` at 0.1.9, a running OpenShell gateway, and Docker (see section 7) | ``` rustup toolchain install 1.94 --profile minimal --component rustfmt,clippy @@ -122,7 +122,7 @@ sorts after its own prereleases (`latest`, `latest-stable`, `list`, `pinned`, `n ### Tracking the next OpenShell release (`openshell-next`) `openshell-next` is the one long-lived branch besides `main`. It is `main` plus the OpenShell pin moved to the newest -upstream tag, prereleases included (for example `v0.1.9-pre.3` while `main` is on `v0.1.8`), plus any fix that only +upstream tag, prereleases included (for example `v0.1.10-pre.3` while `main` is on `v0.1.9`), plus any fix that only makes sense on that version. It exists so the next OpenShell is integrated, and its breakage fixed, before it ships as stable. A draft pull request `openshell-next` → `main` and an issue labelled `openshell-next` track it; the issue gets a comment for every new upstream tag. @@ -227,11 +227,15 @@ openshell-annotate diff-logs path/to/sandbox.log --write # inserts directives a # otherwise writes openshell/observed-egress.sh (scanned like any source: review or delete it) ``` -Sample logs for both formats are in `tests/fixtures/logs/`. Filesystem denials are not logged by OpenShell 0.1.8, so +Sample logs for both formats are in `tests/fixtures/logs/`. Filesystem denials are not logged by OpenShell 0.1.9, so `diff-logs` only sees network and L7 events. It reads no sandbox attribution fields, so OpenShell v0.1.8 moving `container.uid`/`container.name` to `device.container.*` (ai-openshell/openshell#5048) needs no change; the OCSF fixture is real v0.1.7 output. +`diff-logs` reads only network (4001) and HTTP (4002) activity. Gateway API Activity records (class 6003) are +skipped, so OpenShell v0.1.9 reporting write-method authorization denials as Create/Update/Delete instead of Other +(`type_uid` 600399, ai-openshell/openshell#5606) needs no change; a unit test covers both shapes. + ## 6. Docker image ``` @@ -255,7 +259,7 @@ scripts/flow.sh /path/to/project --diff-logs sandbox.log # + diff-logs scripts/flow.sh /path/to/project --image my-image:tag --run-seconds 30 --exercise exercise.js -- sleep 600 ``` -It needs `openshell` and `openshell-prover` 0.1.8 on PATH and a connected gateway (`openshell status` shows `Connected`), and +It needs `openshell` and `openshell-prover` 0.1.9 on PATH and a connected gateway (`openshell status` shows `Connected`), and `OPENSHELL_ANNOTATE=/path/to/binary` if the binary is not on PATH. The image's interpreter paths must be real executables (not symlinks) and match `[languages]` in `openshell-annotate.toml`, because OpenShell matches the resolved binary path. A bare `sleep` workload produces no traffic and so no events: drive the sandbox with `--exercise FILE.js` (run with `node -e`), @@ -301,4 +305,4 @@ public repo or a paid plan). `.github/rulesets/protect-openshell-next.json` bloc | `docs are stale` | run `scripts/gen-docs.sh` and commit `docs/` | | `docs/GITHUB_ACTIONS.md is out of date with actions/*/action.yml` | run `scripts/gen-actions-docs.sh` and commit it; add a `BEGIN/END actions-docs ` section for a new action | | sandbox probes get `403` from `api.github.com` | unauthenticated GitHub API rate limit (60 requests per hour per IP), not a policy decision; wait for the reset or use another host | -| `openshell-prover: not found` in `flow.sh` | install the OpenShell 0.1.8 tools; the static commands (`scan`, `generate`, `lint`, `drift`, `diff-logs`) do not need them | +| `openshell-prover: not found` in `flow.sh` | install the OpenShell 0.1.9 tools; the static commands (`scan`, `generate`, `lint`, `drift`, `diff-logs`) do not need them | diff --git a/examples/polyglot/openshell/policy.yaml b/examples/polyglot/openshell/policy.yaml index 77e238d..493d836 100644 --- a/examples/polyglot/openshell/policy.yaml +++ b/examples/polyglot/openshell/policy.yaml @@ -1,5 +1,5 @@ # Generated by openshell-annotate @VERSION@ - DO NOT EDIT. Change the @openshell directives in source and regenerate. -# Validated against openshell-policy-schema and the OpenShell v0.1.8 gateway validator. Each entry's comment gives the reason and source file:line. +# Validated against openshell-policy-schema and the OpenShell v0.1.9 gateway validator. Each entry's comment gives the reason and source file:line. # Startup-only sections (filesystem_policy, landlock, process) need a sandbox recreate to change; network_policies are live. version: 1 filesystem_policy: diff --git a/src/diff_logs.rs b/src/diff_logs.rs index afaca53..4a15918 100644 --- a/src/diff_logs.rs +++ b/src/diff_logs.rs @@ -3,7 +3,7 @@ //! directives that never matched an event are reported as stale. //! //! Delivery of these logs is best-effort: *absence of a deny or an allow is not proof*. Filesystem denials are not logged by -//! OpenShell 0.1.8 (upstream #4270), so only network and L7 HTTP events are handled. +//! OpenShell 0.1.9 (upstream #4270), so only network and L7 HTTP events are handled. use crate::config::Config; use crate::directive::{Directive, Kind}; @@ -876,7 +876,7 @@ pub fn render_text(rep: &Report) -> String { "diff-logs: {} event(s) ({} denied, {} allowed); {} suggestion(s), {} stale directive(s)\n", rep.events, rep.denied, rep.allowed, rep.suggestions.len(), rep.stale.len() ); - s.push_str("note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.8 (#4270).\n"); + s.push_str("note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.9 (#4270).\n"); for g in &rep.suggestions { let up = g.kind.to_ascii_uppercase(); s.push_str(&format!( @@ -988,6 +988,21 @@ garbage line\n"; ); } + #[test] + fn skips_gateway_api_activity_denials_old_and_new() { + // Gateway authorization denials are OCSF API Activity (class 6003) records, not sandbox egress. OpenShell + // v0.1.9 (ai-openshell/openshell#5606) reports write denials as Create/Update/Delete (type_uid 600301..3) + // instead of Other (600399); diff-logs never selects on type_uid, so both shapes are skipped. + let t = concat!( + "{\"class_uid\":6003,\"activity_id\":99,\"type_uid\":600399,\"status_id\":2,\"action\":\"Denied\",\"dst_endpoint\":{\"domain\":\"gw\",\"port\":8080}}\n", + "{\"class_uid\":6003,\"activity_id\":3,\"type_uid\":600303,\"status_id\":2,\"action\":\"Denied\",\"dst_endpoint\":{\"domain\":\"gw\",\"port\":8080}}\n", + "{\"class_uid\":4001,\"action_id\":2,\"dst_endpoint\":{\"domain\":\"pypi.org\",\"port\":443}}\n", + ); + let e = parse_logs(t, "x"); + assert_eq!(e.len(), 1); + assert_eq!(e[0].host, "pypi.org"); + } + #[test] fn sandbox_attribution_location_does_not_matter() { // OpenShell v0.1.8 (ai-openshell/openshell#5048) moved supervisor sandbox attribution from top-level `container.*` diff --git a/src/generate.rs b/src/generate.rs index ce30b5a..0cd973e 100644 --- a/src/generate.rs +++ b/src/generate.rs @@ -652,7 +652,7 @@ pub fn generate( // Emit let mut y = String::new(); y.push_str(&format!("# Generated by {TOOL} - DO NOT EDIT. Change the @openshell directives in source and regenerate.\n")); - y.push_str("# Validated against openshell-policy-schema and the OpenShell v0.1.8 gateway validator. Each entry's comment gives the reason and source file:line.\n"); + y.push_str("# Validated against openshell-policy-schema and the OpenShell v0.1.9 gateway validator. Each entry's comment gives the reason and source file:line.\n"); y.push_str("# Startup-only sections (filesystem_policy, landlock, process) need a sandbox recreate to change; network_policies are live.\n"); y.push_str("version: 1\n"); if !fs_read.is_empty() || !fs_write.is_empty() { diff --git a/src/image.rs b/src/image.rs index a4cc937..2520bab 100644 --- a/src/image.rs +++ b/src/image.rs @@ -1,8 +1,8 @@ //! `generate --image IMAGE`: propose `fs read` directives for application paths in a container image. //! //! The OpenShell supervisor only grants read access to a fixed baseline (`/usr /lib /etc /app /var/log /proc -//! /dev/urandom`, plus `/tmp` and `/dev/null` for writing, verified in v0.1.7 and v0.1.8 `PROXY_BASELINE_*`). An app that lives -//! elsewhere (`/opt/context7`) fails at startup with EACCES, and OpenShell 0.1.8 does not log filesystem denials +//! /dev/urandom`, plus `/tmp` and `/dev/null` for writing, verified in v0.1.7 to v0.1.9 `PROXY_BASELINE_*`). An app that lives +//! elsewhere (`/opt/context7`) fails at startup with EACCES, and OpenShell 0.1.9 does not log filesystem denials //! (upstream #4270), so neither the logs nor `diff-logs` can point at it. The image says where the app lives: its //! WORKDIR, ENTRYPOINT and CMD. @@ -260,7 +260,7 @@ pub fn add_dirs(props: &mut Vec, dirs: Vec, declared: &[String /// Renders the stderr note listing the proposals and the `@openshell fs read` lines to add for them. pub fn render_note(image: &str, props: &[Proposal]) -> String { let mut s = format!( - "note: image {image} keeps files outside OpenShell's baseline read set ({}); the sandbox cannot read them, and OpenShell 0.1.8 does not log that denial (#4270):\n", + "note: image {image} keeps files outside OpenShell's baseline read set ({}); the sandbox cannot read them, and OpenShell 0.1.9 does not log that denial (#4270):\n", ["/usr", "/lib", "/etc", "/app", "/var/log", "/proc", "/dev/urandom"].join(" ") ); for p in props { diff --git a/src/lint.rs b/src/lint.rs index 458dfda..4895c05 100644 --- a/src/lint.rs +++ b/src/lint.rs @@ -521,7 +521,13 @@ pub fn lint(scan: &Scan, cfg: &Config) -> Vec { out.push(directive_finding(&d.file, d.line, m)); } if let Kind::Egress { host, .. } = &d.kind { - if let Some(m) = validate::host_warning(host) { + for m in [ + validate::host_warning(host), + validate::wildcard_private_ip_warning(host), + ] + .into_iter() + .flatten() + { out.push(Finding::new( d.file.clone(), d.line, diff --git a/src/render.rs b/src/render.rs index 142b77c..ef5a7e4 100644 --- a/src/render.rs +++ b/src/render.rs @@ -662,7 +662,7 @@ pub fn diff_logs_human( } out.push_str(&style.paint( "2", - "note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.8 (#4270).\n", + "note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.9 (#4270).\n", )); out } diff --git a/src/validate.rs b/src/validate.rs index d70bd7b..487c0d8 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,7 +2,7 @@ //! //! Authoritative checks live in `openshell-policy-schema` (parsing, unknown fields) and in //! [`gateway_violations`], which calls `openshell_policy::validate_and_canonicalize_sandbox_policy` -//! (OpenShell v0.1.8, the same tag as the schema crate). This module also re-implements the +//! (OpenShell v0.1.9, the same tag as the schema crate). This module also re-implements the //! file-level semantic rules documented in `docs/how-it-works/policies/schema.mdx` so errors carry //! directive locations. `generate` round-trips its output through `parse_policy` and the gateway //! validator. @@ -79,6 +79,79 @@ pub fn host_warning(host: &str) -> Option { Some(format!("`{host}` is an IPv4-mapped IPv6 address; OpenShell v0.1.8+ evaluates these destinations as IPv4, so the rule never matches: use `{v4}`")) } +/// Private and special-use IPv4 ranges a wildcard endpoint no longer admits as IP literals since OpenShell v0.1.9 +/// (ai-openshell/openshell#5522): RFC 1918, CGNAT, IETF protocol assignments, the three TEST-NETs, benchmarking and +/// broadcast. Loopback, link-local and unspecified are always blocked and rejected by [`check_host`] already. +/// Each entry is the inclusive range per octet. +const GRANT_ONLY_V4: &[[(u8, u8); 4]] = &[ + [(10, 10), (0, 255), (0, 255), (0, 255)], + [(172, 172), (16, 31), (0, 255), (0, 255)], + [(192, 192), (168, 168), (0, 255), (0, 255)], + [(100, 100), (64, 127), (0, 255), (0, 255)], + [(192, 192), (0, 0), (0, 0), (0, 255)], + [(192, 192), (0, 0), (2, 2), (0, 255)], + [(198, 198), (18, 19), (0, 255), (0, 255)], + [(198, 198), (51, 51), (100, 100), (0, 255)], + [(203, 203), (0, 0), (113, 113), (0, 255)], + [(255, 255), (255, 255), (255, 255), (255, 255)], +]; + +/// Matches one DNS label against a pattern label in which `*` stands for any run of characters. +fn label_glob(pat: &str, s: &str) -> bool { + match pat.split_once('*') { + None => pat == s, + Some((head, rest)) => { + s.starts_with(head) + && (0..=s.len() - head.len()).any(|i| label_glob(rest, &s[head.len() + i..])) + } + } +} + +/// Returns a private IPv4 address that the wildcard `host` matches, if any. A leading `**` label matches one or more +/// labels; other labels match one label each. +fn wildcard_private_v4(host: &str) -> Option { + let h = host.trim_matches(|c| c == '[' || c == ']'); + if !h.contains('*') { + return None; + } + let labels: Vec<&str> = h.split('.').collect(); + let (spread, tail) = match labels.split_first() { + Some((&"**", rest)) => (true, rest), + _ => (false, &labels[..]), + }; + let fits = if spread { + tail.len() < 4 + } else { + tail.len() == 4 + }; + if !fits + || tail + .iter() + .any(|l| l.is_empty() || !l.chars().all(|c| c.is_ascii_digit() || c == '*')) + { + return None; + } + let mut pats = vec!["*"; 4 - tail.len()]; + pats.extend_from_slice(tail); + GRANT_ONLY_V4.iter().find_map(|net| { + let mut octets = [0u8; 4]; + for (i, &(lo, hi)) in net.iter().enumerate() { + octets[i] = (lo..=hi).find(|v| label_glob(pats[i], &v.to_string()))?; + } + Some(std::net::Ipv4Addr::from(octets)) + }) +} + +/// Returns a warning when the wildcard `host` can match a private IPv4 literal such as `10.0.0.1`. +/// +/// Since OpenShell v0.1.9 (ai-openshell/openshell#5522) a wildcard endpoint no longer allows a private IP literal on +/// its own: the destination needs an exact endpoint for that address or an `allowed_ips` grant. Callers skip the +/// warning for policy endpoints that have `allowed_ips`. +pub fn wildcard_private_ip_warning(host: &str) -> Option { + let ip = wildcard_private_v4(host)?; + Some(format!("wildcard host `{host}` matches private IP literals such as `{ip}`; OpenShell v0.1.9+ no longer allows a private IP literal through a wildcard endpoint: declare each private address as its own endpoint (in a policy file, `allowed_ips` also works)")) +} + /// Checks a `filesystem_policy` path; `write` is true for `read_write` entries. /// /// # Errors @@ -400,6 +473,11 @@ pub fn check_document(doc: &PolicyDocument) -> (Vec, Vec) { if let Some(m) = host_warning(&ep.host) { warns.push(format!("{at}: {m}")); } + if ep.allowed_ips.is_empty() { + if let Some(m) = wildcard_private_ip_warning(&ep.host) { + warns.push(format!("{at}: {m}")); + } + } } if ep.port != 0 && !ep.ports.is_empty() { errs.push(format!("{at}: `port` and `ports` are mutually exclusive")); @@ -491,6 +569,31 @@ mod tests { assert!(host_warning("api.example.com").is_none()); } + #[test] + fn wildcard_hosts_that_match_private_ip_literals_warn() { + assert!(wildcard_private_ip_warning("**.*.*") + .unwrap() + .contains("such as `10.0.0.0`")); + assert!(wildcard_private_ip_warning("10.*.*.*").is_some()); + assert!(wildcard_private_ip_warning("*.23.45.67") + .unwrap() + .contains("`10.23.45.67`")); + assert!(wildcard_private_ip_warning("**.168.1.1") + .unwrap() + .contains("`10.168.1.1`")); + assert!(wildcard_private_ip_warning("17*.*.*.*") + .unwrap() + .contains("`172.16.0.0`")); + assert!(wildcard_private_ip_warning("[**.*.*]").is_some()); + // public-only, exact or DNS wildcards: no warning + assert!(wildcard_private_ip_warning("8.*.*.*").is_none()); + assert!(wildcard_private_ip_warning("172.32.*.*").is_none()); + assert!(wildcard_private_ip_warning("10.0.0.1").is_none()); + assert!(wildcard_private_ip_warning("*.example.com").is_none()); + assert!(wildcard_private_ip_warning("**.example.com").is_none()); + assert!(wildcard_private_ip_warning("*.*.*.*.*").is_none()); + } + #[test] fn fs_paths() { assert!(check_fs_path("/workspace/data", true).is_ok()); diff --git a/tests/cli.rs b/tests/cli.rs index f9c6675..0d06443 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -2272,3 +2272,48 @@ fn lint_policy_warns_about_ipv4_mapped_hosts() { "{s}" ); } + +/// OpenShell v0.1.9 (ai-openshell/openshell#5522): a wildcard endpoint no longer allows a private IP literal on its +/// own. lint warns about wildcard hosts that match private IPv4 literals, unless the policy endpoint has `allowed_ips`. +#[test] +fn lint_warns_about_wildcards_that_match_private_ip_literals() { + let t = tempfile::tempdir().unwrap(); + std::fs::write(t.path().join("a.js"), "console.log(1)\n").unwrap(); + let policy = |extra: &str| { + format!("version: 1\nnetwork_policies:\n lan:\n endpoints:\n - host: \"**.*.*\"\n port: 443\n{extra} binaries:\n - path: /usr/bin/curl\n") + }; + std::fs::write(t.path().join("p.yaml"), policy("")).unwrap(); + let o = run( + t.path(), + &["lint", "--format", "compact", "--policy", "p.yaml"], + ); + let s = out(&o); + assert!( + s.contains("wildcard host `**.*.*` matches private IP literals such as `10.0.0.0`"), + "{s}{}", + err(&o) + ); + std::fs::write( + t.path().join("p.yaml"), + policy(" allowed_ips:\n - 10.23.45.0/24\n"), + ) + .unwrap(); + let s = out(&run( + t.path(), + &["lint", "--format", "compact", "--policy", "p.yaml"], + )); + assert!(!s.contains("private IP literals"), "{s}"); + // and in an egress directive, where only an exact address helps + std::fs::write( + t.path().join("a.js"), + "// @openshell egress 10.*.*.*:443 reason=\"lan\"\nconsole.log(1)\n", + ) + .unwrap(); + let s = out(&run(t.path(), &["lint", "--format", "compact"])); + assert!( + s.contains( + "a.js:1: warning[directive]: wildcard host `10.*.*.*` matches private IP literals" + ), + "{s}" + ); +} diff --git a/tests/fixtures/sample/policy.expected.yaml b/tests/fixtures/sample/policy.expected.yaml index 4306257..46d1634 100644 --- a/tests/fixtures/sample/policy.expected.yaml +++ b/tests/fixtures/sample/policy.expected.yaml @@ -1,5 +1,5 @@ # Generated by openshell-annotate @VERSION@ - DO NOT EDIT. Change the @openshell directives in source and regenerate. -# Validated against openshell-policy-schema and the OpenShell v0.1.8 gateway validator. Each entry's comment gives the reason and source file:line. +# Validated against openshell-policy-schema and the OpenShell v0.1.9 gateway validator. Each entry's comment gives the reason and source file:line. # Startup-only sections (filesystem_policy, landlock, process) need a sandbox recreate to change; network_policies are live. version: 1 filesystem_policy: diff --git a/tests/gateway_policies.rs b/tests/gateway_policies.rs index e611744..99576e9 100644 --- a/tests/gateway_policies.rs +++ b/tests/gateway_policies.rs @@ -74,3 +74,27 @@ fn websocket_credential_rewrite_needs_the_websocket_protocol() { let ws = openshell_annotate::validate::gateway_violations(&policy("websocket")).unwrap(); assert!(ws.is_empty(), "{ws:?}"); } + +/// OpenShell v0.1.9 (ai-openshell/openshell#4359): middleware endpoint selectors match hosts on every port, and a +/// selector with a port now fails validation. annotate does not generate `network_middlewares`, but `lint --policy`, +/// `drift` and `generate` run the gateway validator on committed policies, so they report it. +#[test] +fn middleware_selectors_cannot_include_a_port() { + let policy = |include: &str| { + format!( + "version: 1\nnetwork_middlewares:\n redact:\n middleware: openshell/regex\n order: 10\n config:\n mode: redact\n on_error: fail_closed\n endpoints:\n include: [\"{include}\"]\nnetwork_policies:\n api:\n binaries:\n - path: /usr/bin/curl\n endpoints:\n - host: api.example.com\n port: 443\n" + ) + }; + let with_port = + openshell_annotate::validate::gateway_violations(&policy("api.example.com:443")).unwrap(); + assert!( + with_port.iter().any(|v| v.contains("cannot include one")), + "{with_port:?}" + ); + let without = + openshell_annotate::validate::gateway_violations(&policy("api.example.com")).unwrap(); + assert!( + !without.iter().any(|v| v.contains("cannot include one")), + "{without:?}" + ); +} diff --git a/tests/golden/diff_logs_human_color.txt b/tests/golden/diff_logs_human_color.txt index 7778dfb..f8252e0 100644 --- a/tests/golden/diff_logs_human_color.txt +++ b/tests/golden/diff_logs_human_color.txt @@ -59,5 +59,5 @@ ✖ 4 suggestions (1 stale directive · 1 not actionable) 💡 next: `openshell-annotate diff-logs denied.log --write` inserts 3 directives (review, then regenerate the policy) -note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.8 (#4270). +note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.9 (#4270).  \ No newline at end of file diff --git a/tests/golden/diff_logs_human_plain.txt b/tests/golden/diff_logs_human_plain.txt index ddfc288..a7737de 100644 --- a/tests/golden/diff_logs_human_plain.txt +++ b/tests/golden/diff_logs_human_plain.txt @@ -59,4 +59,4 @@ blocked: 169.254.169.254:80 x1 4 suggestions (1 stale directive, 1 not actionable) next: `openshell-annotate diff-logs denied.log --write` inserts 3 directives (review, then regenerate the policy) -note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.8 (#4270). +note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.9 (#4270). diff --git a/tests/golden/diff_logs_ocsf_1_8_0_plain.txt b/tests/golden/diff_logs_ocsf_1_8_0_plain.txt index 2489c23..b3b1f88 100644 --- a/tests/golden/diff_logs_ocsf_1_8_0_plain.txt +++ b/tests/golden/diff_logs_ocsf_1_8_0_plain.txt @@ -39,4 +39,4 @@ stale: jsonplaceholder.typicode.com:443 /usr/local/bin/python3.12 3 suggestions (1 stale directive) next: `openshell-annotate diff-logs ocsf.jsonl --write` inserts 3 directives (review, then regenerate the policy) -note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.8 (#4270). +note: logs are best-effort and lossy; absence of an event is not proof. Filesystem denials are not logged by OpenShell 0.1.9 (#4270).