vigievuln 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -2
- package/README.md +10 -4
- package/lib/airgap-project.js +35 -7
- package/lib/applicability-evidence.js +12 -0
- package/lib/artifacts/applications.js +54 -0
- package/lib/artifacts/cve-view.js +108 -0
- package/lib/artifacts/enrichment.js +86 -0
- package/lib/artifacts/go-main-identity.js +45 -0
- package/lib/artifacts/go-publisher-advisories.js +24 -0
- package/lib/artifacts/index.js +272 -0
- package/lib/artifacts/publisher-advisories.js +12 -0
- package/lib/artifacts/remediation-report.js +48 -0
- package/lib/artifacts/report-inventory.js +26 -0
- package/lib/artifacts/report.js +191 -0
- package/lib/artifacts/risk-report.js +120 -0
- package/lib/artifacts/sbom.js +68 -0
- package/lib/artifacts/scan.js +401 -0
- package/lib/cache-archive-sqlite.js +41 -25
- package/lib/charts.js +124 -32
- package/lib/cli-command-routing.js +20 -6
- package/lib/cli-groups.js +2 -1
- package/lib/cli-image.js +206 -0
- package/lib/codecs/binary/elf-metadata.js +42 -0
- package/lib/codecs/binary/go-buildinfo.js +37 -0
- package/lib/codecs/binary/metadata.js +7 -0
- package/lib/codecs/binary/scan.js +14 -13
- package/lib/codecs/binary/sniff.js +16 -15
- package/lib/codecs/binary.codec.js +22 -2
- package/lib/codecs/gradle/parse.js +63 -2
- package/lib/codecs/gradle/versionless.js +175 -0
- package/lib/codecs/gradle.codec.js +20 -3
- package/lib/codecs/index.js +2 -2
- package/lib/csaf-export.js +13 -6
- package/lib/cve-download.js +33 -29
- package/lib/cve-match.js +10 -0
- package/lib/cve-packages-proxy.js +19 -0
- package/lib/cve-report.js +273 -165
- package/lib/deps-descriptor.js +25 -3
- package/lib/diagnostics.js +12 -0
- package/lib/diff.js +0 -0
- package/lib/epss.js +6 -6
- package/lib/euvd.js +34 -4
- package/lib/finding-enrichment.js +165 -0
- package/lib/finding-summary.js +4 -3
- package/lib/i18n.js +34 -9
- package/lib/image-network.js +54 -0
- package/lib/image-references.js +203 -0
- package/lib/image-registry.js +385 -0
- package/lib/image-update.js +39 -0
- package/lib/json-export.js +50 -8
- package/lib/kev.js +6 -6
- package/lib/maven-bom.js +2 -1
- package/lib/merge-sources.js +3 -0
- package/lib/native-advisories.js +9 -7
- package/lib/native-cna-identities.js +12 -0
- package/lib/native-package-match.js +159 -0
- package/lib/native-source-prepare.js +60 -0
- package/lib/nvd.js +34 -23
- package/lib/osv.js +33 -14
- package/lib/project-descriptor.js +3 -2
- package/lib/provenance.js +8 -2
- package/lib/providers/alpine.js +8 -0
- package/lib/providers/common.js +11 -3
- package/lib/providers/debian.js +11 -0
- package/lib/providers/euvd.js +2 -1
- package/lib/providers/freexian.js +13 -0
- package/lib/providers/github.js +1 -0
- package/lib/providers/go.js +2 -1
- package/lib/providers/index.js +18 -14
- package/lib/providers/nginx.js +5 -0
- package/lib/providers/nvd.js +1 -1
- package/lib/providers/osv.js +1 -1
- package/lib/providers/osvdb.js +2 -2
- package/lib/proxy-throttle.js +89 -29
- package/lib/purl.js +10 -2
- package/lib/record-freshness.js +22 -0
- package/lib/report-notices.js +47 -0
- package/lib/report-time.js +45 -0
- package/lib/request-failure.js +22 -0
- package/lib/resource-cache/engine.js +130 -26
- package/lib/resource-cache/snapshot-projection.js +33 -0
- package/lib/resource-cache/validate.js +22 -5
- package/lib/risk-evidence.js +18 -0
- package/lib/sarif-export.js +17 -9
- package/lib/sbom-export.js +32 -12
- package/lib/source-health.js +25 -8
- package/lib/source-image-scan.js +57 -0
- package/lib/source-profile.js +6 -3
- package/lib/system-inventory/advisories.js +169 -0
- package/lib/system-inventory/alpine-tracker.js +47 -0
- package/lib/system-inventory/collect.js +118 -0
- package/lib/system-inventory/current-debian.js +99 -0
- package/lib/system-inventory/distribution-sources.js +132 -0
- package/lib/system-inventory/freexian-ela.js +32 -0
- package/lib/system-inventory/freexian-release-evidence.js +35 -0
- package/lib/system-inventory/freexian-tracker.js +72 -0
- package/lib/system-inventory/historical-debian.js +196 -0
- package/lib/system-inventory/index.js +2 -0
- package/lib/system-inventory/nginx-advisories.js +39 -0
- package/lib/system-inventory/rpm-storage.js +86 -0
- package/lib/system-inventory/targeted.js +70 -0
- package/lib/system-inventory/versions.js +59 -0
- package/lib/transitive.js +11 -2
- package/lib/ui.js +8 -5
- package/lib/unmanaged.js +1 -1
- package/package.json +12 -3
- package/vigievuln.js +204 -95
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog — VigieVuln
|
|
2
2
|
|
|
3
|
+
## [1.3.0] — 2026-11-17
|
|
4
|
+
|
|
5
|
+
- Add opt-in Docker/OCI, registry, rootfs and publisher-SBOM audits, with system-package and application findings.
|
|
6
|
+
- Add image report sections, update guidance, offline inventory transfer and digest-based cache reuse.
|
|
7
|
+
- Improve ELF/Go identification and add the application icon to Windows executables.
|
|
8
|
+
- Support literal Groovy `ext` versions, scoped implicit Spring Boot BOMs and conservative recovery of versionless Gradle declarations.
|
|
9
|
+
- Preserve all inventoried Maven/npm/PyPI versions and vulnerability links in CycloneDX exports.
|
|
10
|
+
- Add dated application benchmarks and a same-inventory pip-audit comparison.
|
|
11
|
+
- Reuse stable advisory records with explicit refresh controls and apply proxy retry limits per request.
|
|
12
|
+
|
|
3
13
|
## [1.2.1] — 2026-11-04
|
|
4
14
|
|
|
5
15
|
- Report unreadable Maven manifests and native binaries as incomplete coverage, preserve other inventory entries, and bound binary hashing and PE metadata reads.
|
|
@@ -11,7 +21,7 @@
|
|
|
11
21
|
- Apply Go workspace replacements, preserve conditional Python and NuGet versions, and collect Python dependency groups with explicit coverage warnings.
|
|
12
22
|
- Suggest `vigievuln setup` during direct scans and refresh the committed report samples, terminal demo and screenshots.
|
|
13
23
|
|
|
14
|
-
## [1.2.0] —
|
|
24
|
+
## [1.2.0] — 2026-11-04
|
|
15
25
|
|
|
16
26
|
- Match VigieVuln Maven/npm advisories through the configured official proxy and offline cache, including partial ranges and `VV:CVE-…` identifiers.
|
|
17
27
|
- Revalidate local caches after four hours, or on demand with `--force-update`; retain offline snapshots and avoid redownloading unchanged CVE releases.
|
|
@@ -36,7 +46,7 @@
|
|
|
36
46
|
- Refresh the example audit reports and their screenshot.
|
|
37
47
|
- Send the CLI version to the hosted proxy and explain how to update when the server requires a newer version.
|
|
38
48
|
|
|
39
|
-
## [1.1.2] —
|
|
49
|
+
## [1.1.2] — 2026-10-28
|
|
40
50
|
|
|
41
51
|
- Fix Windows account sessions when the home directory uses an 8.3 short path, including GitHub Actions temporary directories.
|
|
42
52
|
- Require explicit `--config` for repository configuration and bound Composer validation and JAR decompression.
|
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
[](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml)
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
**VigieVuln** is a polyglot dependency auditor
|
|
13
|
+
**VigieVuln 1.3.0** is a polyglot dependency auditor for code audits.
|
|
14
14
|
|
|
15
15
|
It scans dependencies and **9 CMS/frameworks** in one pass without build tools, supports **air-gapped** workflows, detects private packages, binaries and certificates, and produces HTML, JSON and other reports.
|
|
16
16
|
|
|
@@ -31,6 +31,7 @@ It scans dependencies and **9 CMS/frameworks** in one pass without build tools,
|
|
|
31
31
|
- **CMS & frameworks audited as instances**; Symfony, Laravel, WordPress, Drupal, Joomla, PrestaShop, TYPO3, Magento/Adobe Commerce and SPIP with per-instance inventory (core, plugins, themes, bundles, components) → [the dedicated guide](docs/CMS-FRAMEWORKS.md)
|
|
32
32
|
- **Crypto material**; committed **certificates**, **private vs public keys** across PEM/OpenSSH/PuTTY/PGP and JKS/PKCS#12 keystores.
|
|
33
33
|
- **Air-gapped flow**; **zero network under `--offline`** → [Benchmark](docs/BENCHMARK.md) · [Air-gapped](#air-gapped-audits)
|
|
34
|
+
- **Native image audits**; Docker/OCI archives, registries and rootfs inventories without Docker; Linux packages, ELF/Go metadata and publisher SBOMs, with explicit coverage. Image analysis in source scans is off by default; use `--images` or the separate `vigievuln image` command → [image guide](docs/IMAGES.md)
|
|
34
35
|
- **Hosted proxy with a verified account**; `--set-proxy-cache vigievuln` → [hosted proxy](docs/USAGE.md#hosted-vigievuln-proxy)
|
|
35
36
|
- **Project monitoring**; `vigievuln watch ./project --name 'My Project'` — one free project with up to **100 distinct direct dependency coordinates** → [monitoring guide](docs/USAGE.md#project-monitoring)
|
|
36
37
|
- **Shared cache for a scanner fleet**; `vigievuln serve-cache` + `--proxy-cache` → [cache usage](docs/USAGE.md#shared-proxy-cache-server-serve-cache----proxy-cache)
|
|
@@ -84,8 +85,13 @@ The proxy receives package coordinates and CVE identifiers, not source code. Cac
|
|
|
84
85
|
|
|
85
86
|
These are standalone reports from real source scans, generated on **2026-11-04** with VigieVuln **1.2.1**. Dubbo uses the hosted proxy; the CMS sample uses its local cache offline and focuses on PHP dependencies. Missing Wordfence/Drupal advisory and WordPress checksum inputs are explicitly marked incomplete. [Sample scope, sources and reproduction commands](docs/samples/README.md).
|
|
86
87
|
|
|
87
|
-
|
|
88
|
-
|
|
88
|
+
### Resolution and coverage
|
|
89
|
+
|
|
90
|
+
- **Gradle:** without a lock, POM-based resolution can differ from Gradle. Locks cover only their recorded configurations, which may mix runtime, tests and build tools.
|
|
91
|
+
- **Python:** exact pins are checked; transitives require a supported resolved lockfile or complete inventory.
|
|
92
|
+
- **Coverage:** missing metadata or unavailable advisory sources can cause omissions or false positives. Review report warnings.
|
|
93
|
+
|
|
94
|
+
See [usage](docs/USAGE.md) and [measured results](docs/BENCHMARK.md).
|
|
89
95
|
|
|
90
96
|
## Why use vigievuln for code audits?
|
|
91
97
|
|
|
@@ -166,7 +172,7 @@ The HTML report opens in any browser, contains every detail (CVSS vectors, refer
|
|
|
166
172
|
See the [CMS coverage limits](docs/CMS-FRAMEWORKS.md#coverage-and-its-current-limits)
|
|
167
173
|
and [shared-cache operating limits](docs/USAGE.md#shared-proxy-cache-server-serve-cache--proxy-cache).
|
|
168
174
|
|
|
169
|
-
vigievuln doesn't just read the `composer.json` under a WordPress or Drupal site — it inventories the **instance**: core, plugins, themes, bundles and framework components with their observed versions, attributes
|
|
175
|
+
vigievuln doesn't just read the `composer.json` under a WordPress or Drupal site — it inventories the **instance**: core, plugins, themes, bundles and framework components with their observed versions, attributes dependency findings where ownership is established, and reports each instance in its own sub-chapter — synthesis included even when it comes out clean. Any recognized layout is activated by the default `--app-plugins auto`; `none` opts out.
|
|
170
176
|
|
|
171
177
|
| Product | Inventory | Advisory lane |
|
|
172
178
|
| --- | --- | --- |
|
package/lib/airgap-project.js
CHANGED
|
@@ -7,7 +7,8 @@ const {openCacheDb}=require('./cache-db');
|
|
|
7
7
|
const {packageName}=require('./advisory-store');
|
|
8
8
|
const packageScope=(ecosystem,name)=>'project-package:'+JSON.stringify([ecosystem,ecosystem==='Maven'?name:packageName(ecosystem,name)]);
|
|
9
9
|
|
|
10
|
-
function buildProjectScope(resolved,{applications=[],cves=[]}={}){
|
|
10
|
+
function buildProjectScope(resolved,{applications=[],cves=[],imageReferences=[],images=true,preferSbom=false}={}){
|
|
11
|
+
const refs=require("./deps-descriptor").serializeImageReferences(imageReferences,{images});
|
|
11
12
|
const {osvEcosystemFor,osvPkgName}=require('./osv');
|
|
12
13
|
const packages=new Map();
|
|
13
14
|
for(const d of resolved.values()){
|
|
@@ -16,12 +17,33 @@ function buildProjectScope(resolved,{applications=[],cves=[]}={}){
|
|
|
16
17
|
if(typeof name!=='string'||!name||name.includes('undefined'))continue;
|
|
17
18
|
packages.set(JSON.stringify([ecosystem,name]),{ecosystem,name});
|
|
18
19
|
}
|
|
19
|
-
const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],retainAllNvd:applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
|
|
20
|
+
const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],imageReferences:refs,imagePreferSbom:!!preferSbom,retainAllNvd:refs.length>0||applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
|
|
20
21
|
return project;
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
function imageInventoryKeys(item,preferSbom=false){
|
|
25
|
+
const crypto=require('node:crypto'),hash=x=>crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
|
26
|
+
const p=require('./image-registry').parseReference(item.reference),canonical=`${p.registry}/${p.repository}@${p.reference}`;
|
|
27
|
+
return [hash([canonical,item.platform||null,!!preferSbom]),hash([item.reference,item.platform||null,!!preferSbom])];
|
|
28
|
+
}
|
|
29
|
+
function validateImageSnapshotCompleteness(scope,repository){
|
|
30
|
+
const refs=require('./deps-descriptor').serializeImageReferences(scope?.imageReferences);
|
|
31
|
+
if(scope?.imageReferences != null && (!Array.isArray(scope.imageReferences) || scope.imageReferences.length!==refs.length))throw Error('invalid prepared image references');
|
|
32
|
+
for(const item of refs){
|
|
33
|
+
const entries=imageInventoryKeys(item,scope.imagePreferSbom).map(key=>repository.get('image-inventory',key)).filter(Boolean);
|
|
34
|
+
if(!entries.length)throw Error(`prepared image inventory is missing: ${item.reference}`);
|
|
35
|
+
let valid=false;
|
|
36
|
+
for(const entry of entries)try{require('./artifacts/scan').validateSnapshot(entry.value);valid=true;break}catch{}
|
|
37
|
+
if(!valid)throw Error(`prepared image inventory is invalid: ${item.reference}`);
|
|
38
|
+
}
|
|
39
|
+
return {images:refs.length};
|
|
40
|
+
}
|
|
41
|
+
|
|
23
42
|
function buildProjectSnapshot(sourceDir,targetDir,project){
|
|
24
|
-
if(project?.schema!==1||!Array.isArray(project.packages)
|
|
43
|
+
if(project?.schema!==1||!Array.isArray(project.packages)||(!project.packages.length && !project.imageReferences?.length))throw Error('invalid or empty prepared project scope');
|
|
44
|
+
const imageRefs=require('./deps-descriptor').serializeImageReferences(project.imageReferences);
|
|
45
|
+
if(project.imageReferences?.length && imageRefs.length!==project.imageReferences.length)throw Error('invalid prepared image reference');
|
|
46
|
+
if(imageRefs.length)validateImageSnapshotCompleteness(project,require('./cache-repository').createCacheRepository(sourceDir));
|
|
25
47
|
const db=openCacheDb({cacheDir:targetDir});
|
|
26
48
|
const quote=s=>`'${s.replace(/'/g,"''")}'`;
|
|
27
49
|
try{
|
|
@@ -59,13 +81,19 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
|
|
|
59
81
|
INSERT INTO advisory_queries SELECT q.* FROM source.advisory_queries q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
|
|
60
82
|
INSERT INTO advisory_query_ids SELECT q.* FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
|
|
61
83
|
INSERT INTO advisory_coverage SELECT * FROM source.advisory_coverage WHERE source<>'osv';
|
|
62
|
-
INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index') AND NOT (namespace='catalogue' AND key IN ('euvd-targeted','epss'));
|
|
84
|
+
INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index','image-inventory') AND NOT (namespace='catalogue' AND (key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss') OR key GLOB 'image-tags-*'));
|
|
63
85
|
INSERT INTO cache_snapshots SELECT * FROM source.cache_snapshots;
|
|
64
86
|
INSERT INTO cve_lookup SELECT l.* FROM source.cve_lookup l WHERE EXISTS(SELECT 1 FROM wanted_packages w WHERE w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1)))));
|
|
65
87
|
INSERT INTO package_versions SELECT * FROM source.package_versions;
|
|
66
88
|
INSERT INTO resource_bodies SELECT * FROM source.resource_bodies;
|
|
67
89
|
INSERT INTO resource_chunks SELECT * FROM source.resource_chunks;
|
|
68
90
|
INSERT INTO resources SELECT * FROM source.resources;`);
|
|
91
|
+
// Image inventories are scoped to reviewed references and platforms; other
|
|
92
|
+
// projects' registry identities and inventories must not enter the archive.
|
|
93
|
+
const insertImage=db.prepare("INSERT OR IGNORE INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace='image-inventory' AND key=?");
|
|
94
|
+
for(const item of imageRefs)for(const prefer of [false,true])for(const key of imageInventoryKeys(item,prefer))insertImage.run(key);
|
|
95
|
+
const insertRegistry=db.prepare("INSERT OR IGNORE INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key=?");
|
|
96
|
+
for(const item of imageRefs){const ref=require('./image-registry').parseReference(item.reference),key='image-tags-'+require('node:crypto').createHash('sha256').update(`${ref.registry}/${ref.repository}`).digest('hex');insertRegistry.run(key);}
|
|
69
97
|
if(!project.retainAllNvd)db.exec("UPDATE advisory_coverage SET complete=0,entry_json=json_set(entry_json,'$.complete',json('false')) WHERE source IN ('cveproject','cveproject-legacy')");
|
|
70
98
|
// A project index proves coverage only for its exported package buckets.
|
|
71
99
|
// Preserve the source timestamp and never claim global index completeness.
|
|
@@ -88,7 +116,7 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
|
|
|
88
116
|
// These per-CVE enrichments may contain observations from other projects.
|
|
89
117
|
// Keep only CVEs actually encountered while preparing this descriptor.
|
|
90
118
|
const keep=new Set(Array.isArray(project.cves)?project.cves:[]),zlib=require('node:zlib');
|
|
91
|
-
const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','epss')").all();
|
|
119
|
+
const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss')").all();
|
|
92
120
|
const insertCache=db.prepare('INSERT INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES(?,?,?,?,?,?,?,?)');
|
|
93
121
|
for(const row of cached){
|
|
94
122
|
const raw=row.encoding==='json+deflate'?zlib.inflateRawSync(row.payload,{maxOutputLength:134217728}):row.encoding==='json'?row.payload:null;
|
|
@@ -112,6 +140,6 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
|
|
|
112
140
|
db.exec('DETACH DATABASE source');
|
|
113
141
|
db.exec('PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE');
|
|
114
142
|
}finally{db.close()}
|
|
115
|
-
return {packages:project.packages.length,fullNvd:!!project.retainAllNvd};
|
|
143
|
+
return {packages:project.packages.length,images:imageRefs.length,fullNvd:!!project.retainAllNvd};
|
|
116
144
|
}
|
|
117
|
-
module.exports={buildProjectScope,buildProjectSnapshot,packageScope};
|
|
145
|
+
module.exports={buildProjectScope,buildProjectSnapshot,validateImageSnapshotCompleteness,imageInventoryKeys,packageScope};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Preserve independent applicability proofs when sources describe one finding.
|
|
3
|
+
function applicabilityEvidence(...records){
|
|
4
|
+
const proofs=new Map();
|
|
5
|
+
for(const c of records){
|
|
6
|
+
for(const item of [...(c?.applicabilityEvidence||[]),...['historical','vendor','publisher'].flatMap(kind=>c?.[kind+'Evidence']?[{kind,evidence:c[kind+'Evidence']}]:[])]){
|
|
7
|
+
if(item && typeof item.kind==='string' && item.evidence && typeof item.evidence==='object')proofs.set(JSON.stringify(item),item);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
return [...proofs.values()];
|
|
11
|
+
}
|
|
12
|
+
module.exports={applicabilityEvidence};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Installed application metadata in an extracted image. Never execute package code.
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const {makeDepRecord} = require('../dep-record');
|
|
5
|
+
const MAX_METADATA = 16 * 1024 * 1024;
|
|
6
|
+
const handlers = [
|
|
7
|
+
{id:'npm', matches:(n,fp)=>n==='package.json' && fp.split(path.sep).includes('node_modules'), parse:(text)=>{const j=JSON.parse(text);return [{ecosystem:'npm',name:j.name,version:j.version}];}},
|
|
8
|
+
{id:'pypi', matches:(n,fp)=>(n==='METADATA' && /\.dist-info$/i.test(path.basename(path.dirname(fp)))) || (n==='PKG-INFO' && /\.egg-info$/i.test(path.basename(path.dirname(fp)))), parse:(text)=>{const name=/^Name:\s*(.+)$/im.exec(text)?.[1]?.trim(), version=/^Version:\s*(.+)$/im.exec(text)?.[1]?.trim();return [{ecosystem:'pypi',name,version}];}},
|
|
9
|
+
{id:'composer', matches:(n,fp)=>n==='installed.json' && path.basename(path.dirname(fp))==='composer', parse:(text)=>{const j=JSON.parse(text), pkgs=Array.isArray(j)?j:j.packages;if(!Array.isArray(pkgs))throw Error('missing packages');return pkgs.map(p=>({ecosystem:'composer',name:p.name,version:p.version}));}},
|
|
10
|
+
{id:'composer-php', matches:(n,fp)=>n==='installed.php' && path.basename(path.dirname(fp))==='composer', parse:(text)=>{
|
|
11
|
+
// Composer's generated PHP is data, but parse literal version entries only.
|
|
12
|
+
// Never evaluate PHP or interpolate its expressions.
|
|
13
|
+
const re=/['"]([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)['"]\s*=>\s*(?:array\s*\(|\[)/g, starts=[]; let match;
|
|
14
|
+
while((match=re.exec(text))) starts.push({name:match[1],start:re.lastIndex});
|
|
15
|
+
return starts.map(item=>{let depth=1,end=item.start,quote=null;for(;end<text.length && depth;end++){const c=text[end];if(quote){if(c==='\\')end++;else if(c===quote)quote=null;continue}if(c==='\"'||c==="'"){quote=c;continue}if(c==='('||c==='[')depth++;else if(c===')'||c===']')depth--;}const block=depth?'':text.slice(item.start,end-1);const version=/['"]pretty_version['"]\s*=>\s*['"]([^'"\r\n]+)['"]/.exec(block)?.[1];return {ecosystem:'composer',name:item.name,version};});
|
|
16
|
+
}},
|
|
17
|
+
{id:'ruby', matches:(n,fp)=>n.endsWith('.gemspec') && path.dirname(fp).split(path.sep).includes('specifications'), parse:(text)=>{const name=/\b(?:s|spec)\.name\s*=\s*["']([^"']+)["']/.exec(text)?.[1],version=/\b(?:s|spec)\.version\s*=\s*(?:Gem::Version\.new\(\s*)?["']([^"']+)["']/.exec(text)?.[1];return [{ecosystem:'ruby',name,version}];}},
|
|
18
|
+
{id:'nuget', matches:n=>n.endsWith('.deps.json'), parse:(text)=>{const j=JSON.parse(text);return Object.entries(j.libraries||{}).filter(([,v])=>v?.type==='package').map(([key])=>{const i=key.lastIndexOf('/');return {ecosystem:'nuget',name:key.slice(0,i),version:key.slice(i+1)};});}},
|
|
19
|
+
];
|
|
20
|
+
function valid(x) {return x && typeof x.name==='string' && x.name.trim() && typeof x.version==='string' && x.version.trim() && !/[\r\n\0]/.test(x.name+x.version);}
|
|
21
|
+
const archiveCollectors = [{id:'jar', async collect(root) {return require('../codecs/maven/jar-scan').scanEmbeddedJars(root,{defaultExcludes:false});}}];
|
|
22
|
+
async function collectInstalledApplications(root,opts={}) {
|
|
23
|
+
const activeHandlers=opts.handlers || handlers, archives=opts.archiveCollectors || archiveCollectors;
|
|
24
|
+
for(const h of activeHandlers) if(!h || typeof h.id!=='string' || typeof h.matches!=='function' || typeof h.parse!=='function') throw Error('Invalid installed metadata handler');
|
|
25
|
+
for(const h of archives) if(!h || typeof h.id!=='string' || typeof h.collect!=='function') throw Error('Invalid installed archive collector');
|
|
26
|
+
const deps=new Map(),warnings=[], coverage={files:0,records:0,handlers:{}}; const stack=[root], max=opts.maxMetadataBytes ?? MAX_METADATA;
|
|
27
|
+
function warning(fp,error) {warnings.push({type:'dependency-coverage',reason:'installed-metadata-error',manifestPath:fp,message:`installed metadata incomplete for ${fp}: ${error.message}`});}
|
|
28
|
+
function add(item,fp,source) {if(item.ecosystem==='composer' && typeof item.name==='string' && !item.namespace) {const slash=item.name.indexOf('/');if(slash>0)item={...item,namespace:item.name.slice(0,slash),name:item.name.slice(slash+1)};}if(!valid(item)){warning(fp,Error('missing package name or version'));return;} const dep=makeDepRecord({...item,manifestPath:fp,provenance:'installed',scope:'transitive'});dep.coordKey=`installed:${fp}:${item.ecosystem}:${item.name}@${item.version}`;dep.installEvidence={path:fp,source};deps.set(dep.coordKey,dep);}
|
|
29
|
+
while(stack.length) {const dir=stack.pop();let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){warning(dir,e);continue}for(const entry of entries){const fp=path.join(dir,entry.name);if(entry.isDirectory()){stack.push(fp);continue}if(!entry.isFile())continue;if(entry.name==='installed.php' && entries.some(e=>e.name==='installed.json' && e.isFile()))continue;for(const h of activeHandlers){if(!h.matches(entry.name,fp))continue;coverage.files++;coverage.handlers[h.id]=(coverage.handlers[h.id]||0)+1;try{const st=fs.statSync(fp);if(st.size>max)throw Error(`metadata exceeds ${max} bytes`);const parsed=h.parse(fs.readFileSync(fp,'utf8'));for(const item of parsed)add(item,fp,h.id)}catch(e){warning(fp,e)}break;}}}
|
|
30
|
+
for(const collector of archives){try{const result=await collector.collect(root,opts);warnings.push(...(result.warnings||[]));coverage.handlers[collector.id]=(result.deps||[]).length;for(const item of result.deps||[]){const fp=item.manifestPaths?.[0]||root;if(!item.namespace && item.ecosystem==='maven'){warning(fp,Error('archive has no complete Maven coordinate'));continue}add({ecosystem:item.ecosystem,namespace:item.namespace,name:item.name,version:item.version},fp,collector.id);}}catch(e){warning(root,e)}}coverage.records=deps.size;coverage.complete=warnings.length===0;return {deps,warnings,coverage};
|
|
31
|
+
}
|
|
32
|
+
// Reclassify only an unidentifiable top-level JAR whose exact installed owner
|
|
33
|
+
// has itself been assessed. Corrupt archives and nested contents remain gaps.
|
|
34
|
+
function classifyOwnedArchiveWarnings(warnings, packages, assessedPackages) {
|
|
35
|
+
const assessed = assessedPackages instanceof Set ? assessedPackages : new Set();
|
|
36
|
+
const byPath = new Map();
|
|
37
|
+
const normalize = value => {
|
|
38
|
+
if(typeof value!=="string" || !value || value.includes("!") || value.includes("\\") || value.includes("\0") || value.split('/').includes('..'))return null;
|
|
39
|
+
return path.posix.normalize('/'+value.replace(/^\/+/,''));
|
|
40
|
+
};
|
|
41
|
+
for(const pkg of packages || []) {
|
|
42
|
+
if(!pkg?.manager || !pkg?.name || !pkg?.version || !assessed.has(`${pkg.manager}:${pkg.name}@${pkg.version}`))continue;
|
|
43
|
+
for(const owned of pkg.ownedPaths||[]) {const p=normalize(owned);if(p && !byPath.has(p))byPath.set(p,pkg);}
|
|
44
|
+
}
|
|
45
|
+
const remaining=[],informational=[];
|
|
46
|
+
for(const warning of warnings || []) {
|
|
47
|
+
const p=normalize(warning?.manifestPath);
|
|
48
|
+
const eligible=warning?.reason==='installed-metadata-error' && /\.jar$/i.test(p||'') && typeof warning.message==='string' && warning.message.endsWith(': archive has no complete Maven coordinate');
|
|
49
|
+
const owner=eligible?byPath.get(p):null;
|
|
50
|
+
if(owner)informational.push({warning,owner:{manager:owner.manager,name:owner.name,version:owner.version},path:p});else remaining.push(warning);
|
|
51
|
+
}
|
|
52
|
+
return {warnings:remaining,informational};
|
|
53
|
+
}
|
|
54
|
+
module.exports={collectInstalledApplications,handlers,archiveCollectors,classifyOwnedArchiveWarnings,MAX_METADATA};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// A presentation projection: distribution verdicts remain unchanged in the
|
|
3
|
+
// canonical findings and image inventory. Only explicit CVE relationships can
|
|
4
|
+
// produce CVE rows, with per-CVE enrichment kept separate.
|
|
5
|
+
const {computePriority}=require('../priority');
|
|
6
|
+
const CVE=/^CVE-\d{4}-\d{4,}$/i;
|
|
7
|
+
function isCve(id){return typeof id==='string' && CVE.test(id);}
|
|
8
|
+
function ids(cve){return [...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])].filter(isCve).map(id=>id.toUpperCase()))];}
|
|
9
|
+
function rel(cve,id){return [cve.id,...(cve.aliases||[])].some(x=>String(x).toUpperCase()===id)?'identity':'upstream';}
|
|
10
|
+
function physical(dep,id){return JSON.stringify([dep.artifactTargetId,dep.ecosystem,dep.manager,dep.namespace || dep.groupId,dep.name || dep.artifactId,dep.version,dep.architecture,dep.artifactPath || dep.manifestPaths?.[0] || null,id]);}
|
|
11
|
+
function advisory(match,id){
|
|
12
|
+
const c=match.cve,notice=match.advisoryId || c.id;
|
|
13
|
+
if(!notice || String(notice).toUpperCase()===id)return null;
|
|
14
|
+
return {id:notice,fixVersion:c.fixVersion || null,description:c.description || c.summary || null,sourceURL:c.advisorySource || null,relationship:rel(c,id)};
|
|
15
|
+
}
|
|
16
|
+
function project(match,id){
|
|
17
|
+
const original=match.cve,relation=rel(original,id),record=(original.nvdEvidence?.records||[]).find(r=>String(r.id).toUpperCase()===id);
|
|
18
|
+
const perCve=(original.cveEvidence||[]).find(r=>String(r.id).toUpperCase()===id);
|
|
19
|
+
const identity=relation==='identity';
|
|
20
|
+
const c={...original,id,aliases:[],upstream:[],related:[],distributionAdvisories:[]};
|
|
21
|
+
// Preserve advisory identifiers from an observed OSV/GHSA source across the
|
|
22
|
+
// CVE-only projection; an alias alone does not prove a source was consulted.
|
|
23
|
+
const observedSources=String(match.source||'').split('+');
|
|
24
|
+
c.sourceGhsaIds=observedSources.some(s=>/^(?:osv|ghsa|github-publisher)$/i.test(s))?[...new Set([original.id,...(original.aliases||[]),match.advisoryId].filter(x=>typeof x==='string' && /^GHSA-[a-z0-9-]+$/i.test(x)))]:[];
|
|
25
|
+
const gnas=new Set(observedSources.map(s=>/^GCVE:GNA-(\d+)$/i.exec(s)?.[1]).filter(x=>x!==undefined));
|
|
26
|
+
c.sourceGcveIds=[...new Set([...(original.sourceGcveIds||[]),original.gcveEvidence?.kind==='derived-alias'?null:original.gcve,original.id,match.advisoryId].filter(x=>{const m=typeof x==='string'&&/^GCVE-(\d+)-[a-z0-9\-/]+$/i.exec(x);return m && gnas.has(m[1]);}))];
|
|
27
|
+
// Aggregated advisory risk can reflect another CVE. Replace it with this CVE's
|
|
28
|
+
// own evidence before computing priority.
|
|
29
|
+
for(const key of ['score','severity','severitySource','scoreSource','cvssVector','cvssVersion','cwes','nvdRefs','nvdEvidence','riskEvidence','kev','kevEvidence','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','epssEvidence','priority','description','summary','published','modified','advisorySource','osvRefs','fixVersion','cveEvidence','euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence','euvdDetails','euvdDetailsEvidence'])delete c[key];
|
|
30
|
+
const euvd=require('../euvd').normalizeEuvdDetailDates(perCve?.euvdDetails);
|
|
31
|
+
const hasOwn=identity && String(original.id||'').toUpperCase()===id;
|
|
32
|
+
const ownScore=hasOwn && original.score!=null, nvdScore=!ownScore && record?.score!=null, euvdScore=!ownScore && !nvdScore && euvd?.score!=null;
|
|
33
|
+
const scoreSource=ownScore?'original':nvdScore?'nvd':euvdScore?'euvd':null;
|
|
34
|
+
if(ownScore && original.scoreSource)c.scoreSource=original.scoreSource;
|
|
35
|
+
c.score=ownScore?original.score:nvdScore?record.score:euvdScore?euvd.score:null;
|
|
36
|
+
const knownOriginal=hasOwn && original.severity && original.severity!=='UNKNOWN';
|
|
37
|
+
const knownNvd=record?.severity && record.severity!=='UNKNOWN';
|
|
38
|
+
c.severity=knownOriginal?original.severity:knownNvd && scoreSource!=='euvd'?record.severity:scoreSource==='euvd' && euvd?.severity?euvd.severity:'UNKNOWN';
|
|
39
|
+
if(knownOriginal && original.severitySource)c.severitySource=original.severitySource;
|
|
40
|
+
if(hasOwn && String(original.riskEvidence?.id||'').toUpperCase()===id && ((ownScore && original.scoreSource===original.riskEvidence.source) || (knownOriginal && original.severitySource===original.riskEvidence.source)))c.riskEvidence={...original.riskEvidence};
|
|
41
|
+
c.description=record?.description || euvd?.description || (hasOwn ? original.description : '') || '';
|
|
42
|
+
if(euvd){c.euvdDetails={...euvd};if(euvdScore){c.scoreSource='euvd';if(!knownOriginal && c.severity!=='UNKNOWN')c.severitySource='euvd';c.riskEvidence={source:'euvd',id,relationship:'identity'};}}
|
|
43
|
+
const vectorSource=scoreSource==='original'?original:scoreSource==='nvd'?record:scoreSource==='euvd'?euvd:null;
|
|
44
|
+
for(const k of ['cvssVector','cvssVersion'])if(vectorSource?.[k]!=null)c[k]=vectorSource[k];
|
|
45
|
+
for(const k of ['cwes','published','modified']){const v=record?.[k] ?? euvd?.[k] ?? (hasOwn ? original[k] : null);if(v!=null)c[k]=v;}
|
|
46
|
+
if(record){c.nvdEvidence={...record,records:[{...record}]};if(record.references)c.nvdRefs=record.references;
|
|
47
|
+
if(!c.riskEvidence && (nvdScore || (!knownOriginal && knownNvd && scoreSource!=='euvd')))c.riskEvidence={source:'nvd',id,relationship:'identity'};}
|
|
48
|
+
if(perCve){c.cveEvidence=[{...perCve,...(euvd?{euvdDetails:euvd}:{})}];for(const key of ['kev','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence','euvdDetailsEvidence'])if(perCve[key]!==undefined)c[key]=perCve[key];}
|
|
49
|
+
if(perCve?.gcveAlias){c.gcveAlias=perCve.gcveAlias;if(hasOwn && original.gcve && original.gcve!==perCve.gcveAlias){c.gcve=original.gcve;if(original.gcveEvidence)c.gcveEvidence=original.gcveEvidence;}else c.gcve=perCve.gcveAlias;}
|
|
50
|
+
// Older exported inventories can contain single-CVE evidence but not cveEvidence.
|
|
51
|
+
for(const [evidenceKey,keys] of [['kevEvidence',['kev','kevDateAdded','kevDueDate','kevRansomware']],['epssEvidence',['epssScore','epssPercentile']]]){
|
|
52
|
+
if(String(original[evidenceKey]?.id||'').toUpperCase()===id)for(const key of keys)if(c[key]===undefined && original[key]!==undefined)c[key]=original[key];
|
|
53
|
+
}
|
|
54
|
+
// Legacy findings may have only one CVE and no per-CVE observation array.
|
|
55
|
+
// Their original risk is safe to reuse only when it cannot represent another
|
|
56
|
+
// linked CVE and no explicit evidence points elsewhere.
|
|
57
|
+
if(hasOwn && !perCve && ids(original).length===1){
|
|
58
|
+
for(const key of ['euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence'])if(original[key]!==undefined)c[key]=original[key];
|
|
59
|
+
for(const [evidenceKey,keys] of [['kevEvidence',['kev','kevDateAdded','kevDueDate','kevRansomware']],['epssEvidence',['epssScore','epssPercentile']]]){
|
|
60
|
+
const evidenceId=original[evidenceKey]?.id;
|
|
61
|
+
if(!evidenceId || String(evidenceId).toUpperCase()===id)for(const key of keys)if(c[key]===undefined && original[key]!==undefined)c[key]=original[key];
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const notice=advisory(match,id);if(notice)c.distributionAdvisories.push(notice);
|
|
65
|
+
c.fixVersion=notice?.fixVersion || (hasOwn ? original.fixVersion || null : null);
|
|
66
|
+
c.priority=computePriority(c);
|
|
67
|
+
return {...match,cve:c};
|
|
68
|
+
}
|
|
69
|
+
function merge(target,incoming){
|
|
70
|
+
const a=target.cve,b=incoming.cve;
|
|
71
|
+
a.applicabilityEvidence=require('../applicability-evidence').applicabilityEvidence(a,b);
|
|
72
|
+
a.sourceGhsaIds=[...new Set([...(a.sourceGhsaIds||[]),...(b.sourceGhsaIds||[])])];
|
|
73
|
+
a.sourceGcveIds=[...new Set([...(a.sourceGcveIds||[]),...(b.sourceGcveIds||[])])];
|
|
74
|
+
// Source applicability evidence survives consolidation with a distribution
|
|
75
|
+
// advisory that projects to the same CVE row.
|
|
76
|
+
for(const key of ['historicalEvidence','vendorEvidence'])if(!a[key] && b[key])a[key]=b[key];
|
|
77
|
+
target.source=[...new Set([target.source,incoming.source].flatMap(s=>String(s||'').split('+')).filter(Boolean))].sort().join('+');
|
|
78
|
+
for(const notice of b.distributionAdvisories){if(!a.distributionAdvisories.some(n=>n.id===notice.id && n.fixVersion===notice.fixVersion && n.sourceURL===notice.sourceURL))a.distributionAdvisories.push(notice);}
|
|
79
|
+
for(const field of ['references','relatedAdvisories'])a[field]=[...new Map([...(a[field]||[]),...(b[field]||[])].map(item=>[typeof item==='string'?item:item?.url,item]).filter(([url])=>url)).values()];
|
|
80
|
+
const fixes=[...new Set([a.fixVersion ?? null,b.fixVersion ?? null,...a.distributionAdvisories.map(n=>n.fixVersion ?? null)])];a.fixVersion=fixes.length===1 ? fixes[0] : null;
|
|
81
|
+
const compatibleScore=a.score==null || b.score==null || a.score===b.score;
|
|
82
|
+
const compatibleSeverity=!a.severity || a.severity==='UNKNOWN' || !b.severity || b.severity==='UNKNOWN' || a.severity===b.severity;
|
|
83
|
+
let acceptedRisk=false;
|
|
84
|
+
if((!a.severity || a.severity==='UNKNOWN') && b.severity && b.severity!=='UNKNOWN' && compatibleScore){a.severity=b.severity;if(b.severitySource)a.severitySource=b.severitySource;acceptedRisk=true;}
|
|
85
|
+
if(a.score==null && b.score!=null && compatibleSeverity){a.score=b.score;if(b.scoreSource)a.scoreSource=b.scoreSource;acceptedRisk=true;}
|
|
86
|
+
if(acceptedRisk && !a.riskEvidence && b.riskEvidence)a.riskEvidence={...b.riskEvidence};
|
|
87
|
+
if(compatibleScore && compatibleSeverity)for(const key of ['cvssVector','cvssVersion'])if(!a[key] && b[key])a[key]=b[key];
|
|
88
|
+
for(const key of ['description','cwes','nvdRefs','nvdEvidence','published','modified','kev','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','euvd','certfr','gcve','gcveEvidence','gcveAlias','euvdEvidence','certfrEvidence','euvdDetails','euvdDetailsEvidence'])if((a[key]==null || a[key]==='' || Array.isArray(a[key])&&!a[key].length) && b[key]!=null)a[key]=b[key];
|
|
89
|
+
for(const entry of b.cveEvidence||[]){
|
|
90
|
+
if(!Array.isArray(a.cveEvidence))a.cveEvidence=[];
|
|
91
|
+
const existing=a.cveEvidence.find(x=>x.id===entry.id);
|
|
92
|
+
if(!existing)a.cveEvidence.push({...entry});
|
|
93
|
+
else for(const [key,value] of Object.entries(entry))if((existing[key]==null || existing[key]==='') && value!=null)existing[key]=value;
|
|
94
|
+
}
|
|
95
|
+
a.priority=computePriority(a);
|
|
96
|
+
}
|
|
97
|
+
function projectImageCves(matches){
|
|
98
|
+
const output=[],byKey=new Map();
|
|
99
|
+
for(const match of matches||[]){
|
|
100
|
+
if(!match?.dep?.artifactTargetId || match.dep.ecosystem!=='system'){output.push(match);continue;}
|
|
101
|
+
for(const id of ids(match.cve)){
|
|
102
|
+
const key=physical(match.dep,id),row=project(match,id),existing=byKey.get(key);
|
|
103
|
+
if(existing)merge(existing,row);else{byKey.set(key,row);output.push(row);}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return output;
|
|
107
|
+
}
|
|
108
|
+
module.exports={projectImageCves};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Enrichment adds independent risk evidence; it never changes OS advisory verdicts.
|
|
3
|
+
const {createCacheRepository}=require('../cache-repository');
|
|
4
|
+
const {getCacheDir}=require('../cache-directory');
|
|
5
|
+
function cveIds(match){return [...new Set([match.cve?.id,...(match.cve?.aliases||[]),...(match.cve?.upstream||[])].filter(id=>/^CVE-\d{4}-\d{4,}$/i.test(id||'')))];}
|
|
6
|
+
function cveId(match){return cveIds(match)[0]||null;}
|
|
7
|
+
function relationship(cve,id){return cve.id===id || (cve.aliases||[]).includes(id) ? 'identity' : 'upstream';}
|
|
8
|
+
function proxies(matches){return matches.flatMap(m=>cveIds(m).map(id=>({...m,cve:{id}})));}
|
|
9
|
+
function cveEvidence(cve,id){if(!Array.isArray(cve.cveEvidence))cve.cveEvidence=[];let value=cve.cveEvidence.find(x=>x.id===id);if(!value){value={id};cve.cveEvidence.push(value);}return value;}
|
|
10
|
+
// Hosted proxies offer a targeted KEV operation. Persist both positive and
|
|
11
|
+
// negative observations so an air-gapped replay does not need a global catalog.
|
|
12
|
+
async function enrichKevCopies(copies,opts){
|
|
13
|
+
const repo=createCacheRepository(opts.cacheDir||getCacheDir()),wanted=[...new Set(copies.map(m=>m.cve.id))];
|
|
14
|
+
const targeted=repo.get('catalogue','kev-targeted')?.value || {entries:{}};
|
|
15
|
+
const hosted=opts.hostedProxy ?? require('../providers').hasHostedProxy();let failure=null;
|
|
16
|
+
if(hosted && !opts.offline){
|
|
17
|
+
try{
|
|
18
|
+
for(let i=0;i<wanted.length;i+=100){
|
|
19
|
+
const group=wanted.slice(i,i+100),res=await require('../providers').getResource('kev','cves',{ids:group},{fetcher:opts.fetcher,noStore:true,streaming:true});
|
|
20
|
+
if(!res.ok)throw Error(`KEV HTTP ${res.status}`);const body=await res.json();if(!Array.isArray(body?.items))throw Error('invalid KEV response');
|
|
21
|
+
const seen=new Map();for(const row of body.items){if(!row || !group.includes(row.cve) || seen.has(row.cve) || (row.kev!=null && (typeof row.kev!=='object'||Array.isArray(row.kev))))throw Error('invalid KEV record');seen.set(row.cve,row.kev||null);}
|
|
22
|
+
const stamp=Date.parse(res.headers?.get?.('x-fad-proxy-fetched-at')||'');const fetchedAt=Number.isFinite(stamp)&&stamp>0&&stamp<=Date.now()+300000?stamp:null,stale=fetchedAt===null || res.headers?.get?.('x-fad-proxy')==='stale';
|
|
23
|
+
for(const id of group)targeted.entries[id]={item:seen.get(id)||null,fetchedAt,stale};
|
|
24
|
+
repo.put('catalogue','kev-targeted',targeted);
|
|
25
|
+
}
|
|
26
|
+
}catch(error){failure=`KEV targeted lookup failed: ${error.message}`;}
|
|
27
|
+
}else if(!opts.offline)await require('../kev').enrichKev(copies,{...opts,hostedProxy:false});
|
|
28
|
+
else await require('../kev').enrichKev(copies,{...opts,offline:true});
|
|
29
|
+
const bulk=repo.get('catalogue','kev')?.value,hasBulk=!!bulk?.body?.byId && typeof bulk.body.byId==='object';let missing=0,stale=0;
|
|
30
|
+
for(const copy of copies){const saved=targeted.entries[copy.cve.id];if(saved && (opts.offline||hosted)){
|
|
31
|
+
if(saved.stale || !Number.isFinite(saved.fetchedAt) || saved.fetchedAt<=0 || saved.fetchedAt>Date.now()+300000)stale++;const item=saved.item;if(item){copy.cve.kev=true;copy.cve.kevDateAdded=item.dateAdded;copy.cve.kevDueDate=item.dueDate;copy.cve.kevRansomware=item.ransomware;}
|
|
32
|
+
}else if(!hasBulk)missing++;
|
|
33
|
+
}
|
|
34
|
+
return {complete:!failure && !missing && !stale,reason:failure || (missing?`KEV observations unavailable for ${missing} eligible CVE(s).`:`KEV observations stale for ${stale} eligible CVE(s).`)};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const enrichmentAdapters=[
|
|
38
|
+
{id:'kev',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};const state=await enrichKevCopies(copies,opts);const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.kev){const record=cveEvidence(m.cve,id);for(const key of ['kev','kevDateAdded','kevDueDate','kevRansomware'])if(item[key]!==undefined)record[key]=item[key];}}const hit=cveIds(m).map(id=>byId.get(id)).find(x=>x?.cve.kev);if(hit?.cve.kev){m.cve.kev=true;m.cve.kevDateAdded=hit.cve.kevDateAdded;m.cve.kevDueDate=hit.cve.kevDueDate;m.cve.kevRansomware=hit.cve.kevRansomware;m.cve.kevEvidence={source:'kev',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}}return state;}},
|
|
39
|
+
{id:'epss',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};await require('../epss').enrichEpss(copies,opts);const cache=createCacheRepository(opts.cacheDir||getCacheDir()).get('catalogue','epss')?.value;const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.epssScore!=null || item?.epssPercentile!=null){const record=cveEvidence(m.cve,id);if(item.epssScore!=null)record.epssScore=item.epssScore;if(item.epssPercentile!=null)record.epssPercentile=item.epssPercentile;}}const hit=cveIds(m).map(id=>byId.get(id)).filter(Boolean).sort((a,b)=>(b.cve.epssScore??-1)-(a.cve.epssScore??-1))[0];if(hit?.cve.epssScore!=null){m.cve.epssScore=hit.cve.epssScore;m.cve.epssEvidence={source:'epss',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}if(hit?.cve.epssPercentile!=null)m.cve.epssPercentile=hit.cve.epssPercentile;}return {complete:matches.every(m=>cveIds(m).every(id=>Object.hasOwn(cache?.entries||{},id))),reason:'EPSS scores are not cached for all eligible CVEs.'};}},
|
|
40
|
+
{id:'nvd',async run(matches,opts){
|
|
41
|
+
const copies=proxies(matches).map(m=>({...m,cve:{id:m.cve.id,severity:'UNKNOWN'}}));if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};
|
|
42
|
+
const nvd=require('../nvd'),absent=new Set(),failures=[];
|
|
43
|
+
await nvd.enrichMatches(copies,{...opts,onAbsent:id=>absent.add(id),onFailure:(id,reason)=>failures.push({id,reason}),onProgress:(completed,total)=>opts.onEnrichmentProgress?.({source:'nvd',completed,total})});
|
|
44
|
+
if(opts.offline)for(const copy of copies)if(nvd.hasCachedAbsence(copy.cve.id,{cacheDir:opts.cacheDir,offline:true}))absent.add(copy.cve.id);
|
|
45
|
+
const byId=new Map(copies.map(x=>[x.cve.id,x]));
|
|
46
|
+
for(const m of matches){
|
|
47
|
+
const ids=cveIds(m), enriched=ids.map(id=>byId.get(id)).filter(x=>x?.source?.split('+').includes('nvd'));
|
|
48
|
+
const records=enriched.map(x=>({id:x.cve.id,relationship:relationship(m.cve,x.cve.id),severity:x.cve.severity||null,score:x.cve.score??null,
|
|
49
|
+
cvssVector:x.cve.cvssVector||null,cvssVersion:x.cve.cvssVersion||null,description:x.cve.description||null,
|
|
50
|
+
cwes:x.cve.cwes||[],references:x.cve.nvdRefs||[],published:x.cve.published||null,modified:x.cve.modified||null}));
|
|
51
|
+
if(records.length){m.cve.nvdEvidence={...records[0],records};const sources=new Set(String(m.source||'').split('+').filter(Boolean));sources.add('nvd');m.source=[...sources].sort().join('+');}
|
|
52
|
+
// A single explicitly related CVE can fill missing display metadata without
|
|
53
|
+
// changing the distribution's advisory identity or affected/fixed verdict.
|
|
54
|
+
// Multi-CVE advisories retain separate records and never acquire a made-up
|
|
55
|
+
// aggregate severity or score.
|
|
56
|
+
if(ids.length===1 && enriched.length===1){
|
|
57
|
+
const item=enriched[0].cve;let riskFilled=false;
|
|
58
|
+
if((!m.cve.severity || String(m.cve.severity).toUpperCase()==='UNKNOWN') && item.severity && item.severity!=='UNKNOWN'){
|
|
59
|
+
m.cve.severity=item.severity; m.cve.severitySource='nvd'; riskFilled=true;
|
|
60
|
+
}
|
|
61
|
+
if(m.cve.score==null && typeof item.score==='number' && Number.isFinite(item.score)){m.cve.score=item.score;m.cve.scoreSource='nvd';riskFilled=true;}
|
|
62
|
+
if(riskFilled)m.cve.riskEvidence={source:'nvd',id:item.id,relationship:relationship(m.cve,item.id)};
|
|
63
|
+
if(!m.cve.cvssVector && item.cvssVector)m.cve.cvssVector=item.cvssVector;
|
|
64
|
+
if(!m.cve.cvssVersion && item.cvssVersion)m.cve.cvssVersion=item.cvssVersion;
|
|
65
|
+
if(!m.cve.cwes?.length && item.cwes?.length)m.cve.cwes=item.cwes;
|
|
66
|
+
if(!m.cve.nvdRefs?.length && item.nvdRefs?.length)m.cve.nvdRefs=item.nvdRefs;
|
|
67
|
+
if(!m.cve.published && item.published)m.cve.published=item.published;
|
|
68
|
+
if(!m.cve.modified && item.modified)m.cve.modified=item.modified;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const complete=matches.every(m=>cveIds(m).every(id=>absent.has(id)||m.cve.nvdEvidence?.records.some(record=>record.id===id)));
|
|
72
|
+
return {complete,result:copies.every(copy=>absent.has(copy.cve.id))?'no-match':undefined,reason:failures.length?`NVD lookup failed: ${[...new Set(failures.map(f=>f.reason))].join('; ')} (${failures.length} CVE(s)).`:'NVD metadata unavailable for some eligible CVEs.'};
|
|
73
|
+
}},
|
|
74
|
+
];
|
|
75
|
+
async function enrichArtifactFindings(matches,opts={}) {
|
|
76
|
+
const registry=opts.enrichmentAdapters||enrichmentAdapters;if(!Array.isArray(registry)||registry.some(a=>!a||typeof a.id!=='string'||typeof a.run!=='function'))throw Error('Invalid enrichment adapter registry');
|
|
77
|
+
const selected=opts.enrich || ['nvd','kev','epss','gcve','euvd','certfr'];if(!Array.isArray(selected))throw Error('Invalid enrichment selection');
|
|
78
|
+
const coverage=[],warnings=[];
|
|
79
|
+
const european=opts.europeanAdapters || require('../finding-enrichment').europeanAdapters;
|
|
80
|
+
const europeanIds=new Set(european.map(a=>a.id));
|
|
81
|
+
for(const id of selected.filter(id=>!europeanIds.has(id))){if(opts[id]===false){const reason=`${id} is excluded by the selected source profile.`;coverage.push({capability:'sources',collector:id,execution:'not-applicable',result:'not-consulted',expected:false,reason});continue;}const adapter=registry.find(a=>a.id===id);if(!adapter)throw Error(`Unknown enrichment adapter ${id}`);try{opts.onEnrichmentProgress?.({source:id,completed:0,total:matches.length});const result=await adapter.run(matches,opts);opts.onEnrichmentProgress?.({source:id,completed:matches.length,total:matches.length});if(!result||typeof result.complete!=='boolean')throw Error('Invalid enrichment result');coverage.push({capability:'sources',collector:id,execution:result.notApplicable?'not-applicable':result.complete?'completed':'partial',result:result.notApplicable?'not-applicable':result.complete?(result.result||'available'):'indeterminate',...(result.notApplicable?{expected:false,reason:result.reason}:!result.complete?{reason:result.reason}:{})});if(!result.complete)warnings.push({type:'source-unavailable',capability:'sources',source:id,message:result.reason||`${id} unavailable`});}catch(e){coverage.push({capability:'sources',collector:id,execution:'partial',result:'indeterminate',reason:e.message});warnings.push({type:'source-unavailable',capability:'sources',source:id,message:`${id}: ${e.message}`});}}
|
|
82
|
+
const selectedEuropean=european.filter(a=>selected.includes(a.id) || (a.parent && selected.includes(a.parent)));
|
|
83
|
+
if(selectedEuropean.length){const result=await require('../finding-enrichment').enrichEuropeanFindings(matches,{...opts,europeanAdapters:selectedEuropean});coverage.push(...result.coverage);warnings.push(...result.warnings);}
|
|
84
|
+
return {coverage,warnings};
|
|
85
|
+
}
|
|
86
|
+
module.exports={enrichArtifactFindings,enrichmentAdapters,cveId};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Bind a Go main module to a version only when independent Go proxy VCS
|
|
3
|
+
// provenance matches the clean revision embedded in the binary. OCI labels
|
|
4
|
+
// propose a lookup; neither a label nor an image tag proves a version alone.
|
|
5
|
+
const {makeDepRecord}=require('../dep-record');
|
|
6
|
+
const VERSION=/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+incompatible)?$/;
|
|
7
|
+
function repo(value){try{const u=new URL(value);if(u.protocol!=='https:'||u.username||u.password||u.port||u.search||u.hash)return null;const pathname=u.pathname.replace(/\/+$/,'').replace(/\.git$/i,'');if(!pathname||pathname==='/'||pathname.split('/').some(x=>x==='.'||x==='..'))return null;return `${u.hostname.toLowerCase()}${pathname}`;}catch{return null;}}
|
|
8
|
+
function escapeModule(value){return value.replace(/[A-Z]/g,c=>'!'+c.toLowerCase());}
|
|
9
|
+
function tagRef(module,source,version){const suffix=module.slice(source.length).split('/').filter(Boolean);if(/^v(?:[2-9]|[1-9]\d+)$/.test(suffix.at(-1)||''))suffix.pop();return `refs/tags/${suffix.length?suffix.join('/')+'/':''}${version}`;}
|
|
10
|
+
async function resolveGoMainIdentities(target,options={}){
|
|
11
|
+
const metadata=target?.metadata||{},labels=metadata.imageConfig?.labels||{},version=labels['org.opencontainers.image.version'],source=repo(labels['org.opencontainers.image.source']);
|
|
12
|
+
const outputs=[],warnings=[],seen=new Set();let candidates=0,unavailable=0,conflicts=0,stale=0;
|
|
13
|
+
if(!source || !VERSION.test(version||'') || !/^sha256:[a-f0-9]{64}$/i.test(metadata.configDigest||''))return {deps:outputs,warnings,coverage:{collector:'go-main-identity',execution:'not-applicable',result:'no-candidate',count:0}};
|
|
14
|
+
const lookup=options.lookup || (async(module,ver)=>{const providers=require('../providers'),response=await providers.getResource('go','module-info',{module:escapeModule(module),version:ver},{offline:false,fetcher:options.fetcher,...(options.store?{store:options.store}:{})});if(!response.ok)throw Error(`Go proxy HTTP ${response.status}`);const proxied=providers.hasProxyRoute(),stamp=Date.parse(response.headers.get('x-fad-proxy-fetched-at')||'');if(proxied&&(!Number.isFinite(stamp)||stamp<=0||stamp>Date.now()+300000))throw Error('Go proxy evidence has no valid observation timestamp');return {info:await response.json(),observedAt:proxied?stamp:Date.now(),stale:proxied&&response.headers.get('x-fad-proxy')==='stale'};});
|
|
15
|
+
let repository;const cacheRepo=()=>repository||(repository=require('../cache-repository').createCacheRepository(options.cacheDir||require('../cache-directory').getCacheDir()));
|
|
16
|
+
const cache=new Map();
|
|
17
|
+
for(const binary of target.deps||[]){
|
|
18
|
+
if(binary.ecosystem!=='binary')continue;const go=binary.binaryMetadata?.go,settings=go?.settings||{},main=(go?.modules||[]).filter(m=>m.kind==='mod');
|
|
19
|
+
if(main.length!==1 || main[0].version!=='(devel)' || main[0].replace || !main[0].path || !(main[0].path===source || main[0].path.startsWith(source+'/')))continue;
|
|
20
|
+
const module=main[0].path,revision=settings['vcs.revision'],binaryPath=binary.artifactPath||binary.manifestPaths?.[0];
|
|
21
|
+
if(settings.vcs!=='git'||settings['vcs.modified']!=='false'||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(revision||'')||!binaryPath||!/^[a-f0-9]{64}$/i.test(binary.hashes?.sha256||'')){conflicts++;continue;}
|
|
22
|
+
if((settings.GOOS && metadata.platform?.os && settings.GOOS!==metadata.platform.os)||(settings.GOARCH && metadata.platform?.architecture && settings.GOARCH!==metadata.platform.architecture)){conflicts++;continue;}
|
|
23
|
+
candidates++;let info,observation,key=JSON.stringify([module,version,source,revision.toLowerCase()]);try{
|
|
24
|
+
if(options.offline){const saved=cacheRepo().get('go-main-identity',key);if(!saved)throw Error('no cached Go proxy version evidence');observation={info:saved.value,observedAt:saved.fetchedAt,stale:saved.stale};}
|
|
25
|
+
else{const requestKey=`${module}\0${version}`;if(!cache.has(requestKey))cache.set(requestKey,Promise.resolve().then(()=>lookup(module,version)));const value=await cache.get(requestKey);observation=value?.info?value:{info:value,observedAt:Date.now(),stale:false};}
|
|
26
|
+
if(!Number.isFinite(observation.observedAt)||observation.observedAt<=0||observation.observedAt>Date.now()+300000)throw Error('invalid Go proxy evidence timestamp');
|
|
27
|
+
info=observation.info;
|
|
28
|
+
}catch(error){
|
|
29
|
+
let saved;try{if(!options.offline)saved=cacheRepo().get('go-main-identity',key);}catch{}
|
|
30
|
+
if(saved && Number.isFinite(saved.fetchedAt) && saved.fetchedAt>0 && saved.fetchedAt<=Date.now()+300000){observation={info:saved.value,observedAt:saved.fetchedAt,stale:true};info=observation.info;warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version refresh failed for ${module}@${version}; cached evidence is stale: ${error.message}`});}
|
|
31
|
+
else{unavailable++;warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version evidence unavailable for ${module}@${version}: ${error.message}`});continue;}
|
|
32
|
+
}
|
|
33
|
+
const origin=info?.Origin||{};
|
|
34
|
+
if(info?.Version!==version||origin.VCS!=='git'||repo(origin.URL)!==source||origin.Ref!==tagRef(module,source,version)||String(origin.Hash||'').toLowerCase()!==revision.toLowerCase()){conflicts++;if(!options.offline)try{cacheRepo().delete('go-main-identity',key);}catch{}continue;}
|
|
35
|
+
if(observation.stale){stale++;if(!warnings.some(w=>w.source==='go-proxy' && w.message.includes(`${module}@${version}`)))warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version evidence is stale for ${module}@${version}.`});}
|
|
36
|
+
if(!options.offline)try{cacheRepo().put('go-main-identity',key,info,{fetchedAt:observation.observedAt,stale:!!observation.stale,metadata:{source:'go-module-proxy',module,version}});}catch(error){warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy-cache',message:`Could not cache Go module version evidence: ${error.message}`});}
|
|
37
|
+
const occurrence=`${binaryPath}\0${module}\0${version}`;if(seen.has(occurrence))continue;seen.add(occurrence);
|
|
38
|
+
const dep=makeDepRecord({ecosystem:'go',name:module,version,manifestPath:binaryPath,provenance:'binary-module',scope:'runtime'});
|
|
39
|
+
dep.coordKey=`binary-module:${binaryPath}:${module}@${version}`;
|
|
40
|
+
dep.binaryEvidence={binaryPath,source:'go-vcs-and-module-proxy',binarySha256:binary.hashes.sha256,original:main[0],revision,modified:false,configDigest:metadata.configDigest,declaredSource:labels['org.opencontainers.image.source'],declaredVersion:version,proxyOrigin:{VCS:origin.VCS,URL:origin.URL,Ref:origin.Ref,Hash:origin.Hash},observedAt:observation.observedAt,stale:!!observation.stale,verification:'vcs-metadata-consistent',symbolReachability:'unknown'};
|
|
41
|
+
outputs.push(dep);
|
|
42
|
+
}
|
|
43
|
+
return {deps:outputs,warnings,coverage:{collector:'go-main-identity',execution:unavailable||conflicts||stale?'partial':candidates?'completed':'not-applicable',result:outputs.length?'identified':unavailable?'unavailable':conflicts?'conflicting-evidence':'no-match',count:outputs.length,candidates,conflicts,stale}};
|
|
44
|
+
}
|
|
45
|
+
module.exports={resolveGoMainIdentities};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Publisher advisories are separate from CVEProject/OSV. Only a verified Go
|
|
3
|
+
// main-module repository and exact typed package can produce a candidate.
|
|
4
|
+
const {createCacheRepository}=require('../cache-repository');
|
|
5
|
+
const {compareSemver}=require('../osv-db');
|
|
6
|
+
const GHSA=/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i,CVE=/^CVE-\d{4}-\d{4,}$/i;
|
|
7
|
+
function repository(dep){const e=dep.binaryEvidence;if(e?.source!=='go-vcs-and-module-proxy'||e.verification!=='vcs-metadata-consistent')return null;try{const u=new URL(e.proxyOrigin.URL);if(u.protocol!=='https:'||u.hostname!=='github.com'||u.username||u.password||u.port||u.search||u.hash)return null;const m=/^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(u.pathname);if(!m)return null;const root=`github.com/${m[1]}/${m[2]}`;return dep.name===root||dep.name?.startsWith(root+'/')?`${m[1]}/${m[2]}`:null;}catch{return null;}}
|
|
8
|
+
function affected(version,range){if(typeof range!=='string'||range.length>500||compareSemver(version,version)==null)return null;const branches=range.split(/\s*\|\|\s*/);if(!branches.length||branches.length>20)return null;let unknown=false;for(const branch of branches){const parts=branch.split(',').map(x=>x.trim());if(!parts.length||parts.some(x=>!x))return null;let yes=true;for(const part of parts){const m=/^(<=|>=|<|>|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(part);if(!m){unknown=true;yes=false;break;}const cmp=compareSemver(version,m[2]);if(cmp==null){unknown=true;yes=false;break;}const op=m[1]||'=';if(!({'<':cmp<0,'<=':cmp<=0,'>':cmp>0,'>=':cmp>=0,'=':cmp===0}[op]))yes=false;}if(yes)return true;}return unknown?null:false;}
|
|
9
|
+
async function assessGoPublisherAdvisories(deps,options={}){
|
|
10
|
+
const groups=new Map();for(const dep of deps instanceof Map?deps.values():deps||[]){if(dep.ecosystem!=='go'||!dep.version)continue;const repo=repository(dep);if(repo){if(!groups.has(repo))groups.set(repo,[]);groups.get(repo).push(dep);}}
|
|
11
|
+
const matches=[],coverage=[],warnings=[];if(!groups.size)return {matches,coverage,warnings};const cache=createCacheRepository(options.cacheDir||require('../cache-directory').getCacheDir()),providers=require('../providers');
|
|
12
|
+
for(const [repo,items] of groups){let snapshot,observedAt,stale=false,failed=null;let cached=null;try{cached=cache.get('publisher-go-advisories',repo);}catch{}
|
|
13
|
+
try{if(options.offline){if(!cached)throw Error('publisher advisory snapshot is not cached');snapshot=cached.value;observedAt=cached.fetchedAt;stale=cached.stale;}else{
|
|
14
|
+
const advisories=[];let end=false;observedAt=Date.now();const max=options.maxPublisherPages??10;if(!Number.isSafeInteger(max)||max<1||max>100)throw Error('invalid publisher page limit');
|
|
15
|
+
for(let page=1;page<=max;page++){const res=await providers.getResource('github','publisher-advisories',{repo,page,perPage:100},{fetcher:options.fetcher,signal:AbortSignal.timeout(options.publisherTimeoutMs??30000),headers:{Accept:'application/vnd.github+json','User-Agent':'vigievuln-publisher-advisories'}});if(!res.ok)throw Error(`GitHub publisher advisory HTTP ${res.status}`);let stamp=Date.now();if(providers.hasProxyRoute()){stamp=Date.parse(res.headers.get('x-fad-proxy-fetched-at')||'');if(!Number.isFinite(stamp)||stamp<=0||stamp>Date.now()+300000)throw Error('publisher advisory response has no trustworthy source timestamp');stale||=res.headers.get('x-fad-proxy')==='stale';}observedAt=Math.min(observedAt,stamp);const body=await res.json();if(!Array.isArray(body)||body.length>100)throw Error('invalid publisher advisory response');for(const a of body){if(!a||!GHSA.test(a.ghsa_id||'')||!Array.isArray(a.vulnerabilities))throw Error('invalid publisher advisory record');}advisories.push(...body);const hasNext=/rel\s*=\s*"?next"?/i.test(res.headers.get('link')||'');if(!hasNext&&body.length<100){end=true;break;}}
|
|
16
|
+
if(!end)throw Error('publisher advisory pagination limit reached');snapshot={advisories};cache.put('publisher-go-advisories',repo,snapshot,{fetchedAt:observedAt,stale,metadata:{source:'github-publisher',repo}});
|
|
17
|
+
}}catch(error){failed=error.message;if(!options.offline&&cached){snapshot=cached.value;observedAt=cached.fetchedAt;stale=true;try{cache.put('publisher-go-advisories',repo,snapshot,{fetchedAt:observedAt,stale:true,metadata:{source:'github-publisher',repo}})}catch{}}else snapshot=null;}
|
|
18
|
+
if(!snapshot||!Array.isArray(snapshot.advisories)||!Number.isFinite(observedAt)||observedAt<=0||observedAt>Date.now()+300000){warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory feed unavailable for ${repo}: ${failed||'invalid cached evidence'}`});coverage.push({collector:'github-publisher',execution:'partial',result:'indeterminate',repository:repo});continue;}
|
|
19
|
+
let unknown=0;for(const dep of items)for(const advisory of snapshot.advisories){if(!GHSA.test(advisory?.ghsa_id||'')||!Array.isArray(advisory.vulnerabilities)){unknown++;continue;}for(const v of advisory.vulnerabilities){if(String(v?.package?.ecosystem||'').toLowerCase()!=='go'||v.package.name!==dep.name)continue;const verdict=affected(dep.version,v.vulnerable_version_range);if(verdict===null){unknown++;continue;}if(!verdict)continue;const id=CVE.test(advisory.cve_id||'')?advisory.cve_id.toUpperCase():advisory.ghsa_id;const score=Number.isFinite(advisory.cvss?.score)&&advisory.cvss.score>=0&&advisory.cvss.score<=10?advisory.cvss.score:null;const severity=String(advisory.severity||'UNKNOWN').toUpperCase().replace('MODERATE','MEDIUM');matches.push({dep,source:'github-publisher',confidence:'exact',advisoryId:advisory.ghsa_id,cve:{id,aliases:id===advisory.ghsa_id?[]:[advisory.ghsa_id],description:typeof advisory.description==='string'?advisory.description:'',severity:['CRITICAL','HIGH','MEDIUM','LOW'].includes(severity)?severity:'UNKNOWN',score,fixVersion:typeof v.patched_versions==='string'&&/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.patched_versions)?v.patched_versions:null,published:advisory.published_at||null,modified:advisory.updated_at||null,advisorySource:advisory.html_url||null,publisherEvidence:{repository:repo,observedAt,stale,range:v.vulnerable_version_range,scope:'explicit-go-package'}}});}}
|
|
20
|
+
if(stale||failed)warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory evidence for ${repo} is stale${failed?`: ${failed}`:'.'}`});coverage.push({collector:'github-publisher',execution:stale||unknown?'partial':'completed',result:unknown?'indeterminate':'consulted',repository:repo,unknown,count:matches.filter(m=>items.includes(m.dep)).length,observedAt,fetchedAt:observedAt,scope:'explicit-go-package'});
|
|
21
|
+
}
|
|
22
|
+
return {matches,coverage,warnings};
|
|
23
|
+
}
|
|
24
|
+
module.exports={assessGoPublisherAdvisories,affected,repository};
|