Skip to main content
VulnParse-Pin emblem VulnParse-Pin emblem
VulnParse-Pin
Architecture Security Features.md
View source on GitHub ↗

Security Features

VulnParse-Pin v2.1.1 (Apache-2.0) enforces fail-closed security controls across filesystem I/O, DuckDB storage, XML/SARIF/ZIP/CMDB parsing, threat-intel caches, offline ML artifacts, reporting templates, CSV exports, RunManifest verification, CI/CD supply-chain workflows, and the local MCP and browser workbench servers.

Security Goals

  • Prevent path traversal, ancestor symlink escapes, and DuckDB WAL/temp symlink attacks
  • Prevent XXE, DTD/entity expansion, JSON/SARIF memory exhaustion, ANSI/control injection, and OSV zip-bomb/traversal attacks
  • Detect tampering and prevent silent HMAC-to-SHA256 downgrades in threat-intel caches and signed ML models
  • Protect downstream readers from HTML/Markdown XSS/injection and CSV formula injection
  • Keep vpp verify, vpp intel status, vpp simulate, vpp mcp, and vpp gui strictly read-only by default
  • Protect localhost HTTP surfaces (vpp mcp and vpp gui) against DNS rebinding, CSRF, CSWSH, clickjacking, HTTP request smuggling, and unbounded resource exhaustion

File I/O, _UMASK_LOCK, and DuckDB Path Hardening

  • PFH (src/vulnparse_pin/io/pfhandler.py): Defaults in build_pfh() are forbid_symlinks_read=True (opt-out via --allow-symlinks-read), forbid_symlinks_write=True, enforce_roots_on_write=True, enforce_roots_on_read=False (opt-in via --enforce-root-read), file_mode=0o600, and dir_mode=0o700.
  • Ancestor symlink & loop checks (_check_no_symlinks_or_loops): Validates every path segment from root to leaf against stat.S_ISLNK and errno.ELOOP. On macOS (darwin), PermFileHandler (src/vulnparse_pin/io/pfhandler.py) and storage/db.py recognize Apple’s three root-owned immutable Signed System Volume (SSV) root symlinks (/var -> private/var, /tmp -> private/tmp, /etc -> private/etc resolving to root-owned non-symlink directories under /private) while rejecting all other symlinks and child symlinks fail-closed.
  • Thread-safe restricted umask (_UMASK_LOCK): ensure_safe_dir_non_pfh() and open_for_write_non_pfh() (src/vulnparse_pin/storage/db.py) acquire _UMASK_LOCK around os.umask() so staging temp files and directories are created 0o600/0o700 atomically before os.replace().
  • DuckDB workspace guards (VppDatabase): _validate_duckdb_paths() checks .vpp.db, its .wal and .tmp sidecars, and all parent segments against symlinks; duckdb.connect() and transactions run under umask(0o177) + _UMASK_LOCK with _chmod_0600_if_exists().
  • Read-only vpp verify (_build_verify_pfh): Verifies RunManifest JSON, SHA-256 ledger hash chains, and listed output artifact hashes without writing to $HOME/XDG_* directories unless a custom --log-file is passed.

XML, SARIF, JSONL, Inventory, and Input Validation Hardening

  • Hardened lxml XML parsing (NO defusedxml): src/vulnparse_pin/parsers/_xml_security.py replaces defusedxml with safe_iterparse() and sniff_xml_head_events() backed by lxml.etree (resolve_entities=False, no_network=True, load_dtd=False, dtd_validation=False, huge_tree=False).
    • inspect_xml_prolog() inspects up to MAX_XML_PROLOG_BYTES = 1 MiB before the root element, handling UTF-8 BOM, UTF-16 BOM, UTF-32, and BOM-less UTF-16LE/BE, and rejecting <!ENTITY, SYSTEM, PUBLIC, parameter entities (%), internal DTD subsets, and NUL bytes.
    • safe_iterparse() iterates all elements internally (even when tag= is specified) and runs assert_no_entity_nodes() across subtrees so entity nodes outside filtered tags cannot evade rejection.
  • Bounded input validation (FileInputValidator): 500 MiB default cap (up to 50 GiB with --allow-large), 64 KiB SchemaDetector head read, 8 MiB max JSONL line, and 32 MiB CSV field cap (_MAX_CSV_FIELD_BYTES).
  • Chunked SARIF streaming & 512-level depth guard: _FastSarifStreamReader (src/vulnparse_pin/parsers/sarif_parser.py) decodes 4 MiB chunks incrementally via json.JSONDecoder.raw_decode, skips unrelated values in O(1) memory, and enforces an iterative 512-level JSON nesting depth ceiling (_MAX_JSON_NESTING_DEPTH = 512, converting any RecursionError to ValueError) so deeply nested SARIF payloads fail closed across Python versions.
  • Offline parser fuzzing harness (fuzz/fuzz_parsers.py, fuzz/targets.py, tests/test_fuzz_parsers.py): Provides an Atheris coverage-guided fuzzing harness exercising XML prolog/entity guards, SchemaDetector, and all 5 primary streaming parsers over bounded 64 KiB inputs inside isolated temporary workspaces with zero network I/O and strict propagation of programming errors (KeyError, IndexError, RecursionError).
  • Inventory compiler & auditor (vpp assets, src/vulnparse_pin/core/inventory_compiler.py):
    • _read_bytes_safe() enforces a 64 MiB hard read cap (_MAX_INVENTORY_BYTES), rejects NUL bytes, symlinks, symlink loops, and non-regular files (os.lstat + O_NOFOLLOW + os.fstat).
    • Nmap XML inventory inputs run through inspect_xml_prolog() and safe_iterparse() to block XXE/DTD attacks.
    • _strip_ansi_and_control() strips ANSI CSI/OSC/DCS/APC escape sequences and C0/C1 control characters across CMDB/cloud tags, hostnames, owners, and titles before YAML emission.
    • Emitted and merged assets.yaml payloads are validated against JSON Schema Draft 2020-12 (assets.schema.json); rule promotion acquires an exclusive fcntl.flock lock on a 0o600 O_NOFOLLOW lockfile and performs atomic writes.
    • _evaluate_exposure_honesty() preserves internet_facing: null on ambiguous private-only cloud/CMDB assets unless explicitly tagged or overridden via --default-private-exposure.

Clean-Room Apache-2.0 CVSS Engine

src/vulnparse_pin/utils/cvss_utils.py implements FIRST CVSS v2.0, v3.0, v3.1, and v4.0 validation and base-score calculation using Python standard library modules only (Decimal, Fraction), removing the legacy LGPL cvss dependency.

Threat-Intel Cache, Network & OSV Zip Security

  • Strict HMAC anti-downgrade: When VP_FEED_CACHE_HMAC_KEY (FeedCacheManager) or VP_SQLITE_HMAC_KEY (nvd_cache.sqlite3, epss_cache.sqlite3, kev_cache.sqlite3, ghsa_cache.sqlite3, osv_cache.sqlite3) is set, plain sha256 downgrade sidecars or unsigned pre-existing DBs fail closed with zero auto-resign; tampered SQLite files are quarantined to .tampered.<UTCSTAMP>.
  • World-writable rejection: Caches and sidecars with stat.S_IWOTH are rejected immediately.
  • Per-hop HTTPS redirect validation: _open_https_stream() uses allow_redirects=False and validates every redirect Location to https:// (MAX_NVD_META_BYTES = 1 MiB, MAX_REMOTE_FEED_BYTES = 200 MiB, MAX_DECOMPRESSED_FEED_BYTES = 2 GiB).
  • OSV zip-bomb & traversal guard: OSVEnrichmentSource._validate_zip_member() rejects .., absolute/backslash paths, drive prefixes, NUL bytes, POSIX symlinks, entries > 50 MiB, total > 2 GiB, > 250,000 entries, and compression ratios > 500.
  • GHSA token validation: Rejects \r/\n header-unsafe tokens and enforces GitHub token prefixes without logging secrets.

Offline ML Model Registry Security (vpp ml)

  • Signed model verification (src/vulnparse_pin/ml/registry.py): load_signed_model() enforces a strict < 2 MiB cap (MAX_MODEL_ARTIFACT_BYTES = 2 * 1024 * 1024), 64 KiB signature cap (MAX_SIGNATURE_ARTIFACT_BYTES), and 64 MiB optional ONNX cap (MAX_ONNX_ARTIFACT_BYTES), rejecting symlinks, symlink loops, non-regular files, and world-writable files (stat.S_IWOTH) via O_NOFOLLOW.
  • Anti-downgrade HMAC enforcement: Every model artifact requires a companion .sig.json verified via constant-time hmac.compare_digest on the SHA-256 digest; when VP_MODEL_HMAC_KEY (MODEL_HMAC_ENV) is set, unsigned or plain sha256 signatures fail closed unless mode == "hmac-sha256".
  • Non-mutating default: resolve_ml_policy() defaults to ml.mode: shadow, recording ml_* attributions and pre_kev_* signals without altering baseline deterministic scores unless active is explicitly configured.

Localhost Browser Workbench (vpp gui) & MCP Server (vpp mcp) Hardening

  • Localhost Browser GUI (src/vulnparse_pin/ui/gui_server.py):
    • Binds 127.0.0.1:8787 by default; validate_http_security() fails closed on non-loopback --host bindings unless --auth-token-env names an environment variable of at least 16 characters, verified via hmac.compare_digest on Bearer Authorization.
    • Generates a per-process 256-bit CSRF token (secrets.token_urlsafe(32)) and verifies X-VPP-CSRF via hmac.compare_digest on POST /api/rpc.
    • Sends strict HTTP response headers: Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'; object-src 'none', X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, and Cache-Control: no-store.
    • Enforces HttpSecurityPolicy Host and Origin allowlists to block DNS-rebinding and cross-origin attacks, rejects duplicate security/framing headers (400), rejects Transfer-Encoding (501), enforces Content-Type: application/json (415), requires Content-Length (411) bounded by 4 MiB (413 MAX_MESSAGE_BYTES), caps concurrent connections via threading.BoundedSemaphore(32) (503), sets 15.0s socket timeouts (HTTP_SOCKET_TIMEOUT), and serializes JSON with allow_nan=False.
    • Runs read-only by default; opt-in --allow-write enables write-gated modals (gui_propose_deferral, gui_promote_shadow_asset) that record hash-chained GUI_DEFERRAL_RECORDED and GUI_ASSET_RULE_PROMOTED events in ledger_events with full DuckDB + YAML atomic rollback on failure.
  • MCP Server (src/vulnparse_pin/mcp/server.py, src/vulnparse_pin/mcp/tools.py):
    • stdio (default) routes all logs/banners to stderr and bounds frames at 4 MiB (MAX_MESSAGE_BYTES); streamable-http enforces the same validate_http_security() / HttpSecurityPolicy, MAX_HTTP_CONCURRENCY = 32 (503), HTTP_SOCKET_TIMEOUT = 15.0, 415 application/json, 501 Transfer-Encoding, 400 duplicate-header checks, MAX_BATCH_ITEMS = 64, MAX_JSON_DEPTH = 64, allow_nan=False, and sanitized -32603 internal error responses.
    • Opens .vpp.db with read_only=True by default, exposing 7 read-only tools and blocking the 3 mutating tools (ToolDisabledError / -32601) unless --allow-write is passed.
    • Validates --assets, --decisions, and --workspace-root via _validate_mcp_config_path() (_check_no_symlinks_or_loops + PFH confinement).
    • Isolates read-only vpp_diff_and_drift(re_enrich=True) by copying .vpp.db and .wal into 0o600 O_NOFOLLOW | O_EXCL temp files; _assert_export_target_not_protected() blocks vpp_export_dossier from overwriting .vpp.db, .wal, .tmp, workspace config files, or .db/.duckdb/.wal/.sqlite/.sqlite3/.yaml/.yml extensions.
    • vpp_scan_and_diff runs _verify_sqlite_caches_fail_closed() before ingestion, merges inline_decisions via merge_decisions_registries(), and invokes delete_run() rollback on failure; vpp_propose_deferral snapshots and rolls back both DuckDB tables and decisions.yaml on error.
  • Unified 3-Mode Workbench HTML (src/vulnparse_pin/mcp/ui_app.py):
    • Zero-CDN DOM-only rendering (document.createElement / textContent, zero innerHTML, zero http:// or https:// URLs).
    • Uses Object.create(null) dictionaries to prevent prototype pollution, Number.isFinite guards on bar charts/metrics, RPC_TIMEOUT_MS = 30000 timeouts, and initRpcId-gated hostOrigin latching (blocking tools/call without a verified host origin in mcp mode).
    • Rejects CSS url(, expression(, and @import tokens in host theme variables, escapes embedded snapshot JSON for <script type="application/json"> via _escape_json_for_script_tag() (\u0026, \u003c, \u003e, \u2028, \u2029), and embeds strict <meta http-equiv="Content-Security-Policy"> (connect-src 'none' in mcp and static-simulator; connect-src 'self' in loopback).

Reporting, CSV Export, Config & Webhook Hardening

  • Jinja2 autoescape & md_escape: src/vulnparse_pin/reporting/renderer.py configures Jinja2 autoescape=select_autoescape(["html", "xml", "html.j2", "xml.j2", "htm", "htm.j2"]) for HTML Dossiers/Roadmaps and applies md_escape across Markdown Dossiers, Roadmaps, PR diff comments, remediation plans, simulation reports, and legacy markdown_report.py. Generated HTML (including simulator-html) contains zero external CDN scripts or stylesheets.
  • CSV formula-injection sanitization: csv_exporter.py neutralizes dangerous prefixes (=, +, -, @, \t, \r) and strips control characters by default. Disabling via --no-csv-sanitize requires explicit --confirm-unsafe-csv (otherwise exits with code 2).
  • Safe YAML & schema validation: config_source.py and assets_context.py load YAML with ruamel.yaml.YAML(typ="safe", pure=True) and validate against JSON Schema Draft 2020-12 (config.schema.json, assets.schema.json, decisions.schema.json).
  • Signed HTTPS webhooks: webhook_delivery.py enforces https:// without embedded credentials, allow_redirects=False, pinned-IP DNS validation (_PinnedIPHTTPSAdapter), bounded payload sizes (262144 bytes), and HMAC-SHA256 signatures via VP_WEBHOOK_HMAC_KEY.

Release Pipeline, CI & Supply-Chain Security

  • 40-character commit-SHA action pins, least-privilege checkouts, CodeQL, Scorecard & Non-Prod Rehearsal (.github/workflows/{ci,release,release-rehearsal,docs-pages,codeql,scorecard}.yml): Every uses: action reference is pinned to a 40-character hexadecimal commit SHA (zero mutable tag references), with permissions: {} at workflow top level in ci.yml, release.yml, release-rehearsal.yml, and codeql.yml, narrow job-level permissions (including explicit permissions: contents: read on docs-pages.yml build and all release-rehearsal.yml jobs), and persist-credentials: false on every actions/checkout step across all workflows. release-rehearsal.yml automatically rehearses the full build, SBOM, multi-arch .deb/.rpm, Homebrew bottle/formula (ruby -c), ephemeral-GPG APT/RPM signing (rpmsign/rpmkeys), root and offline examples/deploy/Dockerfile --read-only smoke tests, and strict MkDocs build on PRs and release branches with zero production secrets (scripts/check_release_drift.py also runs in release.yml validation-gate, while finalize-release and publish-ghcr rehearse downstream repo/formula signing and examples/deploy/Dockerfile on -rcN tags as well as stable releases). codeql.yml runs CodeQL analysis over actions and python, while scorecard.yml runs OpenSSF Scorecard on main and uploads SARIF results to GitHub Code Scanning.
  • 100% hash-locked dependencies & --no-isolation builds (packaging/requirements-{build,ci,core,docs,runtime,sbom,ui}.txt, ci.yml, release.yml, docs-pages.yml): Every CI, release, docs, and SBOM environment installs binary wheels strictly with --require-hashes --only-binary=:all:, builds distributions with --no-isolation, and verifies the locally built wheel by SHA-256 before installation. release.yml passes release-requirements (requirements-sbom.txt and requirements-runtime.txt) to finalize-release and pins multi-arch @sha256: digests on ubuntu:22.04 and rockylinux:9 smoke-test containers.
  • Input-free tag dispatch, pre-checkout validation & immutable ${{ github.sha }} checkouts (.github/workflows/release.yml): Uses input-free tag dispatch (workflow_dispatch: {}, where operators select a v* tag under Use workflow from -> Tags instead of passing a branch or tag input) and checks github.ref_type == "tag" plus github.ref == "refs/tags/${REF_NAME}" against ^v[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z]+(\.[0-9A-Za-z]+)*)?$ before any git checkout, blocking branch-name spoofs such as refs/heads/v2.1.0. All 8 actions/checkout steps pin directly to immutable ${{ github.sha }} (eliminating CodeQL cache-poisoning and tag-TOCTOU risks), all 9 downstream jobs require startsWith(github.ref, 'refs/tags/v') with no workflow_dispatch bypass (with publish-pypi, publish-pkg-repos, and publish-homebrew-tap additionally requiring needs.validation-gate.outputs.is_prerelease != 'true'), verify-tag unconditionally confirms HEAD == github.sha == TAG_SHA via a single git ls-remote plus origin/main ancestry (exporting validation-gate.outputs.release_sha, while downstream checkouts pin ${{ github.sha }} directly rather than referencing release_sha), and context values pass through env: bindings rather than inline shell interpolation.
  • Header-only PEP 639 METADATA & [ui,mcp] CycloneDX SBOM copyleft gates (ci.yml, release.yml): Splits .dist-info/METADATA on the first blank line (\r?\n\r?\n) to inspect headers only for License-Expression: Apache-2.0, License-File: LICENSE/NOTICE, py.typed, and zero copyleft tokens (agpl|lgpl|gpl|affero). Both ci.yml and release.yml install ${wheels[0]}[ui,mcp] into an isolated runtime virtualenv, generate a CycloneDX JSON SBOM via cyclonedx-py, and fail closed if vulnparse-pin, mcp, or Apache-2.0 is absent or if any component declares a copyleft license.
  • Gated publishing, concurrency serialization, SHA256SUMS.asc & SLSA provenance (release.yml, docs-pages.yml, MANIFEST.in): publish-pypi, publish-ghcr, publish-pkg-repos, and publish-homebrew-tap all depend on finalize-release (and phased opt-in gates fail closed on partial credentials). finalize-release (release-finalize-<tag>), publish-ghcr (release-publish-ghcr), publish-pkg-repos (release-publish-pkg-repos), and publish-homebrew-tap (release-publish-homebrew-tap) all enforce cancel-in-progress: false concurrency serialization; publish-ghcr restricts floating :latest, :major, and :major.minor tags to stable versions (skipping - prereleases). build-homebrew-bottles aligns arm64_sequoia bottle builds on macos-15 using an ephemeral build venv (BOTTLE_VENV) to avoid PEP 668 EXTERNALLY-MANAGED pip failures, MANIFEST.in bundles packaging/generate_cli_assets.py inside sdists for Homebrew source-fallback man-page and completion generation, and docs-pages.yml restricts GitHub Pages uploads and deployments to refs/heads/main with cancel-in-progress scoped strictly to pull requests. finalize-release imports GPG_PRIVATE_KEY into an isolated 0o700 GNUPGHOME with a gpgconf --kill gpg-agent cleanup trap, signs SHA256SUMS via --pinentry-mode loopback --passphrase-fd 0 --digest-algo SHA256 --armor --detach-sign, verifies gpg --batch --verify SHA256SUMS.asc SHA256SUMS, and generates SLSA build provenance attestations (actions/attest-build-provenance) for all release assets and pushed GHCR OCI digests.
  • Hash-pinned Dockerfiles, fail-closed /wheels offline guard, Stage-1 audit & .dockerignore secret protection (Dockerfile, examples/deploy/Dockerfile, .dockerignore): Both root Dockerfile and examples/deploy/Dockerfile pin multi-arch python:3.12-slim@sha256:... digests in both builder and runtime stages and install dependencies strictly with --require-hashes --only-binary=:all:. Root Dockerfile Stage 1 builds the local wheel inside /tmp/build-venv using packaging/requirements-build.txt and --no-isolation, installs runtime wheels from packaging/requirements-{core,ui,runtime}.txt plus the SHA-256-verified local wheel, and optionally stages ./wheelhouse/ (COPY LICENSE wheelhous[e] /wheels/) while failing closed if PIP_NO_INDEX=1 lacks a valid local PIP_FIND_LINKS directory. examples/deploy/Dockerfile ships standalone hash-locked examples/deploy/requirements-runtime.txt, requires --build-arg VPP_PYPI_SHA256=<64-hex> (failing closed when missing or malformed), and validates offline wheel PEP 440 versions against VPP_PYPI_VERSION. Both Dockerfiles run an inline Stage-1 email.parser.HeaderParser zero-copyleft and Apache-2.0 audit over every .dist-info/METADATA file, and .dockerignore excludes fuzz/ while placing trailing secret/database re-exclusions (.env*, .vpp*.db*, *.pem, *.key, etc.) after !wheelhouse/ and !examples/deploy/.

Distro Packaging, Repository Signing & CLI Parser Hardening

Linux Package Staging & Archive Security (packaging/build_linux_pkg.py, packaging/python_standalone.json)

  • Pinned HTTPS-only toolchains, hash-locked UI closure & symlink-safe staging: python-build-standalone (3.12.16, release 20261201) and nfpm (2.49.0) tarballs are pinned by lowercase 64-hex SHA-256 digests in packaging/python_standalone.json and fetched by download_verified_artifact(), which enforces https:// via _HttpsOnlyRedirectHandler, verifies digests in constant time (hmac.compare_digest), and replaces staging files atomically (os.replace). Runtime dependencies and the built vulnparse-pin wheel are installed strictly from hash-locked packaging/requirements-ui.txt using --require-hashes --only-binary=:all:. _assert_not_symlink() rejects pre-existing symlinks across download cache directories, destination files, stage_root, staging prefix components, and packaged outputs.
  • Fail-closed archive extraction (safe_extract_tar_gz): Performs two-pass pre-validation before extraction—Pass 1 rejects .. traversal, absolute/backslash paths, NUL bytes, escaping symlink/hardlink bounds, character/block devices, FIFOs, and setuid/setgid (S_ISUID | S_ISGID) bits while collecting the complete symlink table; Pass 2 catches out-of-order symlink-ancestor pivots, symlink/member path collisions, hardlinks targeting or traversing symlinks, and multi-hop symlink escapes or cycles (_resolve_virtual_path, max_hops=40)—and extracts strictly via mandatory PEP 706 tarfile.data_filter (filter="data", failing closed if unavailable).
  • Isolated -I wrappers, umask-safe permissions & race-free nFPM output: write_posix_wrapper() writes /usr/bin/vpp and /usr/bin/vulnparse-pin wrappers invoking exec /opt/vulnparse-pin/venv/bin/python3 -I -m vulnparse_pin.main "$@"; normalize_tree_permissions() normalizes /opt/vulnparse-pin directories/executables to 0o755 and regular files to 0o644 (skipping symlinks without following them) so packages built under umask 0077 stay usable by non-root users; package_with_nfpm() stages .deb/.rpm outputs in per-invocation tempfile.TemporaryDirectory directories and atomically promotes them with os.replace().
  • Header-only RFC 822 copyleft audits (audit_venv_zero_copyleft, audit_libexec_licenses): Uses email.parser.HeaderParser(policy=email.policy.compat32) to inspect License, License-Expression, Classifier, and License-File headers across every non-symlink .dist-info/METADATA file inside bundled virtualenvs and Homebrew libexec, failing closed on any copyleft token, empty metadata directories, or missing/non-Apache-2.0 vulnparse-pin metadata (plus missing textual in Linux bundles and Homebrew CLI bottle builds) while ignoring unrelated fields such as Provides-Extra.

Ephemeral GPG Repository Signing & Atomic R2 Sync (packaging/build_pkg_repos.py, packaging/r2_sync.py)

  • Ephemeral 0o700 GPG signer, RPM 4.18+ macro safety & retry verification (EphemeralGPGSigner, compute_rpm_immutable_digest, build_rpm_repo): Requires non-empty GPG_PRIVATE_KEY and GPG_PASSPHRASE (fail-closed), caches gpg, gpgconf, rpmsign, rpmkeys, and rpm executables at __enter__, falls back to /tmp whenever TMPDIR exceeds 50 bytes or contains unsafe characters (preserving the 108-byte SUN_LEN Unix socket cap), pins TMPDIR to the isolated 0o700 GNUPGHOME, validates GNUPGHOME and temporary passphrase file paths against SAFE_RPM_PATH_RE (^[A-Za-z0-9._/+-]+\Z) before RPM macro expansion, passes passphrases via --passphrase-fd 0 (and zeroed 0o600 temp files unlinked in finally for rpmsign using RPM 4.18+-compatible _gpg_sign_cmd_extra_args, _gpg_path, and _gpg_digest_algo macros), kills gpg-agent via gpgconf --kill gpg-agent on exit, and verifies generated signatures fail-closed (gpg --batch --verify on APT InRelease/Release.gpg and RPM repomd.xml.asc; verify_rpm_signature() imports the public key into an isolated 0o700 ephemeral rpmdb and runs rpmkeys --checksig / rpm -K, accepting rc == 0 only when signature OK is present and NOT OK, MISSING KEYS, NOKEY, and BAD are absent). build_rpm_repo() preserves historical existing_rpm_files byte-for-byte (is_new=False) and signs only newly built (is_new=True) RPMs; on release retries where a newly built unsigned .rpm shares a filename with an already-signed pool .rpm, idempotent reuse is permitted only when sign_rpms=True, compute_rpm_immutable_digest() confirms byte-identical immutable Main Header + Payload bytes (parsing the 96-byte Lead and 8-byte-aligned Signature Header), and verify_rpm_signature() succeeds on the pool .rpm (failing closed on any payload change, unsigned pool file, or foreign key).
  • Pure-stdlib .deb/.rpm validation, .zst bomb defense, \Z regexes & header injection guards: parse_deb_control_fields() parses ar archives and control.tar* with strict size caps (MAX_CONTROL_ARCHIVE_BYTES, MAX_DECOMPRESSED_TAR_BYTES, MAX_CONTROL_FILE_BYTES), rejecting GNU/BSD extended ar member names (/, #1/), duplicate debian-binary / control.tar* / data.tar* members, missing data.tar*, and symlinks/hardlinks/traversal; _decompress_control_tar() guards control.tar.zst against decompression bombs using _bounded_read() (via Python 3.14 compression.zstd or zstd -d -c with proc.kill() on cap overflow); _validate_rpm_magic() enforces RPM lead magic; _validate_release_metadata() blocks header injection in APT Release fields; validation regexes across build_pkg_repos.py, build_homebrew_bottle.py, and r2_sync.py anchor strictly with \Z to reject trailing-newline bypasses; and _safe_mkdir() refuses pre-existing symlinks.
  • Two-phase atomic Cloudflare R2 sync (R2Client): Implements pure-stdlib AWS SigV4 over ssl.TLSVersion.TLSv1_3 minimum (_validate_endpoint blocks arbitrary endpoints outside production R2) with bounded transient retries (max_retries 0..5 on HTTP 429/502/503/504 and network OSError), rejects <!DOCTYPE/<!ENTITY XML responses (XML_FORBIDDEN_RE), validates object keys (validate_object_key) and prefixes (validate_prefix, safely skipping 0-byte / folder markers in list_objects()), verifies exact listed byte size on every pool download plus 32-hex MD5 ETag integrity on single-part objects (accommodating multipart ETags), and publishes via publish_repo_dir() in two phases: Phase A uploads immutable .deb/.rpm blobs first with Cache-Control: public, max-age=31536000, immutable; Phase B serves mutable metadata with Cache-Control: public, max-age=0, must-revalidate and uploads secondary metadata (Packages*, primary.xml.gz, gpg.key) first, then detached signatures (.asc, .gpg) BEFORE Release/repomd.xml (eliminating any CDN cache-skew window for DNF repo_gpgcheck=1), and single-object atomic InRelease very last via _phase_b_sort_key(). Public package reads on pkg.vulnparse-pin.com negotiate TLS 1.3 (with hybrid post-quantum key exchange where supported) by default while retaining a minTLS: 1.2 floor for enterprise/federal TLS-inspecting proxies, with r2.dev public access disabled and every package/index independently GPG-signed.

Homebrew Bottle & Formula Launcher Isolation (packaging/build_homebrew_bottle.py, packaging/Formula/vulnparse-pin.rb.tmpl)

  • Isolated -I execution & symlink-safe outputs: Precompiled bottle bin/vpp and bin/vulnparse-pin wrappers invoke python3.12 -I .../libexec/_vpp_launcher.py, and source-install fallback wrappers in packaging/Formula/vulnparse-pin.rb.tmpl likewise execute "#{libexec}/bin/python" -I "#{libexec}/bin/#{cmd}" (-I isolated mode ignoring ambient PYTHONPATH and user site-packages); render_formula() enforces _validate_ruby_safe_string() and https:// validation to prevent Ruby template injection; and build_homebrew_bottle.py performs pre-write os.lstat symlink checks on bottle tarballs, metadata JSON files, and rendered formula outputs.

CLI Parser & GHSA Fail-Closed Hardening (src/vulnparse_pin/cli/args.py, cli/commands.py, utils/ghsa_enrichment.py)

  • Parse-time os.lstat symlink deferral: valid_input_file() and valid_existing_path() (args.py) and vpp diff path checks (commands.py) inspect paths with os.lstat() without dereferencing symlinks, deferring symlink enforcement to PermFileHandler (--forbid-symlinks-read / --allow-symlinks-read).
  • Post--- option boundary protection (get_args): Restricts --debug-path-policy and _preprocess_legacy_argv() legacy flag rewriting strictly to tokens preceding --, preventing literal filenames after -- from spoofing flags.
  • Strict octal parse_mode & 0o000 preservation: parse_mode() rejects hex (0x/0X), leading signs (+/-), and underscores while bounding modes to 0o000..0o777; _OctalAwareDefaultsHelpFormatter renders defaults in octal (0o600/0o700); and commands.py checks is not None so explicit --file-mode 0o000 / --dir-mode 0o000 values are preserved rather than replaced with 0o600/0o700.
  • Stdlib-clean parser introspection (args.py) & fail-closed GHSA directories (ghsa_enrichment.py): valid_https_url() lazy-imports validate_webhook_https_url so build_parser(prog=...) runs under python3 -I without third-party dependencies during man page/completion generation; GHSAEnrichmentSource re-raises FilePathError when ensure_readable_dir() rejects a symlinked --ghsa advisory directory rather than returning False.