vigievuln 1.2.0 → 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 +23 -2
- package/README.md +13 -7
- package/lib/advisory-freshness.js +2 -0
- 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/certs/analyze.js +49 -13
- 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/pe-metadata.js +27 -1
- package/lib/codecs/binary/scan.js +44 -26
- package/lib/codecs/binary/sniff.js +16 -15
- package/lib/codecs/binary.codec.js +27 -4
- package/lib/codecs/go/parse.js +10 -4
- package/lib/codecs/go.codec.js +23 -6
- 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/codecs/maven.codec.js +9 -4
- package/lib/codecs/npm/collect.js +6 -11
- package/lib/codecs/nuget/parse.js +16 -5
- package/lib/codecs/nuget.codec.js +2 -1
- package/lib/codecs/pypi/parse.js +56 -15
- package/lib/codecs/pypi.codec.js +2 -0
- package/lib/csaf-export.js +46 -11
- 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 +35 -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 +100 -10
- 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 +38 -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/sqlite-driver.js +15 -1
- package/lib/suppress.js +34 -13
- 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/lib/xlsx-export.js +8 -2
- package/package.json +12 -3
- package/vigievuln.js +279 -127
package/lib/json-export.js
CHANGED
|
@@ -10,10 +10,57 @@
|
|
|
10
10
|
* @email: pp9ping@gmail.com
|
|
11
11
|
*/
|
|
12
12
|
const fs = require("fs");
|
|
13
|
+
const path = require("node:path");
|
|
13
14
|
const { purlFor } = require("./purl");
|
|
14
15
|
const { summarizeFindings, uniqueFindings } = require("./finding-summary");
|
|
15
16
|
const { europeanReferences, euvdExploited } = require("./eu-refs");
|
|
16
17
|
|
|
18
|
+
// Reports are shareable artifacts. Keep locations relative to the project,
|
|
19
|
+
// without rewriting advisory evidence, URLs, stable IDs or the input payload.
|
|
20
|
+
function portableLocations(doc, source) {
|
|
21
|
+
if (typeof source !== "string" || source.startsWith("(")) return doc;
|
|
22
|
+
const paths = path.win32.isAbsolute(source) && !path.posix.isAbsolute(source) ? path.win32 : path.posix;
|
|
23
|
+
if (!paths.isAbsolute(source)) return doc;
|
|
24
|
+
const normalized = paths.normalize(source);
|
|
25
|
+
const volumeRoot = paths.parse(normalized).root;
|
|
26
|
+
const root = normalized === volumeRoot ? volumeRoot : normalized.replace(/[\\/]+$/, "");
|
|
27
|
+
const locationKeys = new Set(["src", "path", "file", "root", "manifestPath", "manifestPaths", "pomPath", "pomPaths",
|
|
28
|
+
"archive", "dir", "location", "ignoreFile", "vexFile"]);
|
|
29
|
+
const relative = value => {
|
|
30
|
+
if (!paths.isAbsolute(value)) return value;
|
|
31
|
+
const rel = paths.relative(root, value);
|
|
32
|
+
return rel === ".." || rel.startsWith(`..${paths.sep}`) || paths.isAbsolute(rel)
|
|
33
|
+
? `[external]/${paths.basename(value)}` : (rel || ".").split(paths.sep).join("/");
|
|
34
|
+
};
|
|
35
|
+
const walk = (value, key, warning = false) => {
|
|
36
|
+
if (typeof value === "string") {
|
|
37
|
+
if (locationKeys.has(key)) return relative(value);
|
|
38
|
+
if (warning && key === "message") {
|
|
39
|
+
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
40
|
+
const prefix = root.endsWith(paths.sep) ? root : root + paths.sep;
|
|
41
|
+
return value.split(/((?:https?:)?\/\/[^\s"'<>]+)/gi).map((part, index) => {
|
|
42
|
+
if (index % 2) return part; // keep whole URLs, including query paths
|
|
43
|
+
for (const p of new Set([prefix, prefix.replace(/\\/g, "/")])) {
|
|
44
|
+
// A filesystem path starts at a text boundary, never inside a URL.
|
|
45
|
+
// In particular source=/ must not strip slashes from https://...
|
|
46
|
+
// or from a protocol-relative //host/path reference.
|
|
47
|
+
part = part.replace(new RegExp(`(^|[\\s'"(=])${escape(p)}${p === "/" ? "(?!/)" : ""}(?=[^\\s'"),:;])`, "g"), "$1");
|
|
48
|
+
}
|
|
49
|
+
return part.replace(new RegExp(`(^|[\\s'"(=])${escape(root)}(?=$|[\\s'"),:;])`, "g"), "$1.");
|
|
50
|
+
}).join("");
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
if (Array.isArray(value)) return value.map(v => walk(v, key, warning));
|
|
55
|
+
if (value && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) return Object.fromEntries(Object.entries(value)
|
|
56
|
+
.map(([k, v]) => [k, walk(v, k, warning || k === "warnings")]));
|
|
57
|
+
return value;
|
|
58
|
+
};
|
|
59
|
+
const out = walk(doc);
|
|
60
|
+
out.project.src = paths.basename(root) || ".";
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
17
64
|
function coordOf(dep) {
|
|
18
65
|
const ns = dep.namespace || dep.groupId || "";
|
|
19
66
|
const name = dep.name || dep.artifactId;
|
|
@@ -35,6 +82,19 @@ function depBrief(dep) {
|
|
|
35
82
|
// When the version was backfilled from an import/platform BOM, record which BOM
|
|
36
83
|
// supplied it — { via: "bom", bom: "g:a:v" } — so the finding is traceable.
|
|
37
84
|
versionSource: dep.versionSource || null,
|
|
85
|
+
binaryEvidence: dep.binaryEvidence || null,
|
|
86
|
+
installEvidence: dep.installEvidence || null,
|
|
87
|
+
sbomEvidence: dep.sbomEvidence || null,
|
|
88
|
+
artifactTargetId: dep.artifactTargetId || null,
|
|
89
|
+
artifactPath: dep.artifactPath || null,
|
|
90
|
+
packageType: dep.packageType || null,
|
|
91
|
+
manager: dep.manager || null,
|
|
92
|
+
distribution: dep.distribution || null,
|
|
93
|
+
sourceName: dep.sourceName || null,
|
|
94
|
+
sourceVersion: dep.sourceVersion || null,
|
|
95
|
+
packageMetadata: dep.packageMetadata || null,
|
|
96
|
+
packageOrigin: dep.packageOrigin || null,
|
|
97
|
+
osPackageOwners: dep.osPackageOwners || [],
|
|
38
98
|
};
|
|
39
99
|
}
|
|
40
100
|
|
|
@@ -43,9 +103,20 @@ function cveFinding(m) {
|
|
|
43
103
|
return {
|
|
44
104
|
id: c.id,
|
|
45
105
|
aliases: c.aliases || [],
|
|
106
|
+
upstream: c.upstream || [],
|
|
107
|
+
related: c.related || [],
|
|
108
|
+
advisorySource: c.advisorySource || null,
|
|
109
|
+
historicalEvidence: c.historicalEvidence || null,
|
|
110
|
+
applicabilityEvidence: require('./applicability-evidence').applicabilityEvidence(c),
|
|
111
|
+
vendorEvidence: c.vendorEvidence || null,
|
|
112
|
+
publisherEvidence: c.publisherEvidence || null,
|
|
113
|
+
summary: c.summary || null,
|
|
114
|
+
published: c.published || null,
|
|
115
|
+
modified: c.modified || null,
|
|
46
116
|
description: c.description || null,
|
|
47
117
|
copyrightNotice: c.copyrightNotice || null,
|
|
48
|
-
references: (c.osvRefs || []).map(r => r
|
|
118
|
+
references: [...new Set([...(c.osvRefs || []),...(c.references || [])].map(r => typeof r==='string'?r:r?.url).filter(u => {try{const parsed=new URL(u);return ['http:','https:'].includes(parsed.protocol)&&!parsed.username&&!parsed.password;}catch{return false;}}))],
|
|
119
|
+
relatedAdvisories: Array.isArray(c.relatedAdvisories) ? c.relatedAdvisories : [],
|
|
49
120
|
findingId: m.findingId || null,
|
|
50
121
|
applicationIds: m.applicationIds || [],
|
|
51
122
|
applicationExposures: m.applicationExposures || [],
|
|
@@ -56,6 +127,12 @@ function cveFinding(m) {
|
|
|
56
127
|
severity: c.severity || "UNKNOWN",
|
|
57
128
|
severityOriginal: c.severityOriginal || null,
|
|
58
129
|
severityScheme: c.severityScheme || null,
|
|
130
|
+
severitySource: c.severitySource || null,
|
|
131
|
+
scoreSource: c.scoreSource || null,
|
|
132
|
+
riskEvidence: c.riskEvidence || null,
|
|
133
|
+
cveEvidence: c.cveEvidence || [],
|
|
134
|
+
kevEvidence: c.kevEvidence || null,
|
|
135
|
+
epssEvidence: c.epssEvidence || null,
|
|
59
136
|
cvss: c.score ?? null,
|
|
60
137
|
cvssVector: c.cvssVector || null,
|
|
61
138
|
epss: c.epssScore ?? null,
|
|
@@ -72,6 +149,8 @@ function cveFinding(m) {
|
|
|
72
149
|
certfr: (c.certfr || []).map(a => a.ref),
|
|
73
150
|
priority: c.priority ? { band: c.priority.band, score: c.priority.score } : null,
|
|
74
151
|
cwes: c.cwes || [],
|
|
152
|
+
nvdEvidence: c.nvdEvidence || null,
|
|
153
|
+
euvdDetails: c.euvdDetails || null,
|
|
75
154
|
fixVersion: c.fixVersion || null,
|
|
76
155
|
...(c.fixVersion && c.fixEvidence ? { fixEvidence: c.fixEvidence } : {}),
|
|
77
156
|
...(c.fixVersion ? { fixScope: 'advisory', packageFixVerified: false } : {}),
|
|
@@ -83,6 +162,7 @@ function cveFinding(m) {
|
|
|
83
162
|
cpeFiltered: !!m.cpeFiltered,
|
|
84
163
|
suppressed: !!m.suppressed,
|
|
85
164
|
suppressedReason: m.suppressedReason || null,
|
|
165
|
+
suppressionStatus: m.suppressionStatus || null,
|
|
86
166
|
dep: depBrief(m.dep),
|
|
87
167
|
};
|
|
88
168
|
}
|
|
@@ -101,28 +181,37 @@ function buildFindings(payload = {}) {
|
|
|
101
181
|
} = payload;
|
|
102
182
|
|
|
103
183
|
const { buildInventory } = require("./unmanaged");
|
|
104
|
-
const
|
|
184
|
+
const sourceDeps = new Map([...(resolvedDeps || [])].filter(([, dep]) => !dep.artifactTargetId));
|
|
185
|
+
const unmanaged = buildInventory(sourceDeps);
|
|
105
186
|
|
|
106
187
|
const { buildEmbeddedInventory } = require("./embedded");
|
|
107
|
-
const embeddedMatches = cveMatches.filter(m => m.dep?.provenance === "embedded");
|
|
108
|
-
const embedded =
|
|
188
|
+
const embeddedMatches = cveMatches.filter(m => !m.dep?.artifactTargetId && m.dep?.provenance === "embedded");
|
|
189
|
+
const embedded = buildEmbeddedInventory(sourceDeps, embeddedMatches);
|
|
109
190
|
|
|
110
191
|
const uniqueCveMatches = uniqueFindings(cveMatches);
|
|
111
192
|
const findingSummary = summarizeFindings(uniqueCveMatches);
|
|
112
193
|
// Count diagnostic signals as well as incomplete application capabilities.
|
|
113
194
|
// Several signals can describe the same gap; this is not a count of sources.
|
|
114
195
|
const applicationCoverageIncomplete = coverage.filter(c => c.execution === "partial" || c.execution === "not-run" || c.execution === "failed").length;
|
|
196
|
+
const classifiedNotices = require('./report-notices').partitionReportNotices(warnings);
|
|
197
|
+
const provenance = projectInfo.provenance || payload.provenance || null;
|
|
198
|
+
const reportProvenance = classifiedNotices.notices.length || classifiedNotices.freshness.length ? { ...(provenance || {}),
|
|
199
|
+
notices: [...(provenance?.notices || []), ...classifiedNotices.notices],
|
|
200
|
+
freshnessNotices: [...(provenance?.freshnessNotices || []), ...classifiedNotices.freshness] } : provenance;
|
|
115
201
|
const coverageWarningTypes = new Set(["source-unavailable", "source-stale", "dependency-coverage", "osv-coverage", "go-coverage", "unresolved-versions", "no-lockfile", "parse-error", "missing-include", "local-replace", "private-libs"]);
|
|
116
|
-
const coverageWarnings = warnings.filter(w => coverageWarningTypes.has(w.type)).length;
|
|
202
|
+
const coverageWarnings = classifiedNotices.warnings.filter(w => coverageWarningTypes.has(w.type)).length;
|
|
203
|
+
const artifactCoverageIncomplete = (projectInfo.artifacts || []).flatMap(a => a.coverage || []).filter(c => !['completed', 'not-applicable'].includes(c.execution)).length;
|
|
117
204
|
|
|
118
|
-
return {
|
|
205
|
+
return portableLocations({
|
|
119
206
|
schema: "fad-findings/1",
|
|
120
207
|
tool: { name: "VigieVuln", version: String(toolVersion) },
|
|
121
208
|
generatedAt: projectInfo.generatedAt || null,
|
|
122
209
|
project: { name: projectInfo.name || null, src: projectInfo.src || null },
|
|
210
|
+
...(projectInfo.artifacts ? { artifacts: require('./artifacts/report-inventory').reportArtifacts(projectInfo.artifacts,cveMatches) } : {}),
|
|
211
|
+
...(projectInfo.imageReferences?.length ? { imageReferences: projectInfo.imageReferences } : {}),
|
|
123
212
|
// Scan-provenance manifest (data-source freshness + run configuration) for a
|
|
124
213
|
// reproducible/defensible audit. Null if the caller didn't supply one.
|
|
125
|
-
provenance:
|
|
214
|
+
provenance: reportProvenance,
|
|
126
215
|
summary: {
|
|
127
216
|
dependencies: resolvedDeps?.size ?? null,
|
|
128
217
|
cve: { ...findingSummary.bySeverity, kev: findingSummary.kev, total: findingSummary.total },
|
|
@@ -145,7 +234,8 @@ function buildFindings(payload = {}) {
|
|
|
145
234
|
applicationComponents: applicationInventory.length,
|
|
146
235
|
applicationCoverageIncomplete,
|
|
147
236
|
coverageWarnings,
|
|
148
|
-
|
|
237
|
+
...(projectInfo.artifacts ? { artifacts: projectInfo.artifacts.length, artifactCoverageIncomplete } : {}),
|
|
238
|
+
coverageIncomplete: applicationCoverageIncomplete + coverageWarnings + artifactCoverageIncomplete,
|
|
149
239
|
},
|
|
150
240
|
findingSummary,
|
|
151
241
|
cve: uniqueCveMatches.map(cveFinding),
|
|
@@ -188,12 +278,12 @@ function buildFindings(payload = {}) {
|
|
|
188
278
|
applicationInventory,
|
|
189
279
|
applicationRelations,
|
|
190
280
|
coverage,
|
|
191
|
-
warnings,
|
|
281
|
+
warnings: classifiedNotices.warnings,
|
|
192
282
|
excludedDirs,
|
|
193
283
|
// Differential audit vs a --baseline document (summary + per-category deltas).
|
|
194
284
|
// Null when no baseline was provided.
|
|
195
285
|
diff: diff || null,
|
|
196
|
-
};
|
|
286
|
+
}, projectInfo.src);
|
|
197
287
|
}
|
|
198
288
|
|
|
199
289
|
function writeFindings(payload, outputPath) {
|
package/lib/kev.js
CHANGED
|
@@ -19,17 +19,17 @@ const CACHE_PATH = path.join(CACHE_DIR, "kev-cache.json");
|
|
|
19
19
|
const CACHE_TTL_MS = 4 * 3600 * 1000;
|
|
20
20
|
const KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json";
|
|
21
21
|
|
|
22
|
-
function readCache({ offline = false } = {}) {
|
|
22
|
+
function readCache({ offline = false, cacheDir = CACHE_DIR } = {}) {
|
|
23
23
|
try {
|
|
24
|
-
const data = require('./cache-repository').createCacheRepository(
|
|
24
|
+
const data = require('./cache-repository').createCacheRepository(cacheDir).get('catalogue','kev')?.value;
|
|
25
25
|
if (offline || require('./cache-policy').fresh(data._fetchedAt, CACHE_TTL_MS)) return data.body;
|
|
26
26
|
} catch { /* ignore */ }
|
|
27
27
|
return null;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
function writeCache(body, fetchedAt = Date.now()) {
|
|
30
|
+
function writeCache(body, fetchedAt = Date.now(), cacheDir = CACHE_DIR) {
|
|
31
31
|
try {
|
|
32
|
-
require('./cache-repository').createCacheRepository(
|
|
32
|
+
require('./cache-repository').createCacheRepository(cacheDir).put('catalogue','kev',{ _fetchedAt: fetchedAt, body });
|
|
33
33
|
} catch { /* ignore */ }
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -73,14 +73,14 @@ async function enrichKev(matches, opts = {}) {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
|
|
76
|
-
let index = readCache({ offline });
|
|
76
|
+
let index = readCache({ offline, cacheDir: opts.cacheDir });
|
|
77
77
|
if (!index && !offline) {
|
|
78
78
|
try {
|
|
79
79
|
const r = await require("./providers").getResource("kev", "catalog", {},
|
|
80
80
|
{ fetcher, headers: { "User-Agent": "vigievuln-kev" } });
|
|
81
81
|
if (r.ok) {
|
|
82
82
|
index = indexKevCatalog(await r.json());
|
|
83
|
-
writeCache(index, require('./providers/common').responseFetchedAt(r));
|
|
83
|
+
writeCache(index, require('./providers/common').responseFetchedAt(r), opts.cacheDir);
|
|
84
84
|
} else if (verbose) {
|
|
85
85
|
console.warn(` KEV HTTP ${r.status}`);
|
|
86
86
|
}
|
package/lib/maven-bom.js
CHANGED
|
@@ -162,7 +162,7 @@ async function resolveBomManagedVersions(boms, opts = {}) {
|
|
|
162
162
|
if (!d.groupId || !d.artifactId) continue;
|
|
163
163
|
const k = `${d.groupId}:${d.artifactId}`;
|
|
164
164
|
if (map.has(k)) continue;
|
|
165
|
-
if (d.version && !/\$\{/.test(String(d.version))) map.set(k, { version: String(d.version), bom: bomCoord, ...(via ? { via } : {}) });
|
|
165
|
+
if (d.version && !/\$\{/.test(String(d.version))) map.set(k, { version: String(d.version), bom: bomCoord, ...(via ? { via } : {}), ...(bom.manifestPath ? { manifestPath: bom.manifestPath } : {}) });
|
|
166
166
|
}
|
|
167
167
|
}
|
|
168
168
|
return map;
|
|
@@ -184,6 +184,7 @@ function backfillVersions(resolvedDeps, mgmtMap) {
|
|
|
184
184
|
if (dep.version && !/\$\{/.test(String(dep.version))) continue; // already concrete
|
|
185
185
|
const entry = mgmtMap.get(`${dep.groupId}:${dep.artifactId}`);
|
|
186
186
|
if (!entry) continue;
|
|
187
|
+
if (entry.manifestPath && (dep.ecosystemType !== "gradle" || dep.manifestPaths?.length !== 1 || dep.manifestPaths[0] !== entry.manifestPath)) continue;
|
|
187
188
|
const v = entry.version;
|
|
188
189
|
dep.version = v;
|
|
189
190
|
if (!Array.isArray(dep.versions)) dep.versions = [];
|
package/lib/merge-sources.js
CHANGED
|
@@ -76,6 +76,9 @@ function mergeBySource(existing, additions) {
|
|
|
76
76
|
cve: {
|
|
77
77
|
...prev.cve,
|
|
78
78
|
...m.cve,
|
|
79
|
+
references: [...new Map([...(prev.cve.references||[]),...(m.cve.references||[])].map(ref=>[typeof ref==='string'?ref:ref?.url,ref]).filter(([url])=>url)).values()],
|
|
80
|
+
relatedAdvisories: [...new Map([...(prev.cve.relatedAdvisories||[]),...(m.cve.relatedAdvisories||[])].map(ref=>[ref?.url,ref]).filter(([url])=>url)).values()],
|
|
81
|
+
applicabilityEvidence: require('./applicability-evidence').applicabilityEvidence(prev.cve,m.cve),
|
|
79
82
|
...require('./advisory-fixes').mergeAdvisoryFixes(prev.cve,m.cve),
|
|
80
83
|
id,
|
|
81
84
|
// an advisory's identity is the UNION of its ids — dropping the
|
package/lib/native-advisories.js
CHANGED
|
@@ -28,23 +28,23 @@ function cveEnvelope(raw, { fetchedAt, provenance = {transport:'direct'} } = {})
|
|
|
28
28
|
for (const name of (a.packageNames || [])) packages.push({ecosystem:'Maven',name});
|
|
29
29
|
if (a.product) packages.push({ecosystem:'CVEProduct',name:String(a.product).toLowerCase()});
|
|
30
30
|
}
|
|
31
|
-
// Preserve
|
|
32
|
-
//
|
|
31
|
+
// Preserve explicitly typed package identities. Product names alone do not
|
|
32
|
+
// establish an ecosystem or an affected package coordinate.
|
|
33
33
|
for (const container of [raw.containers?.cna,...(Array.isArray(raw.containers?.adp)?raw.containers.adp:[])])
|
|
34
34
|
for (const affected of (Array.isArray(container?.affected)?container.affected:[])) {
|
|
35
|
-
const p=
|
|
36
|
-
if (p) packages.push(p);
|
|
35
|
+
const p=require('./native-package-match').explicitNativePackage(affected,{source:'cveproject',record:raw,container});
|
|
36
|
+
if (p) packages.push({ecosystem:p.ecosystem,name:p.name});
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
return {source:'cveproject',id:id.toUpperCase(),document:raw,fetchedAt,provenance,packages};
|
|
40
40
|
}
|
|
41
41
|
function gcveEnvelope(stored, { provenance = {transport:'direct'} } = {}) {
|
|
42
|
-
const {identity
|
|
42
|
+
const {identity}=require('./gcve-index');
|
|
43
43
|
const raw=stored?.raw, ident=identity(raw,stored?.gna), at=Date.parse(stored.collectedAt);
|
|
44
44
|
if (!Number.isSafeInteger(at) || at <= 0 || at > Date.now()+300000) throw new Error('invalid GCVE collection date');
|
|
45
45
|
const packages=[];
|
|
46
|
-
if (ident.recordType === 'advisory' && raw?.cveMetadata?.state === 'PUBLISHED') for (const
|
|
47
|
-
const p=
|
|
46
|
+
if (ident.recordType === 'advisory' && raw?.cveMetadata?.state === 'PUBLISHED') for (const container of [raw?.containers?.cna,...(Array.isArray(raw?.containers?.adp)?raw.containers.adp:[])]) for (const a of (Array.isArray(container?.affected)?container.affected:[])) {
|
|
47
|
+
const p=require('./native-package-match').explicitNativePackage(a);if (p) packages.push({ecosystem:p.ecosystem,name:p.name});
|
|
48
48
|
}
|
|
49
49
|
return {source:'gcve',id:ident.id,document:raw,fetchedAt:at,provenance:{...provenance,gna:ident.gna,sourceUrl:stored.sourceUrl || null},packages};
|
|
50
50
|
}
|
|
@@ -266,3 +266,5 @@ function matchGcveStore(deps, store, legacyIndex = null) {
|
|
|
266
266
|
return result;
|
|
267
267
|
}
|
|
268
268
|
module.exports.matchGcveStore=matchGcveStore;
|
|
269
|
+
|
|
270
|
+
module.exports.matchNativePackages=require('./native-package-match').matchNativePackages;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// CVE Record provider organization IDs, not CVE or product allowlists.
|
|
3
|
+
// Debian's CNA ID is corroborated by CVEProject's published Debian records.
|
|
4
|
+
const cnaIdentities=Object.freeze([{orgId:'79363d38-fa19-49d1-9214-5f28da3f3ac5',vendor:'debian',ecosystem:'system:deb:debian:*',manager:'deb',distribution:'debian',versionType:'dpkg'}]);
|
|
5
|
+
function cnaSystemPackage(affected,context={},registry=cnaIdentities){
|
|
6
|
+
const raw=context.record,container=context.container;if(context.source!=='cveproject'||container!==raw?.containers?.cna)return null;
|
|
7
|
+
const org=container?.providerMetadata?.orgId;if(typeof org!=='string'||org!==raw?.cveMetadata?.assignerOrgId)return null;
|
|
8
|
+
const item=registry.find(r=>r.orgId===org&&String(affected?.vendor||'').toLowerCase()===r.vendor);if(!item)return null;
|
|
9
|
+
const name=affected.packageName;if(typeof name!=='string'||!/^[a-z0-9][a-z0-9+.-]*$/.test(name)||!Array.isArray(affected.versions)||!affected.versions.some(v=>String(v?.versionType||'').toLowerCase()===item.versionType))return null;
|
|
10
|
+
return {ecosystem:item.ecosystem,name,manager:item.manager,distribution:item.distribution,release:null,arch:'source'};
|
|
11
|
+
}
|
|
12
|
+
module.exports={cnaIdentities,cnaSystemPackage};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Shared native-record package matching. A typed PURL is required; neither
|
|
3
|
+
// product names nor advisory identifiers establish a package identity.
|
|
4
|
+
const {explicitPackage,identity}=require('./gcve-index');
|
|
5
|
+
const {osvEcosystemFor,osvPkgName}=require('./osv');
|
|
6
|
+
const {packageName}=require('./advisory-store');
|
|
7
|
+
const nativeVersions=require('./system-inventory/versions');
|
|
8
|
+
function systemPackage(a){
|
|
9
|
+
const raw=typeof a?.packageURL==='string'?a.packageURL:typeof a?.purl==='string'?a.purl:null;
|
|
10
|
+
if(!raw){
|
|
11
|
+
const name=a?.packageName,url=a?.collectionURL;
|
|
12
|
+
if(typeof name==='string'&&/^[a-z0-9][a-z0-9+.-]*$/.test(name)&&typeof url==='string'&&/^https:\/\/packages\.debian\.org\/?$/i.test(url)&&Array.isArray(a.versions)&&a.versions.some(v=>String(v?.versionType||'').toLowerCase()==='dpkg'))return {ecosystem:'system:deb:debian:*',name,manager:'deb',distribution:'debian',release:null,arch:'source'};
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
if(!/^pkg:(?:deb|apk|rpm)\//i.test(raw))return null;
|
|
16
|
+
const unqualified=/^pkg:deb\/debian\/([a-z0-9][a-z0-9+.-]*)$/i.exec(raw);
|
|
17
|
+
if(unqualified&&Array.isArray(a.versions)&&a.versions.some(v=>String(v?.versionType||'').toLowerCase()==='dpkg'))return {ecosystem:'system:deb:debian:*',name:unqualified[1],manager:'deb',distribution:'debian',release:null,arch:'source'};
|
|
18
|
+
const m=/^pkg:(deb|apk|rpm)\/([^/@?#]+)\/([^/@?#]+)\?([^#]+)$/i.exec(raw);if(!m)return null;
|
|
19
|
+
try{
|
|
20
|
+
const type=m[1].toLowerCase(),namespace=decodeURIComponent(m[2]).toLowerCase(),name=decodeURIComponent(m[3]);
|
|
21
|
+
if(!/^[a-z0-9][a-z0-9.+_-]*$/i.test(name)||!/^[a-z0-9][a-z0-9.+_-]*$/.test(namespace))return null;
|
|
22
|
+
const q=new URLSearchParams(m[4]), keys=[...q.keys()];if(new Set(keys).size!==keys.length || keys.some(k=>!['distro','arch'].includes(k)))return null;
|
|
23
|
+
const distro=q.get('distro'),arch=q.get('arch');if(!distro||!arch||!/^[a-z0-9][a-z0-9.+_-]*$/i.test(arch))return null;
|
|
24
|
+
const prefix=namespace+'-';if(!distro.toLowerCase().startsWith(prefix))return null;
|
|
25
|
+
const release=distro.slice(prefix.length);if(!/^[0-9][A-Za-z0-9._+-]*$/.test(release))return null;
|
|
26
|
+
return {ecosystem:`system:${type}:${namespace}:${release}`,name,manager:type,distribution:namespace,release,arch};
|
|
27
|
+
}catch{return null;}
|
|
28
|
+
}
|
|
29
|
+
function explicitNativePackage(a,context){return systemPackage(a)||require('./native-cna-identities').cnaSystemPackage(a,context,context?.cnaIdentities)||explicitPackage(a)||require('./native-advisories').explicitNpmPackage(a);}
|
|
30
|
+
function depIdentity(dep){
|
|
31
|
+
if(dep.ecosystem==='system'){
|
|
32
|
+
const manager=({dpkg:'deb',deb:'deb',apk:'apk',rpm:'rpm'})[dep.manager||dep.packageType],d=dep.distribution;
|
|
33
|
+
if(!manager||!d?.id||!d?.versionId)return null;
|
|
34
|
+
return {ecosystem:`system:${manager}:${String(d.id).toLowerCase()}:${d.versionId}`,names:[...new Set([dep.sourceName,dep.name].filter(Boolean))]};
|
|
35
|
+
}
|
|
36
|
+
const ecosystem=osvEcosystemFor(dep),name=osvPkgName(dep);return ecosystem&&name?{ecosystem,names:[name]}:null;
|
|
37
|
+
}
|
|
38
|
+
function typeComparator(type,ecosystem){
|
|
39
|
+
type=String(type||'').toLowerCase();
|
|
40
|
+
if(ecosystem.startsWith('system:')){
|
|
41
|
+
const manager=ecosystem.split(':')[1],valid={deb:['deb','debian','dpkg'],apk:['apk','alpine'],rpm:['rpm']}[manager];
|
|
42
|
+
return valid?.includes(type)?nativeVersions[manager==='deb'?'debian':manager]:null;
|
|
43
|
+
}
|
|
44
|
+
if(type==='maven'&&ecosystem==='Maven')return require('./cve-version-verdict').comparator('maven');
|
|
45
|
+
if(type==='semver')return require('./osv-db').compareSemver;
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
function versionVerdict(version,a,ecosystem){
|
|
49
|
+
if(typeof version!=='string'||!version||!Array.isArray(a?.versions))return null;
|
|
50
|
+
let unknown=false,affected=false,unaffected=false;
|
|
51
|
+
for(const v of a.versions){
|
|
52
|
+
if(!v||typeof v.version!=='string'||!['affected','unaffected','unknown'].includes(v.status)||v.lessThan!=null&&v.lessThanOrEqual!=null){unknown=true;continue;}
|
|
53
|
+
const upper=v.lessThan??v.lessThanOrEqual,cmp=typeComparator(v.versionType,ecosystem);
|
|
54
|
+
let member;
|
|
55
|
+
if(upper==null && version===v.version && String(v.versionType||'').toLowerCase()!=='git')member=true;
|
|
56
|
+
else if(!cmp||cmp(version,version)!==0)member=null;
|
|
57
|
+
else if(upper==null){const c=cmp(version,v.version);member=c===null?null:c===0;}
|
|
58
|
+
else {
|
|
59
|
+
const lower=v.version==='0'?-1:cmp(v.version,version),limit=upper==='*'?1:cmp(upper,version),bounds=upper==='*'||v.version==='0'?-1:cmp(v.version,upper);
|
|
60
|
+
if(lower===null||limit===null||bounds===null||bounds>0||bounds===0&&v.lessThan!=null)member=null;
|
|
61
|
+
else member=lower<=0 && (upper==='*' || (v.lessThan!=null?limit>0:limit>=0));
|
|
62
|
+
}
|
|
63
|
+
if(member===null){unknown=true;continue;}if(!member)continue;
|
|
64
|
+
let state=v.status;
|
|
65
|
+
if(v.changes!=null){
|
|
66
|
+
if(!cmp||!Array.isArray(v.changes)||v.changes.some(c=>!c||typeof c.at!=='string'||!['affected','unaffected','unknown'].includes(c.status)||cmp(c.at,c.at)!==0)){unknown=true;continue;}
|
|
67
|
+
const sorted=[...v.changes].sort((x,y)=>cmp(x.at,y.at));let invalid=false;
|
|
68
|
+
for(const c of sorted){
|
|
69
|
+
const lower=v.version==='0'?-1:cmp(v.version,c.at),higher=upper==null?cmp(c.at,v.version):upper==='*'?-1:cmp(c.at,upper),atVersion=cmp(c.at,version);
|
|
70
|
+
if(lower===null||higher===null||atVersion===null||lower>0||upper!=null && upper!=='*' && (higher>0||higher===0&&v.lessThan!=null) || upper==null && higher!==0){invalid=true;break;}
|
|
71
|
+
if(atVersion<=0)state=c.status;
|
|
72
|
+
}
|
|
73
|
+
if(invalid){unknown=true;continue;}
|
|
74
|
+
}
|
|
75
|
+
if(state==='affected')affected=true;else if(state==='unaffected')unaffected=true;else unknown=true;
|
|
76
|
+
}
|
|
77
|
+
if(unknown || affected&&unaffected)return null;if(affected)return true;if(unaffected)return false;
|
|
78
|
+
const fallback=String(a.defaultStatus||'unknown').toLowerCase();return fallback==='affected'?true:fallback==='unaffected'?false:null;
|
|
79
|
+
}
|
|
80
|
+
function containers(record){return [record?.containers?.cna,...(Array.isArray(record?.containers?.adp)?record.containers.adp:[])].filter(Boolean);}
|
|
81
|
+
function sourceReferences(record,source){
|
|
82
|
+
const references=[],relatedAdvisories=[],seen=new Set();
|
|
83
|
+
for(const container of containers(record))for(const ref of Array.isArray(container.references)?container.references:[]){
|
|
84
|
+
let url;try{const u=new URL(ref?.url);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)continue;url=u.href;}catch{continue;}
|
|
85
|
+
if(!seen.has(url)){seen.add(url);references.push({url,tags:Array.isArray(ref.tags)?ref.tags.filter(x=>typeof x==='string'):[],name:typeof ref.name==='string'?ref.name:null,source});}
|
|
86
|
+
if(source!=='cveproject'||container!==record.containers?.cna||!Array.isArray(ref.tags)||!ref.tags.includes('vendor-advisory'))continue;
|
|
87
|
+
const m=/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/security\/advisories\/(GHSA-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4})$/i.exec(url);
|
|
88
|
+
if(m && typeof ref.name==='string' && ref.name.includes(m[1]))relatedAdvisories.push({id:m[1],url,relationship:'reference',source:'CVEProject'});
|
|
89
|
+
}
|
|
90
|
+
return {references,relatedAdvisories:[...new Map(relatedAdvisories.map(item=>[item.url,item])).values()]};
|
|
91
|
+
}
|
|
92
|
+
function metric(cs){for(const c of cs)for(const m of c.metrics||[])for(const k of ['cvssV4_0','cvssV3_1','cvssV3_0','cvssV2_0']){const v=m?.[k],n=v?.baseScore;if(typeof n==='number'&&Number.isFinite(n)&&n>=0&&n<=10)return {score:n,severity:String(v.baseSeverity||(n>=9?'CRITICAL':n>=7?'HIGH':n>=4?'MEDIUM':n>0?'LOW':'NONE')).toUpperCase(),cvssVector:v.vectorString||null};}return {score:null,severity:'UNKNOWN'};}
|
|
93
|
+
function loadRecords(store,sources){
|
|
94
|
+
if(!store?.db?.prepare || typeof store.getRecord!=='function')return [];
|
|
95
|
+
const sql=`SELECT source,id FROM advisory_records WHERE source IN (${sources.map(()=>'?').join(',')}) ORDER BY source,id`;
|
|
96
|
+
const stmt=store.db.prepare(sql),rows=typeof stmt.iterate==='function'?stmt.iterate(...sources):stmt.all(...sources);
|
|
97
|
+
return (function*(){for(const row of rows){const rec=store.getRecord(row.source,row.id);if(rec)yield rec;}})();
|
|
98
|
+
}
|
|
99
|
+
function matchNativePackages(deps,store,opts={}){
|
|
100
|
+
const sources=(opts.sources||['cveproject','gcve']).filter(x=>['cveproject','gcve'].includes(x));
|
|
101
|
+
const wanted=new Map(),unknown=[],matches=[];
|
|
102
|
+
for(const dep of deps instanceof Map?deps.values():deps||[]){if(dep.provenance==='binary')continue;const ident=depIdentity(dep);if(!ident)continue;const ecosystems=[ident.ecosystem,...(ident.ecosystem.startsWith('system:deb:debian:')?['system:deb:debian:*']:[])];for(const ecosystem of ecosystems)for(const name of ident.names){const key=JSON.stringify([ecosystem,packageName(ecosystem,name)]),list=wanted.get(key)||[];list.push(dep);wanted.set(key,list);}}
|
|
103
|
+
if(!wanted.size||!sources.length)return {matches,unknown,coverage:{status:'not-applicable',sources}};
|
|
104
|
+
const snapshots=new Map(),seenRecords=new Set();
|
|
105
|
+
function* records(){
|
|
106
|
+
for(const [key] of wanted){const [ecosystem,name]=JSON.parse(key);for(const source of sources)yield* store.getPackageRecords(ecosystem,name,{source});}
|
|
107
|
+
// Older envelopes indexed only selected ecosystems. Stream their documents
|
|
108
|
+
// once without retaining them or modifying the historical cache.
|
|
109
|
+
if(opts.scanLegacy!==false)yield* loadRecords(store,sources);
|
|
110
|
+
}
|
|
111
|
+
for(const rec of records()){
|
|
112
|
+
const recordKey=rec.source+'\0'+rec.id;if(seenRecords.has(recordKey))continue;seenRecords.add(recordKey);
|
|
113
|
+
const raw=rec.document;if(raw?.cveMetadata?.state!=='PUBLISHED')continue;
|
|
114
|
+
let gcve=null;if(rec.source==='gcve'){
|
|
115
|
+
try{gcve=identity(raw,rec.provenance?.gna);if(gcve.recordType!=='advisory')continue;}catch{continue;}
|
|
116
|
+
const gna=rec.provenance?.gna;if(!Number.isSafeInteger(gna)){unknown.push({id:rec.id,reason:'GCVE source identity unavailable'});continue;}
|
|
117
|
+
if(!snapshots.has(gna))snapshots.set(gna,store.getRecord('gcve-snapshot',`gna:${gna}`));
|
|
118
|
+
const snapshot=snapshots.get(gna),observed=Math.max(rec.fetchedAt,...(rec.observations||[]).map(o=>o.fetchedAt).filter(Number.isFinite));
|
|
119
|
+
if(snapshot && snapshot.provenance?.gna===gna && rec.provenance?.sourceUrl && snapshot.provenance?.sourceUrl===rec.provenance.sourceUrl && snapshot.fetchedAt>observed && Array.isArray(snapshot.document?.ids) && !snapshot.document.ids.includes(rec.id))continue;
|
|
120
|
+
}
|
|
121
|
+
const cs=containers(raw),description=cs.flatMap(c=>Array.isArray(c.descriptions)?c.descriptions:[]).find(d=>String(d?.lang||'').startsWith('en'))?.value || '';
|
|
122
|
+
const evaluations=new Map();
|
|
123
|
+
for(const container of cs)for(const a of (Array.isArray(container.affected)?container.affected:[])){
|
|
124
|
+
const p=explicitNativePackage(a,{source:rec.source,record:raw,container,cnaIdentities:opts.cnaIdentities});if(!p)continue;
|
|
125
|
+
const candidates=wanted.get(JSON.stringify([p.ecosystem,packageName(p.ecosystem,p.name)]))||[];
|
|
126
|
+
const consultation=rec.source==='cveproject' && typeof store.getQuery==='function' ? store.getQuery({source:'cveproject',ecosystem:p.ecosystem,name:p.name,version:'*'},{ttlMs:Number.MAX_SAFE_INTEGER}) : null;
|
|
127
|
+
if(consultation && consultation.provenance?.stale!==true && consultation.fetchedAt >= (rec.contentChangedAt||rec.fetchedAt) && !consultation.ids.includes(rec.id))continue;
|
|
128
|
+
for(const dep of candidates){
|
|
129
|
+
if(p.ecosystem==='system:deb:debian:*'&&['third-party','ambiguous'].includes(dep.packageOrigin?.status))continue;
|
|
130
|
+
if(p.manager && p.arch!=='source' && dep.architecture && dep.architecture!==p.arch)continue;
|
|
131
|
+
if(p.manager && p.arch!=='source' && dep.name!==p.name)continue;
|
|
132
|
+
const versions=p.manager ? [dep.version] : [...new Set([...(Array.isArray(dep.versions)?dep.versions:[]),dep.version].filter(Boolean))];
|
|
133
|
+
for(const installedVersion of versions){
|
|
134
|
+
const location=dep.manifestPaths?.[0] || dep.pomPaths?.[0] || dep.manifestPath || '';
|
|
135
|
+
const occurrence=dep.coordKey || JSON.stringify([dep.artifactTargetId||'',dep.ecosystem,dep.namespace||dep.groupId||'',dep.name||dep.artifactId||'',location,dep.architecture||'']);
|
|
136
|
+
const k=JSON.stringify([occurrence,installedVersion]);let entry=evaluations.get(k);
|
|
137
|
+
if(!entry){entry={dep,installedVersion,name:p.name,verdicts:[]};evaluations.set(k,entry);}
|
|
138
|
+
let version=installedVersion,reason=null;
|
|
139
|
+
if(p.manager && p.arch==='source'){
|
|
140
|
+
if(!dep.sourceName||dep.sourceName!==p.name||!dep.sourceVersion)reason='source identity or version unavailable';else version=dep.sourceVersion;
|
|
141
|
+
} else if(p.manager && !dep.architecture)reason='architecture unavailable';
|
|
142
|
+
if(a.platforms?.length)reason='platform constraints unsupported';
|
|
143
|
+
const result=reason?null:versionVerdict(version,a,p.ecosystem);
|
|
144
|
+
entry.verdicts.push(result);if(result===null)entry.reason=reason||'version semantics unknown';
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
for(const entry of evaluations.values()){
|
|
149
|
+
const values=entry.verdicts;
|
|
150
|
+
if(values.includes(null) || values.includes(true)&&values.includes(false)){unknown.push({id:rec.id,artifactTargetId:entry.dep.artifactTargetId||null,name:entry.name,version:entry.installedVersion,reason:entry.reason||'contradictory affected statuses'});continue;}
|
|
151
|
+
if(!values.includes(true))continue;
|
|
152
|
+
const aliases=gcve?.aliases||[],cveId=aliases.find(id=>/^CVE-\d{4}-\d{4,}$/i.test(id))||rec.id;
|
|
153
|
+
const dep=entry.installedVersion===entry.dep.version?entry.dep:{...entry.dep,version:entry.installedVersion};
|
|
154
|
+
matches.push({dep,source:rec.source==='gcve'?`GCVE:GNA-${gcve.gna}`:'CVEProject',confidence:'exact',cve:{id:cveId,...metric(cs),...sourceReferences(raw,rec.source),description:String(description),published:raw.cveMetadata.datePublished||null,modified:raw.cveMetadata.dateUpdated||null,fixVersion:null,...(gcve?{gcve:gcve.id,gcveSource:rec.provenance?.sourceUrl||null,gcveRecordType:gcve.recordType,gcveRelationships:gcve.relationships,aliases}: {})}});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return {matches,unknown,coverage:{status:unknown.length?'incomplete':'partial',sources,reason:unknown.length?'native comparisons undecidable':'native source completeness must be evaluated separately'}};
|
|
158
|
+
}
|
|
159
|
+
module.exports={systemPackage,explicitNativePackage,depIdentity,versionVerdict,matchNativePackages};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Prepare the native source stores independently of OSV/NVD. Failed refreshes
|
|
3
|
+
// keep earlier observations and are returned as coverage, never clean verdicts.
|
|
4
|
+
const path=require('node:path');
|
|
5
|
+
const {openAdvisoryStore}=require('./advisory-store');
|
|
6
|
+
function selectedNativeSources(options={}){
|
|
7
|
+
const requested=options.nativeSources||['cveproject','gcve'];if(!Array.isArray(requested)||requested.some(s=>!['cveproject','gcve'].includes(s)))throw Error('invalid native source selection');
|
|
8
|
+
return [...new Set(requested)].filter(s=>s==='cveproject'?!options.disableCveProject:!options.disableGcve&&options.gcve!==false);
|
|
9
|
+
}
|
|
10
|
+
async function prepareNativeSources(deps,options={}){
|
|
11
|
+
const cacheDir=options.cacheDir||require('./cache-directory').getCacheDir(),store=options.store||openAdvisoryStore({cacheDir}),close=!options.store;
|
|
12
|
+
const sources=selectedNativeSources(options),coverage=[],warnings=[],ttlMs=options.advisoryQueryTtlMs??4*3600000;
|
|
13
|
+
try{
|
|
14
|
+
for(const source of sources){
|
|
15
|
+
let refreshError=null;
|
|
16
|
+
const existing=store.getSourceCoverage(source,'*');
|
|
17
|
+
const stale=!existing || existing.provenance?.stale===true || Date.now()<existing.fetchedAt || Date.now()-existing.fetchedAt>=ttlMs;
|
|
18
|
+
const offline=options.offline || (source==='gcve'?options.gcveOffline:options.cveOffline);
|
|
19
|
+
if(!offline && (stale||options.forceUpdate)){
|
|
20
|
+
try{
|
|
21
|
+
if(options.nativeSourceAdapters?.[source]) await options.nativeSourceAdapters[source]({deps,store,cacheDir,options});
|
|
22
|
+
else if(source==='gcve'){
|
|
23
|
+
const feed=require('./gcve-feed');await feed.updateGcveIndex({...(options.gcveOptions||{}),cacheFile:path.join(cacheDir,'gcve-data','index.json'),fetcher:require('./providers').hasProxyRoute()?feed.proxyGcveFetcher:(options.fetcher||globalThis.fetch)});
|
|
24
|
+
} else if(require('./providers').hasProxyRoute()){
|
|
25
|
+
// Ask the fleet's typed native package index for all ecosystems. Older
|
|
26
|
+
// servers can still supply their legacy npm/Maven projections, while a
|
|
27
|
+
// failed generic lookup remains an explicit incomplete source.
|
|
28
|
+
try{await require('./cve-packages-proxy').refreshPackageCves(deps,store,{ttlMs});}
|
|
29
|
+
catch(error){
|
|
30
|
+
if(require('./cve-npm-proxy').packageNames(deps).length)await require('./cve-npm-proxy').refreshNpmCves(deps,store,{ttlMs});
|
|
31
|
+
if([...deps.values()].some(d=>d.ecosystem==='maven' && d.provenance!=='binary')){const scanner=(require('./codecs/maven.codec').nativeScanners||[]).find(x=>x.kind==='cve');if(scanner?.scan)await scanner.scan(deps,{hostedProxy:true,offline:false,queryTtlMs:ttlMs});}
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
await require('./cve-download').ensureCveIndex({force:!!options.forceUpdate,offline:false,ttlMs,cacheDir});
|
|
36
|
+
}
|
|
37
|
+
}catch(e){refreshError=e.message;warnings.push({type:'source-unavailable',code:'source-request-failed',source,status:e.status||null,reason:e.message,resources:[source],message:`${source} refresh failed: ${e.message}`});}
|
|
38
|
+
}
|
|
39
|
+
const current=store.getSourceCoverage(source,'*');
|
|
40
|
+
const exists=!!store.db.prepare('SELECT 1 AS n FROM advisory_records WHERE source=? LIMIT 1').get(source);
|
|
41
|
+
const identities=new Map(require('./cve-packages-proxy').packageIdentities(deps).map(p=>[JSON.stringify([p.ecosystem,p.name]),{source,ecosystem:p.ecosystem,name:p.name,version:'*'}]));
|
|
42
|
+
const queries=[...identities.values()].map(tuple=>store.getQuery(tuple,{ttlMs})).filter(Boolean);
|
|
43
|
+
const scoped=identities.size>0 && queries.length===identities.size;
|
|
44
|
+
const scopedAt=scoped?Math.min(...queries.map(q=>q.fetchedAt)):null;
|
|
45
|
+
const fetchedAt=current?.fetchedAt || scopedAt;
|
|
46
|
+
const age=fetchedAt && Date.now()-fetchedAt;
|
|
47
|
+
const expired=age>=ttlMs, invalidDate=fetchedAt>Date.now();
|
|
48
|
+
const declaredStale=current?.stale===true || current?.provenance?.stale===true || (scoped && queries.some(q=>q.provenance?.stale===true));
|
|
49
|
+
const available=exists || !!current || scoped;
|
|
50
|
+
const issue=refreshError?'refresh-failed':!available?'missing-source':invalidDate?'invalid-timestamp':declaredStale||(!offline&&expired)?'stale-source':null;
|
|
51
|
+
const complete=!!current?.complete&&!expired&&!declaredStale&&!invalidDate&&!refreshError;
|
|
52
|
+
const reason=refreshError || (!available?'No native records or source consultation are available':invalidDate?'Source collection timestamp is in the future':declaredStale?'The provider marked its source data stale':!offline&&expired?'Source evidence could not be refreshed':scoped?'Explicit package identities consulted; records without typed package identities remain unassessed':!current?.complete?'Available native records consulted; source-wide completeness is not established':expired?'Prepared source snapshot used offline':'Source snapshot consulted');
|
|
53
|
+
coverage.push({source,status:complete?'complete':available?'incomplete':'missing',complete,
|
|
54
|
+
execution:issue?(available?'partial':'not-run'):'completed',result:issue?'indeterminate':'available',
|
|
55
|
+
scope:scoped?'consulted-packages':'available-native-records',issue,fetchedAt:fetchedAt||null,freshness:expired?'expired':'current',reason});
|
|
56
|
+
}
|
|
57
|
+
return {sources,coverage,warnings};
|
|
58
|
+
} finally {if(close)store.close();}
|
|
59
|
+
}
|
|
60
|
+
module.exports={selectedNativeSources,prepareNativeSources};
|