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, andvpp guistrictly read-only by default - Protect localhost HTTP surfaces (
vpp mcpandvpp 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 inbuild_pfh()areforbid_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, anddir_mode=0o700. - Ancestor symlink & loop checks (
_check_no_symlinks_or_loops): Validates every path segment from root to leaf againststat.S_ISLNKanderrno.ELOOP. On macOS (darwin),PermFileHandler(src/vulnparse_pin/io/pfhandler.py) andstorage/db.pyrecognize Apple’s three root-owned immutable Signed System Volume (SSV) root symlinks (/var -> private/var,/tmp -> private/tmp,/etc -> private/etcresolving 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()andopen_for_write_non_pfh()(src/vulnparse_pin/storage/db.py) acquire_UMASK_LOCKaroundos.umask()so staging temp files and directories are created0o600/0o700atomically beforeos.replace(). - DuckDB workspace guards (
VppDatabase):_validate_duckdb_paths()checks.vpp.db, its.waland.tmpsidecars, and all parent segments against symlinks;duckdb.connect()and transactions run underumask(0o177)+_UMASK_LOCKwith_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-fileis passed.
XML, SARIF, JSONL, Inventory, and Input Validation Hardening
- Hardened
lxmlXML parsing (NOdefusedxml):src/vulnparse_pin/parsers/_xml_security.pyreplacesdefusedxmlwithsafe_iterparse()andsniff_xml_head_events()backed bylxml.etree(resolve_entities=False,no_network=True,load_dtd=False,dtd_validation=False,huge_tree=False).inspect_xml_prolog()inspects up toMAX_XML_PROLOG_BYTES = 1 MiBbefore 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 whentag=is specified) and runsassert_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 KiBSchemaDetectorhead 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 viajson.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 anyRecursionErrortoValueError) 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 a64 MiBhard 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()andsafe_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.yamlpayloads are validated against JSON Schema Draft 2020-12 (assets.schema.json); rule promotion acquires an exclusivefcntl.flocklock on a0o600O_NOFOLLOWlockfile and performs atomic writes. _evaluate_exposure_honesty()preservesinternet_facing: nullon 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) orVP_SQLITE_HMAC_KEY(nvd_cache.sqlite3,epss_cache.sqlite3,kev_cache.sqlite3,ghsa_cache.sqlite3,osv_cache.sqlite3) is set, plainsha256downgrade 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_IWOTHare rejected immediately. - Per-hop HTTPS redirect validation:
_open_https_stream()usesallow_redirects=Falseand validates every redirectLocationtohttps://(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,000entries, and compression ratios> 500. - GHSA token validation: Rejects
\r/\nheader-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 MiBcap (MAX_MODEL_ARTIFACT_BYTES = 2 * 1024 * 1024),64 KiBsignature cap (MAX_SIGNATURE_ARTIFACT_BYTES), and64 MiBoptional ONNX cap (MAX_ONNX_ARTIFACT_BYTES), rejecting symlinks, symlink loops, non-regular files, and world-writable files (stat.S_IWOTH) viaO_NOFOLLOW. - Anti-downgrade HMAC enforcement: Every model artifact requires a companion
.sig.jsonverified via constant-timehmac.compare_digeston the SHA-256 digest; whenVP_MODEL_HMAC_KEY(MODEL_HMAC_ENV) is set, unsigned or plainsha256signatures fail closed unlessmode == "hmac-sha256". - Non-mutating default:
resolve_ml_policy()defaults toml.mode: shadow, recordingml_*attributions andpre_kev_*signals without altering baseline deterministic scores unlessactiveis 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:8787by default;validate_http_security()fails closed on non-loopback--hostbindings unless--auth-token-envnames an environment variable of at least 16 characters, verified viahmac.compare_digeston BearerAuthorization. - Generates a per-process 256-bit CSRF token (
secrets.token_urlsafe(32)) and verifiesX-VPP-CSRFviahmac.compare_digestonPOST /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, andCache-Control: no-store. - Enforces
HttpSecurityPolicyHostandOriginallowlists to block DNS-rebinding and cross-origin attacks, rejects duplicate security/framing headers (400), rejectsTransfer-Encoding(501), enforcesContent-Type: application/json(415), requiresContent-Length(411) bounded by4 MiB(413MAX_MESSAGE_BYTES), caps concurrent connections viathreading.BoundedSemaphore(32)(503), sets15.0ssocket timeouts (HTTP_SOCKET_TIMEOUT), and serializes JSON withallow_nan=False. - Runs read-only by default; opt-in
--allow-writeenables write-gated modals (gui_propose_deferral,gui_promote_shadow_asset) that record hash-chainedGUI_DEFERRAL_RECORDEDandGUI_ASSET_RULE_PROMOTEDevents inledger_eventswith full DuckDB + YAML atomic rollback on failure.
- Binds
- MCP Server (
src/vulnparse_pin/mcp/server.py,src/vulnparse_pin/mcp/tools.py):stdio(default) routes all logs/banners tostderrand bounds frames at4 MiB(MAX_MESSAGE_BYTES);streamable-httpenforces the samevalidate_http_security()/HttpSecurityPolicy,MAX_HTTP_CONCURRENCY = 32(503),HTTP_SOCKET_TIMEOUT = 15.0,415application/json,501Transfer-Encoding,400duplicate-header checks,MAX_BATCH_ITEMS = 64,MAX_JSON_DEPTH = 64,allow_nan=False, and sanitized-32603internal error responses.- Opens
.vpp.dbwithread_only=Trueby default, exposing 7 read-only tools and blocking the 3 mutating tools (ToolDisabledError/-32601) unless--allow-writeis passed. - Validates
--assets,--decisions, and--workspace-rootvia_validate_mcp_config_path()(_check_no_symlinks_or_loops+ PFH confinement). - Isolates read-only
vpp_diff_and_drift(re_enrich=True)by copying.vpp.dband.walinto0o600O_NOFOLLOW | O_EXCLtemp files;_assert_export_target_not_protected()blocksvpp_export_dossierfrom overwriting.vpp.db,.wal,.tmp, workspace config files, or.db/.duckdb/.wal/.sqlite/.sqlite3/.yaml/.ymlextensions. vpp_scan_and_diffruns_verify_sqlite_caches_fail_closed()before ingestion, mergesinline_decisionsviamerge_decisions_registries(), and invokesdelete_run()rollback on failure;vpp_propose_deferralsnapshots and rolls back both DuckDB tables anddecisions.yamlon error.
- Unified 3-Mode Workbench HTML (
src/vulnparse_pin/mcp/ui_app.py):- Zero-CDN DOM-only rendering (
document.createElement/textContent, zeroinnerHTML, zerohttp://orhttps://URLs). - Uses
Object.create(null)dictionaries to prevent prototype pollution,Number.isFiniteguards on bar charts/metrics,RPC_TIMEOUT_MS = 30000timeouts, andinitRpcId-gatedhostOriginlatching (blockingtools/callwithout a verified host origin inmcpmode). - Rejects CSS
url(,expression(, and@importtokens 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'inmcpandstatic-simulator;connect-src 'self'inloopback).
- Zero-CDN DOM-only rendering (
Reporting, CSV Export, Config & Webhook Hardening
- Jinja2
autoescape&md_escape:src/vulnparse_pin/reporting/renderer.pyconfigures Jinja2autoescape=select_autoescape(["html", "xml", "html.j2", "xml.j2", "htm", "htm.j2"])for HTML Dossiers/Roadmaps and appliesmd_escapeacross Markdown Dossiers, Roadmaps, PR diff comments, remediation plans, simulation reports, and legacymarkdown_report.py. Generated HTML (includingsimulator-html) contains zero external CDN scripts or stylesheets. - CSV formula-injection sanitization:
csv_exporter.pyneutralizes dangerous prefixes (=,+,-,@,\t,\r) and strips control characters by default. Disabling via--no-csv-sanitizerequires explicit--confirm-unsafe-csv(otherwise exits with code2). - Safe YAML & schema validation:
config_source.pyandassets_context.pyload YAML withruamel.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.pyenforceshttps://without embedded credentials,allow_redirects=False, pinned-IP DNS validation (_PinnedIPHTTPSAdapter), bounded payload sizes (262144bytes), and HMAC-SHA256 signatures viaVP_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): Everyuses:action reference is pinned to a 40-character hexadecimal commit SHA (zero mutable tag references), withpermissions: {}at workflow top level inci.yml,release.yml,release-rehearsal.yml, andcodeql.yml, narrow job-level permissions (including explicitpermissions: contents: readondocs-pages.ymlbuildand allrelease-rehearsal.ymljobs), andpersist-credentials: falseon everyactions/checkoutstep across all workflows.release-rehearsal.ymlautomatically rehearses the full build, SBOM, multi-arch.deb/.rpm, Homebrew bottle/formula (ruby -c), ephemeral-GPG APT/RPM signing (rpmsign/rpmkeys), root and offlineexamples/deploy/Dockerfile--read-onlysmoke tests, and strict MkDocs build on PRs and release branches with zero production secrets (scripts/check_release_drift.pyalso runs inrelease.ymlvalidation-gate, whilefinalize-releaseandpublish-ghcrrehearse downstream repo/formula signing andexamples/deploy/Dockerfileon-rcNtags as well as stable releases).codeql.ymlruns CodeQL analysis overactionsandpython, whilescorecard.ymlruns OpenSSF Scorecard onmainand uploads SARIF results to GitHub Code Scanning. - 100% hash-locked dependencies &
--no-isolationbuilds (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.ymlpassesrelease-requirements(requirements-sbom.txtandrequirements-runtime.txt) tofinalize-releaseand pins multi-arch@sha256:digests onubuntu:22.04androckylinux:9smoke-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 av*tag under Use workflow from -> Tags instead of passing a branch or tag input) and checksgithub.ref_type == "tag"plusgithub.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 asrefs/heads/v2.1.0. All 8actions/checkoutsteps pin directly to immutable${{ github.sha }}(eliminating CodeQL cache-poisoning and tag-TOCTOU risks), all 9 downstream jobs requirestartsWith(github.ref, 'refs/tags/v')with noworkflow_dispatchbypass (withpublish-pypi,publish-pkg-repos, andpublish-homebrew-tapadditionally requiringneeds.validation-gate.outputs.is_prerelease != 'true'),verify-tagunconditionally confirmsHEAD == github.sha == TAG_SHAvia a singlegit ls-remoteplusorigin/mainancestry (exportingvalidation-gate.outputs.release_sha, while downstream checkouts pin${{ github.sha }}directly rather than referencingrelease_sha), and context values pass throughenv:bindings rather than inline shell interpolation. - Header-only PEP 639
METADATA&[ui,mcp]CycloneDX SBOM copyleft gates (ci.yml,release.yml): Splits.dist-info/METADATAon the first blank line (\r?\n\r?\n) to inspect headers only forLicense-Expression: Apache-2.0,License-File: LICENSE/NOTICE,py.typed, and zero copyleft tokens (agpl|lgpl|gpl|affero). Bothci.ymlandrelease.ymlinstall${wheels[0]}[ui,mcp]into an isolated runtime virtualenv, generate a CycloneDX JSON SBOM viacyclonedx-py, and fail closed ifvulnparse-pin,mcp, orApache-2.0is 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, andpublish-homebrew-tapall depend onfinalize-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), andpublish-homebrew-tap(release-publish-homebrew-tap) all enforcecancel-in-progress: falseconcurrency serialization;publish-ghcrrestricts floating:latest,:major, and:major.minortags to stable versions (skipping-prereleases).build-homebrew-bottlesalignsarm64_sequoiabottle builds onmacos-15using an ephemeral build venv (BOTTLE_VENV) to avoid PEP 668EXTERNALLY-MANAGEDpip failures,MANIFEST.inbundlespackaging/generate_cli_assets.pyinside sdists for Homebrew source-fallback man-page and completion generation, anddocs-pages.ymlrestricts GitHub Pages uploads and deployments torefs/heads/mainwithcancel-in-progressscoped strictly to pull requests.finalize-releaseimportsGPG_PRIVATE_KEYinto an isolated0o700GNUPGHOMEwith agpgconf --kill gpg-agentcleanup trap, signsSHA256SUMSvia--pinentry-mode loopback --passphrase-fd 0 --digest-algo SHA256 --armor --detach-sign, verifiesgpg --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/wheelsoffline guard, Stage-1 audit &.dockerignoresecret protection (Dockerfile,examples/deploy/Dockerfile,.dockerignore): Both rootDockerfileandexamples/deploy/Dockerfilepin multi-archpython:3.12-slim@sha256:...digests in bothbuilderandruntimestages and install dependencies strictly with--require-hashes --only-binary=:all:. RootDockerfileStage 1 builds the local wheel inside/tmp/build-venvusingpackaging/requirements-build.txtand--no-isolation, installs runtime wheels frompackaging/requirements-{core,ui,runtime}.txtplus the SHA-256-verified local wheel, and optionally stages./wheelhouse/(COPY LICENSE wheelhous[e] /wheels/) while failing closed ifPIP_NO_INDEX=1lacks a valid localPIP_FIND_LINKSdirectory.examples/deploy/Dockerfileships standalone hash-lockedexamples/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 againstVPP_PYPI_VERSION. Both Dockerfiles run an inline Stage-1email.parser.HeaderParserzero-copyleft andApache-2.0audit over every.dist-info/METADATAfile, and.dockerignoreexcludesfuzz/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, release20261201) andnfpm(2.49.0) tarballs are pinned by lowercase 64-hex SHA-256 digests inpackaging/python_standalone.jsonand fetched bydownload_verified_artifact(), which enforceshttps://via_HttpsOnlyRedirectHandler, verifies digests in constant time (hmac.compare_digest), and replaces staging files atomically (os.replace). Runtime dependencies and the builtvulnparse-pinwheel are installed strictly from hash-lockedpackaging/requirements-ui.txtusing--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 706tarfile.data_filter(filter="data", failing closed if unavailable). - Isolated
-Iwrappers,umask-safe permissions & race-free nFPM output:write_posix_wrapper()writes/usr/bin/vppand/usr/bin/vulnparse-pinwrappers invokingexec /opt/vulnparse-pin/venv/bin/python3 -I -m vulnparse_pin.main "$@";normalize_tree_permissions()normalizes/opt/vulnparse-pindirectories/executables to0o755and regular files to0o644(skipping symlinks without following them) so packages built underumask 0077stay usable by non-root users;package_with_nfpm()stages.deb/.rpmoutputs in per-invocationtempfile.TemporaryDirectorydirectories and atomically promotes them withos.replace(). - Header-only RFC 822 copyleft audits (
audit_venv_zero_copyleft,audit_libexec_licenses): Usesemail.parser.HeaderParser(policy=email.policy.compat32)to inspectLicense,License-Expression,Classifier, andLicense-Fileheaders across every non-symlink.dist-info/METADATAfile inside bundled virtualenvs and Homebrewlibexec, failing closed on any copyleft token, empty metadata directories, or missing/non-Apache-2.0vulnparse-pinmetadata (plus missingtextualin Linux bundles and Homebrew CLI bottle builds) while ignoring unrelated fields such asProvides-Extra.
Ephemeral GPG Repository Signing & Atomic R2 Sync (packaging/build_pkg_repos.py, packaging/r2_sync.py)
- Ephemeral
0o700GPG signer, RPM 4.18+ macro safety & retry verification (EphemeralGPGSigner,compute_rpm_immutable_digest,build_rpm_repo): Requires non-emptyGPG_PRIVATE_KEYandGPG_PASSPHRASE(fail-closed), cachesgpg,gpgconf,rpmsign,rpmkeys, andrpmexecutables at__enter__, falls back to/tmpwheneverTMPDIRexceeds 50 bytes or contains unsafe characters (preserving the 108-byteSUN_LENUnix socket cap), pinsTMPDIRto the isolated0o700GNUPGHOME, validatesGNUPGHOMEand temporary passphrase file paths againstSAFE_RPM_PATH_RE(^[A-Za-z0-9._/+-]+\Z) before RPM macro expansion, passes passphrases via--passphrase-fd 0(and zeroed0o600temp files unlinked infinallyforrpmsignusing RPM 4.18+-compatible_gpg_sign_cmd_extra_args,_gpg_path, and_gpg_digest_algomacros), killsgpg-agentviagpgconf --kill gpg-agenton exit, and verifies generated signatures fail-closed (gpg --batch --verifyon APTInRelease/Release.gpgand RPMrepomd.xml.asc;verify_rpm_signature()imports the public key into an isolated0o700ephemeralrpmdband runsrpmkeys --checksig/rpm -K, acceptingrc == 0only when signature OK is present andNOT OK,MISSING KEYS,NOKEY, andBADare absent).build_rpm_repo()preserves historicalexisting_rpm_filesbyte-for-byte (is_new=False) and signs only newly built (is_new=True) RPMs; on release retries where a newly built unsigned.rpmshares a filename with an already-signed pool.rpm, idempotent reuse is permitted only whensign_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), andverify_rpm_signature()succeeds on the pool.rpm(failing closed on any payload change, unsigned pool file, or foreign key). - Pure-stdlib
.deb/.rpmvalidation,.zstbomb defense,\Zregexes & header injection guards:parse_deb_control_fields()parsesararchives andcontrol.tar*with strict size caps (MAX_CONTROL_ARCHIVE_BYTES,MAX_DECOMPRESSED_TAR_BYTES,MAX_CONTROL_FILE_BYTES), rejecting GNU/BSD extendedarmember names (/,#1/), duplicatedebian-binary/control.tar*/data.tar*members, missingdata.tar*, and symlinks/hardlinks/traversal;_decompress_control_tar()guardscontrol.tar.zstagainst decompression bombs using_bounded_read()(via Python 3.14compression.zstdorzstd -d -cwithproc.kill()on cap overflow);_validate_rpm_magic()enforces RPM lead magic;_validate_release_metadata()blocks header injection in APTReleasefields; validation regexes acrossbuild_pkg_repos.py,build_homebrew_bottle.py, andr2_sync.pyanchor strictly with\Zto reject trailing-newline bypasses; and_safe_mkdir()refuses pre-existing symlinks. - Two-phase atomic Cloudflare R2 sync (
R2Client): Implements pure-stdlib AWS SigV4 overssl.TLSVersion.TLSv1_3minimum (_validate_endpointblocks arbitrary endpoints outside production R2) with bounded transient retries (max_retries0..5on HTTP429/502/503/504and networkOSError), rejects<!DOCTYPE/<!ENTITYXML responses (XML_FORBIDDEN_RE), validates object keys (validate_object_key) and prefixes (validate_prefix, safely skipping 0-byte/folder markers inlist_objects()), verifies exact listed bytesizeon every pool download plus 32-hex MD5 ETag integrity on single-part objects (accommodating multipart ETags), and publishes viapublish_repo_dir()in two phases: Phase A uploads immutable.deb/.rpmblobs first withCache-Control: public, max-age=31536000, immutable; Phase B serves mutable metadata withCache-Control: public, max-age=0, must-revalidateand uploads secondary metadata (Packages*,primary.xml.gz,gpg.key) first, then detached signatures (.asc,.gpg) BEFORERelease/repomd.xml(eliminating any CDN cache-skew window for DNFrepo_gpgcheck=1), and single-object atomicInReleasevery last via_phase_b_sort_key(). Public package reads onpkg.vulnparse-pin.comnegotiate TLS 1.3 (with hybrid post-quantum key exchange where supported) by default while retaining aminTLS: 1.2floor for enterprise/federal TLS-inspecting proxies, withr2.devpublic 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
-Iexecution & symlink-safe outputs: Precompiled bottlebin/vppandbin/vulnparse-pinwrappers invokepython3.12 -I .../libexec/_vpp_launcher.py, and source-install fallback wrappers inpackaging/Formula/vulnparse-pin.rb.tmpllikewise execute"#{libexec}/bin/python" -I "#{libexec}/bin/#{cmd}"(-Iisolated mode ignoring ambientPYTHONPATHand user site-packages);render_formula()enforces_validate_ruby_safe_string()andhttps://validation to prevent Ruby template injection; andbuild_homebrew_bottle.pyperforms pre-writeos.lstatsymlink 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.lstatsymlink deferral:valid_input_file()andvalid_existing_path()(args.py) andvpp diffpath checks (commands.py) inspect paths withos.lstat()without dereferencing symlinks, deferring symlink enforcement toPermFileHandler(--forbid-symlinks-read/--allow-symlinks-read). - Post-
--option boundary protection (get_args): Restricts--debug-path-policyand_preprocess_legacy_argv()legacy flag rewriting strictly to tokens preceding--, preventing literal filenames after--from spoofing flags. - Strict octal
parse_mode&0o000preservation:parse_mode()rejects hex (0x/0X), leading signs (+/-), and underscores while bounding modes to0o000..0o777;_OctalAwareDefaultsHelpFormatterrenders defaults in octal (0o600/0o700); andcommands.pychecksis not Noneso explicit--file-mode 0o000/--dir-mode 0o000values are preserved rather than replaced with0o600/0o700. - Stdlib-clean parser introspection (
args.py) & fail-closed GHSA directories (ghsa_enrichment.py):valid_https_url()lazy-importsvalidate_webhook_https_urlsobuild_parser(prog=...)runs underpython3 -Iwithout third-party dependencies during man page/completion generation;GHSAEnrichmentSourcere-raisesFilePathErrorwhenensure_readable_dir()rejects a symlinked--ghsaadvisory directory rather than returningFalse.