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/cli-image.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { Command, InvalidArgumentError } = require('commander');
|
|
6
|
+
const { acquireInventories, assessInventories, writeSnapshot, incompleteCapabilities } = require('./artifacts/scan');
|
|
7
|
+
|
|
8
|
+
const REPORTS = Object.freeze({
|
|
9
|
+
json: { name: 'findings.json', write: (p, f) => require('./json-export').writeFindings(p, f) },
|
|
10
|
+
html: { name: 'cve-report.html', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateHtmlReport(p)) },
|
|
11
|
+
doc: { name: 'cve-report.doc', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateWordReport(p)) },
|
|
12
|
+
sbom: { name: 'sbom.cdx.json', write: (p, f) => require('./sbom-export').writeCycloneDx(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
13
|
+
csaf: { name: 'vex.csaf.json', write: (p, f) => require('./csaf-export').writeCsaf(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
14
|
+
sarif: { name: 'findings.sarif.json', write: (p, f) => require('./sarif-export').writeSarif(p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
15
|
+
xlsx: { name: 'report.xlsx', write: (p, f) => require('./xlsx-export').writeXlsx(p, f) },
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
function jsonFile(file) {
|
|
19
|
+
if (fs.statSync(file).size > 1024 * 1024) throw Error('configuration file is too large');
|
|
20
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
21
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('configuration must be a JSON object');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function distribution(value) {
|
|
25
|
+
const match = /^([a-z][a-z0-9_-]*):([^\s:]+)$/.exec(value);
|
|
26
|
+
if (!match) throw new InvalidArgumentError('expected distribution-id:release, e.g. debian:12');
|
|
27
|
+
return { id: match[1], versionId: match[2] };
|
|
28
|
+
}
|
|
29
|
+
// Compare existing files by inode and resolve parent symlinks for new outputs.
|
|
30
|
+
function canonicalFile(file) {
|
|
31
|
+
const absolute = path.resolve(file); let current = absolute, suffix = [];
|
|
32
|
+
while (!fs.existsSync(current)) { const parent = path.dirname(current); if (parent === current) break; suffix.unshift(path.basename(current)); current = parent; }
|
|
33
|
+
try { current = fs.realpathSync(current); } catch { /* unresolved path */ }
|
|
34
|
+
return path.join(current, ...suffix);
|
|
35
|
+
}
|
|
36
|
+
function sameFile(a,b) {
|
|
37
|
+
if (canonicalFile(a) === canonicalFile(b)) return true;
|
|
38
|
+
try { const x=fs.statSync(a),y=fs.statSync(b); return x.dev===y.dev && x.ino===y.ino; } catch { return false; }
|
|
39
|
+
}
|
|
40
|
+
function reportFiles(opts) {
|
|
41
|
+
if (opts.report === false) return [];
|
|
42
|
+
const explicit=Object.keys(REPORTS).filter(format=>opts['report'+format[0].toUpperCase()+format.slice(1)]!==undefined);
|
|
43
|
+
const selected=opts.reports?opts.reports.split(',').map(s=>s.trim()):explicit.length?explicit:['html','json'];
|
|
44
|
+
const formats=[...new Set([...selected,...explicit])];
|
|
45
|
+
if(formats.some(format=>!REPORTS[format]))throw Error('unknown report format');
|
|
46
|
+
return formats.map(format=>{const specified=opts['report'+format[0].toUpperCase()+format.slice(1)];return {format,file:path.resolve(typeof specified==='string'?specified:path.join(opts.reportOutput,REPORTS[format].name))};});
|
|
47
|
+
}
|
|
48
|
+
function makeCommand() {
|
|
49
|
+
const command = new Command().name('vigievuln image').description('Native image, rootfs and publisher-inventory audit. No Docker or package-manager execution.')
|
|
50
|
+
.argument('[input]', 'Docker/OCI/rootfs archive, directory, registry reference or inventory')
|
|
51
|
+
.option('--config <file>', 'read scan configuration from a JSON file')
|
|
52
|
+
.option('--source-profile <profile>', 'advisory operator scope: all, us, eu or proxy')
|
|
53
|
+
.option('--proxy <url>', 'corporate forward proxy for outbound connections')
|
|
54
|
+
.option('--proxy-cache <url|vigievuln|default>', 'use a shared advisory proxy')
|
|
55
|
+
.option('--proxy-rate-limit-wait-ms <milliseconds>', 'maximum proxy retry wait per request (default: 45000)', Number)
|
|
56
|
+
.option('--reuse-stable-advisories', 'reuse cached individual advisories unchanged for at least the configured age', true)
|
|
57
|
+
.option('--no-reuse-stable-advisories', 'refresh older individual advisories using normal cache lifetimes')
|
|
58
|
+
.option('--stable-advisory-age-days <days>', 'minimum unchanged advisory age for reuse (default: 365)', Number)
|
|
59
|
+
.option('--force-update', 'revalidate consulted online sources, retaining cached data on failure')
|
|
60
|
+
.option('--proxy-cache-token <token>', 'shared advisory proxy authentication token')
|
|
61
|
+
.option('--vigievuln-proxy [domain]', 'use the hosted VigieVuln proxy, fr or com')
|
|
62
|
+
.option('--allow-insecure-http', 'allow HTTP to the configured advisory proxy for this invocation')
|
|
63
|
+
.option('--registry', 'obtain input directly from an OCI registry; offline uses a prepared cached inventory')
|
|
64
|
+
.option('--platform <os/arch[/variant]>', 'select an image platform; otherwise inspect all available platforms')
|
|
65
|
+
.option('--prefer-sbom', 'prefer publisher SBOMs when associated with the selected images; signatures remain unverified')
|
|
66
|
+
.option('--registry-auth <file>', 'JSON credentials {username,password,token,authOrigins}; never invokes credential helpers')
|
|
67
|
+
.option('--insecure', 'allow HTTP registry endpoints explicitly')
|
|
68
|
+
.option('--inventory', 'input is an exported VigieVuln artifact inventory')
|
|
69
|
+
.option('--sbom', 'input is a CycloneDX/SPDX or attestation JSON document')
|
|
70
|
+
.option('--expected-digest <digest>', 'require a supplied SBOM subject to agree with this image digest')
|
|
71
|
+
.option('--advisory-config <file>', 'JSON custom distribution advisory scope and optional source URL')
|
|
72
|
+
.option('--distribution <id:release>', 'explicit distribution scope for imported advisories or SBOM', distribution)
|
|
73
|
+
.option('--offline', 'zero network access; use imported advisory snapshots and cached inventories')
|
|
74
|
+
.option('--enrich <sources>', 'enrichment sources: nvd,kev,epss,gcve,euvd,certfr or none', value => value === 'none' ? [] : value.split(',').map(s => s.trim()), ['nvd', 'kev', 'epss', 'gcve', 'euvd', 'certfr'])
|
|
75
|
+
.option('--no-osv', 'exclude OSV advisory matching')
|
|
76
|
+
.option('--no-distro-advisories', 'exclude independent distribution tracker consultations')
|
|
77
|
+
.option('--no-publisher-advisories', 'exclude publisher advisory feeds')
|
|
78
|
+
.option('--no-nvd', 'exclude NVD enrichment')
|
|
79
|
+
.option('--no-kev', 'exclude CISA KEV enrichment')
|
|
80
|
+
.option('--no-epss', 'exclude EPSS enrichment')
|
|
81
|
+
.option('--no-gcve', 'exclude native GCVE advisory matching and derived aliases')
|
|
82
|
+
.option('--no-euvd', 'exclude ENISA EUVD enrichment')
|
|
83
|
+
.option('--no-certfr', 'exclude CERT-FR enrichment')
|
|
84
|
+
.option('--cache-dir <directory>', 'cache directory containing prepared vulnerability data')
|
|
85
|
+
.option('--prepare-cache <file>', 'warm and export advisory cache for an inventory')
|
|
86
|
+
.option('--definitions <directory>', 'find image declarations in source; only explicit matching digests bind to scanned images')
|
|
87
|
+
.option('--export-inventory <file>', 'save portable inventory independently of image contents')
|
|
88
|
+
.option('--import-advisories <file>', 'import a native OSV JSON/JSONL/ZIP dataset for --distribution')
|
|
89
|
+
.option('--snapshot-complete', 'declare imported dataset complete for the stated distribution release')
|
|
90
|
+
.option('--sync-advisories', 'prepare a distribution advisory snapshot online; requires --distribution when no image is supplied')
|
|
91
|
+
.option('--limits <file>', 'JSON resource policy {artifactLimits,registryLimits,maxMetadataBytes,...}')
|
|
92
|
+
.option('--report-output <directory>', 'report directory', './vigievuln-report')
|
|
93
|
+
.option('-r, --reports <formats>', 'comma-separated report formats: ' + Object.keys(REPORTS).join(','))
|
|
94
|
+
.option('--no-report', 'write no reports; inventory export and CI gates remain active')
|
|
95
|
+
.option('--fail-on <severity>', 'fail with exit 1 for matching findings: low,medium,high,critical,kev', 'none')
|
|
96
|
+
.option('--fail-on-incomplete [capabilities]', 'exit 2 for incomplete inventory/advisories/sources', false)
|
|
97
|
+
.option('--lang <language>', 'report language: en or fr', 'en');
|
|
98
|
+
for (const format of Object.keys(REPORTS)) command.option(`--report-${format} [file]`, `write ${format} report`);
|
|
99
|
+
return command;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function run(args, injected = {}) {
|
|
103
|
+
const command = makeCommand();
|
|
104
|
+
command.parse(args, { from: 'user' });
|
|
105
|
+
const setup = require('./image-network').configureImageNetwork(command, injected);
|
|
106
|
+
try {
|
|
107
|
+
const opts = setup.options, input = command.args[0];
|
|
108
|
+
for (const warning of setup.warnings) console.warn(`⚠ ${warning}`);
|
|
109
|
+
if (![opts.registry, opts.inventory, opts.sbom].filter(Boolean).length) opts.mode = 'artifact';
|
|
110
|
+
if ([opts.registry, opts.inventory, opts.sbom].filter(Boolean).length > 1) throw Error('--registry, --inventory and --sbom are mutually exclusive');
|
|
111
|
+
if (opts.preferSbom && !opts.registry) throw Error('--prefer-sbom requires --registry');
|
|
112
|
+
if (opts.prepareCache && (!opts.inventory || opts.offline)) throw Error('--prepare-cache requires an inventory and online mode');
|
|
113
|
+
if (!['en', 'fr'].includes(opts.lang)) throw Error('--lang must be en or fr');
|
|
114
|
+
if (!['none', 'low', 'medium', 'high', 'critical', 'kev'].includes(opts.failOn)) throw Error('invalid --fail-on severity');
|
|
115
|
+
const required = opts.failOnIncomplete ? (opts.failOnIncomplete === true ? 'inventory,advisories,sources' : opts.failOnIncomplete).split(',').map(x => x.trim()) : [];
|
|
116
|
+
if (required.some(x => !['inventory', 'advisories', 'sources'].includes(x))) throw Error('invalid --fail-on-incomplete capability');
|
|
117
|
+
const cacheDir = opts.cacheDir;
|
|
118
|
+
const policy = opts.limits ? jsonFile(opts.limits) : {};
|
|
119
|
+
const credentials = opts.registryAuth ? jsonFile(opts.registryAuth) : {
|
|
120
|
+
token: process.env.VIGIEVULN_REGISTRY_TOKEN, username: process.env.VIGIEVULN_REGISTRY_USER, password: process.env.VIGIEVULN_REGISTRY_PASSWORD,
|
|
121
|
+
};
|
|
122
|
+
const options = { ...policy, ...opts, cacheDir, credentials, authOrigins: credentials.authOrigins || [],
|
|
123
|
+
...(opts.advisoryConfig ? { advisoryConfig: typeof opts.advisoryConfig === 'string' ? jsonFile(opts.advisoryConfig) : opts.advisoryConfig } : {}) };
|
|
124
|
+
if (opts.osv === false && (opts.importAdvisories || opts.syncAdvisories)) throw Error('OSV advisories are excluded by the selected source profile');
|
|
125
|
+
if (opts.importAdvisories) {
|
|
126
|
+
if (!opts.distribution) throw Error('--import-advisories requires --distribution');
|
|
127
|
+
const imported = await require('./system-inventory').importSystemAdvisories(opts.importAdvisories, { ...options, complete: !!opts.snapshotComplete });
|
|
128
|
+
console.log(`Imported ${imported.recordCount} advisory records for ${imported.ecosystem}.`);
|
|
129
|
+
}
|
|
130
|
+
if (!input) {
|
|
131
|
+
if (opts.syncAdvisories) {
|
|
132
|
+
if (!opts.distribution) throw Error('--sync-advisories requires --distribution when no image is supplied');
|
|
133
|
+
const synced = await require('./system-inventory').syncSystemAdvisories(opts.distribution, options);
|
|
134
|
+
console.log(`Prepared ${synced.recordCount} advisory records for ${synced.ecosystem}.`);
|
|
135
|
+
return { synced };
|
|
136
|
+
}
|
|
137
|
+
if (opts.importAdvisories) return {};
|
|
138
|
+
throw Error('an image/archive/rootfs/inventory input is required; see vigievuln image --help');
|
|
139
|
+
}
|
|
140
|
+
const reports = reportFiles(opts);
|
|
141
|
+
const outputs = [...(opts.exportInventory ? [{label:'inventory',file:path.resolve(opts.exportInventory)}] : []), ...(opts.prepareCache ? [{label:'cache',file:path.resolve(opts.prepareCache)}] : []), ...reports.map(r => ({label:r.format,file:r.file}))];
|
|
142
|
+
if (reports.length) outputs.push({label:'checksums',file:path.join(path.dirname(reports[0].file),'SHA256SUMS')});
|
|
143
|
+
for (let i=0;i<outputs.length;i++) {
|
|
144
|
+
if (fs.existsSync(input) && sameFile(input,outputs[i].file)) throw Error(`${outputs[i].label} output must not overwrite the input artifact`);
|
|
145
|
+
for(let j=0;j<i;j++) if(sameFile(outputs[i].file,outputs[j].file)) throw Error('output paths must be distinct');
|
|
146
|
+
}
|
|
147
|
+
const targets = await acquireInventories(input, options);
|
|
148
|
+
const savedReferences = new Map();
|
|
149
|
+
for (const target of targets) for (const ref of target.metadata?.declarations || []) if (ref?.id && !savedReferences.has(ref.id)) savedReferences.set(ref.id, ref);
|
|
150
|
+
let imageReferences = [...savedReferences.values()];
|
|
151
|
+
if (opts.definitions) {
|
|
152
|
+
const discovery = require('./image-references').discoverImageReferences(path.resolve(opts.definitions));
|
|
153
|
+
imageReferences = require('./image-references').bindImageDefinitions(targets, discovery.references);
|
|
154
|
+
for (const target of targets) target.metadata.definitionDiscovery = { status: discovery.warnings.length ? 'incomplete' : target.metadata.definitions.length ? 'matched' : 'no-match', source: path.basename(path.resolve(opts.definitions)) };
|
|
155
|
+
if (discovery.warnings.length) for (const target of targets) target.warnings.push(...discovery.warnings.map(w => ({ ...w, capability: 'inventory' })));
|
|
156
|
+
}
|
|
157
|
+
if (opts.exportInventory) await writeSnapshot(opts.exportInventory, targets);
|
|
158
|
+
const result = await assessInventories(targets, options);
|
|
159
|
+
if (opts.prepareCache) {
|
|
160
|
+
const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
|
|
161
|
+
if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
|
|
162
|
+
const prepared = await require('./cache-archive-sqlite').exportCache(opts.prepareCache, { sourceDir: cacheDir,
|
|
163
|
+
proxyOrigin: options.proxyCache ? require('./proxy-scope').proxyOrigin(options.proxyCache) : undefined });
|
|
164
|
+
console.log(`Prepared cache: ${prepared.path}`);
|
|
165
|
+
}
|
|
166
|
+
const toolVersion = require('../package.json').version;
|
|
167
|
+
const payload = { ...result, toolVersion, locale: opts.lang,
|
|
168
|
+
projectInfo: { name: path.basename(input), src: '(artifact inventory)', toolVersion, generatedAt: new Date().toISOString(),
|
|
169
|
+
artifacts: result.artifacts, ...(imageReferences.length ? { imageReferences } : {}), provenance: { mode: opts.offline ? 'offline' : 'online',notices:[...(setup.notices||[]),...(result.notices||[])],
|
|
170
|
+
dataSources: result.artifacts.flatMap(a => a.coverage.filter(c => c.capability === 'advisories' || c.capability === 'sources').map(c => ({
|
|
171
|
+
label: c.ecosystem || c.source || c.collector, status: c.execution === 'not-applicable' ? 'disabled' : c.execution === 'completed' ? 'cached' : 'missing',
|
|
172
|
+
asOf: c.fetchedAt ? new Date(c.fetchedAt).toISOString() : null, detail: c.reason || c.execution }))) } } };
|
|
173
|
+
let written = [];
|
|
174
|
+
if (opts.report !== false) {
|
|
175
|
+
for (const { format, file } of reports) {
|
|
176
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
177
|
+
await REPORTS[format].write(payload, file);
|
|
178
|
+
written.push(file);
|
|
179
|
+
}
|
|
180
|
+
if (written.length) {
|
|
181
|
+
const checksum = path.join(path.dirname(written[0]), 'SHA256SUMS');
|
|
182
|
+
require('./report-integrity').writeChecksums(written, checksum, { baseDir: path.dirname(checksum) });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const gate = require('./gate').evaluateGate(result.cveMatches, opts.failOn);
|
|
186
|
+
const gaps = incompleteCapabilities(result, required);
|
|
187
|
+
if (opts.failOn === 'kev') {
|
|
188
|
+
gaps.push(...incompleteCapabilities(result, ['advisories']));
|
|
189
|
+
for (const artifact of result.artifacts) {
|
|
190
|
+
const hasCve = result.cveMatches.some(m => m.dep.artifactTargetId === artifact.id);
|
|
191
|
+
const kev = artifact.coverage.find(c => c.capability === 'sources' && c.collector === 'kev');
|
|
192
|
+
if (hasCve && (!kev || kev.execution !== 'completed')) gaps.push({ target: artifact.id, capability: 'kev' });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const malicious = result.cveMatches.some(m => m.malicious && !m.suppressed);
|
|
196
|
+
const exitCode = gaps.length ? 2 : gate.failed || malicious ? 1 : 0;
|
|
197
|
+
process.exitCode = exitCode;
|
|
198
|
+
console.log(`${result.artifacts.length} artifact(s), ${result.resolvedDeps.size} components, ${result.cveMatches.length} findings, ${result.warnings.length} warning(s).`);
|
|
199
|
+
for (const warning of result.warnings) console.warn(`⚠ ${warning.message}`);
|
|
200
|
+
for (const file of written) console.log(file);
|
|
201
|
+
if (gaps.length) console.warn(`Required coverage incomplete: ${[...new Set(gaps.map(g => g.capability))].join(', ')}.`);
|
|
202
|
+
return { ...result, written, exitCode };
|
|
203
|
+
} finally { setup.restore(); }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { run, makeCommand, REPORTS };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Parse file-backed ELF structures without executing the inspected file.
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const MAX_SEGMENT = 32 * 1024 * 1024;
|
|
4
|
+
function extractElfMetadataFile(fd, size, options = {}) {
|
|
5
|
+
try {
|
|
6
|
+
const max = options.maxMetadataBytes || MAX_SEGMENT;
|
|
7
|
+
function read(pos, n) {
|
|
8
|
+
if (!Number.isSafeInteger(pos) || !Number.isSafeInteger(n) || pos < 0 || n < 0 || n > max || pos + n > size) throw Error('ELF bounds or metadata limit');
|
|
9
|
+
const b = Buffer.alloc(n); let off = 0;
|
|
10
|
+
while (off < n) { const got = fs.readSync(fd, b, off, n - off, pos + off); if (!got) throw Error('ELF truncated'); off += got; }
|
|
11
|
+
return b;
|
|
12
|
+
}
|
|
13
|
+
const h = read(0, 16);
|
|
14
|
+
if (!h.subarray(0, 4).equals(Buffer.from([127,69,76,70])) || ![1,2].includes(h[4]) || ![1,2].includes(h[5])) throw Error('unsupported ELF class or byte order');
|
|
15
|
+
const bits = h[4] === 1 ? 32 : 64, le = h[5] === 1;
|
|
16
|
+
const u16 = (b,p) => le ? b.readUInt16LE(p) : b.readUInt16BE(p);
|
|
17
|
+
const u32 = (b,p) => le ? b.readUInt32LE(p) : b.readUInt32BE(p);
|
|
18
|
+
const word = (b,p) => { const v = bits === 32 ? BigInt(u32(b,p)) : le ? b.readBigUInt64LE(p) : b.readBigUInt64BE(p); if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw Error('ELF integer exceeds safe range'); return Number(v); };
|
|
19
|
+
const header = read(0, bits === 32 ? 52 : 64);
|
|
20
|
+
const phoff = word(header, bits === 32 ? 28 : 32), phentsize = u16(header, bits === 32 ? 42 : 54), phnum = u16(header, bits === 32 ? 44 : 56);
|
|
21
|
+
if (phnum > 4096 || (phnum && phentsize < (bits === 32 ? 32 : 56))) throw Error('unsupported ELF program header table');
|
|
22
|
+
const table = read(phoff, phnum * phentsize), segments = [];
|
|
23
|
+
for (let i = 0; i < phnum; i++) { const p = i * phentsize; const type = u32(table,p), flags = u32(table,p + (bits === 32 ? 24 : 4)); const offset = word(table,p + (bits === 32 ? 4 : 8)), vaddr = word(table,p + (bits === 32 ? 8 : 16)), filesz = word(table,p + (bits === 32 ? 16 : 32)); if (offset + filesz > size) throw Error('ELF segment outside file'); segments.push({ type, flags, offset, vaddr, filesz }); }
|
|
24
|
+
const mapped = (addr,n) => { const s = segments.find(x => x.type === 1 && addr >= x.vaddr && addr - x.vaddr + n <= x.filesz); if (!s) throw Error('ELF unmapped address'); return s.offset + addr - s.vaddr; };
|
|
25
|
+
const result = { format:'elf', bits, endian: le ? 'little' : 'big', machine: u16(header,18), type: u16(header,16), needed: [] };
|
|
26
|
+
const interp = segments.find(s => s.type === 3); if (interp && interp.filesz) result.interpreter = read(interp.offset,interp.filesz).toString('utf8').replace(/\0.*$/s,'');
|
|
27
|
+
for (const s of segments.filter(x => x.type === 4)) {
|
|
28
|
+
const b = read(s.offset,s.filesz); let p = 0;
|
|
29
|
+
while (p + 12 <= b.length) { const namesz = u32(b,p), descsz = u32(b,p+4), type = u32(b,p+8); p += 12; const a = Math.ceil(namesz/4)*4, d = Math.ceil(descsz/4)*4; if (p + a + d > b.length) break; if (type === 3 && b.subarray(p,p+namesz).toString('ascii').replace(/\0+$/,'') === 'GNU' && descsz <= 1024) result.buildId = b.subarray(p+a,p+a+descsz).toString('hex'); p += a+d; }
|
|
30
|
+
}
|
|
31
|
+
const dynamic = segments.find(s => s.type === 2);
|
|
32
|
+
if (dynamic) {
|
|
33
|
+
const b = read(dynamic.offset,dynamic.filesz), step = bits === 32 ? 8 : 16; let str = null, strsz = null, soname = null; const needed=[];
|
|
34
|
+
for (let p=0; p+step<=b.length; p+=step) { const tag=word(b,p), val=word(b,p+step/2); if (!tag) break; if(tag===5) str=val; else if(tag===10) strsz=val; else if(tag===1) needed.push(val); else if(tag===14) soname=val; }
|
|
35
|
+
if (str !== null && strsz !== null && strsz <= max) { const strings=read(mapped(str,strsz),strsz); const get = n => { if(n>=strings.length) throw Error('ELF string offset'); const end=strings.indexOf(0,n); if(end<0) throw Error('ELF unterminated string'); return strings.toString('utf8',n,end); }; result.needed=needed.map(get); if(soname!==null) result.soname=get(soname); }
|
|
36
|
+
}
|
|
37
|
+
result.go = require('./go-buildinfo').extractGoBuildInfo({read, segments, mapped, max});
|
|
38
|
+
if (!result.go) delete result.go;
|
|
39
|
+
return result;
|
|
40
|
+
} catch (error) { return { format:'elf', status:'unavailable', reason:error.message }; }
|
|
41
|
+
}
|
|
42
|
+
module.exports = { extractElfMetadataFile, MAX_SEGMENT };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Go linker build-info blob; supports inline and pre-1.18 pointer formats.
|
|
2
|
+
const MAGIC = Buffer.from('\xff Go buildinf:', 'latin1');
|
|
3
|
+
function extractGoBuildInfo({read, segments, mapped, max}) {
|
|
4
|
+
try {
|
|
5
|
+
let budget = max, skipped = false;
|
|
6
|
+
for (const s of segments.filter(x => x.type === 1 && (x.flags & 2) && x.filesz)) {
|
|
7
|
+
if (s.filesz > budget) { skipped = true; continue; }
|
|
8
|
+
budget -= s.filesz;
|
|
9
|
+
const b = read(s.offset,s.filesz);
|
|
10
|
+
for (let pos = b.indexOf(MAGIC); pos >= 0; pos = b.indexOf(MAGIC,pos+1)) {
|
|
11
|
+
if ((s.vaddr+pos)%16 || pos+32>b.length) continue;
|
|
12
|
+
const ptrSize=b[pos+14], flags=b[pos+15]; if (![4,8].includes(ptrSize) || (flags & ~3)) continue;
|
|
13
|
+
const le=!(flags&1);
|
|
14
|
+
const ptr=(buf,p) => { const n=ptrSize===4 ? BigInt(le?buf.readUInt32LE(p):buf.readUInt32BE(p)) : le?buf.readBigUInt64LE(p):buf.readBigUInt64BE(p); if(n>BigInt(Number.MAX_SAFE_INTEGER)) throw Error('pointer overflow'); return Number(n); };
|
|
15
|
+
const memory=(addr,n)=>read(mapped(addr,n),n);
|
|
16
|
+
let version, mod;
|
|
17
|
+
if (flags&2) {
|
|
18
|
+
let p=pos+32;
|
|
19
|
+
const string=()=>{ let n=0, mult=1, c, count=0; do { if(p>=b.length || count++>=8) throw Error('varint'); c=b[p++]; n+=(c&127)*mult; mult*=128; } while(c&128); if(!Number.isSafeInteger(n) || n>max || p+n>b.length) throw Error('string bounds'); const t=b.toString('latin1',p,p+n); p+=n; return t; };
|
|
20
|
+
version=string(); mod=string();
|
|
21
|
+
} else {
|
|
22
|
+
const str=addr=>{ if(!addr)return ''; const hdr=memory(addr,ptrSize*2), start=ptr(hdr,0), len=ptr(hdr,ptrSize); if(len>max) throw Error('string limit'); return memory(start,len).toString('latin1'); };
|
|
23
|
+
version=str(ptr(b,pos+16)); mod=str(ptr(b,pos+16+ptrSize));
|
|
24
|
+
}
|
|
25
|
+
if (!version.startsWith('go')) continue;
|
|
26
|
+
// Module text is surrounded by 16-byte sentinels, as in debug/buildinfo.
|
|
27
|
+
if (mod.length >= 33 && mod[mod.length-17] === '\n') mod=Buffer.from(mod.slice(16,-16),'latin1').toString('utf8'); else mod='';
|
|
28
|
+
const modules=[],settings={}; let last=null;
|
|
29
|
+
for (const line of mod.split('\n')) { const f=line.split('\t'); if ((f[0]==='mod'||f[0]==='dep') && f.length>=3) { last={kind:f[0],path:f[1],version:f[2],sum:f[3]||null}; modules.push(last); } else if(f[0]==='=>' && last && f.length>=2) last.replace={path:f[1],version:f[2] || null,sum:f[3]||null}; else if(f[0]==='build' && f.length===2) { const i=f[1].indexOf('='); if(i>0) {const key=f[1].slice(0,i),value=f[1].slice(i+1);if(/^[A-Za-z0-9_.-]{1,80}$/.test(key) && value.length<=1024) {if(Object.hasOwn(settings,key))settings[key]=null;else settings[key]=value;}} } }
|
|
30
|
+
return { version, modules, settings };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (skipped) return {status:'unavailable',reason:'Go build information search exceeded metadata limit'};
|
|
34
|
+
} catch { return {status:'unavailable',reason:'Malformed Go build information'}; }
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
module.exports={extractGoBuildInfo};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Format registry keeps new binary parsers independent of the walker.
|
|
2
|
+
const extractors = new Map([
|
|
3
|
+
['pe', (fd,size) => require('./pe-metadata').extractPeMetadataFile(fd,size)],
|
|
4
|
+
['elf', (fd,size,opts) => require('./elf-metadata').extractElfMetadataFile(fd,size,opts)],
|
|
5
|
+
]);
|
|
6
|
+
function extractMetadata(kind,fd,size,opts) { const fn=extractors.get(kind); return fn ? fn(fd,size,opts) : {format:kind,status:'unsupported'}; }
|
|
7
|
+
module.exports={extractors,extractMetadata};
|
|
@@ -76,4 +76,30 @@ function extractPeMetadata(buf) {
|
|
|
76
76
|
} catch { return null; }
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
-
|
|
79
|
+
// Adapt the bounded parser to a file descriptor. One 64 KiB cache serves the
|
|
80
|
+
// many small header/string reads; even a distant resource never loads the file.
|
|
81
|
+
function extractPeMetadataFile(fd, size) {
|
|
82
|
+
const fs = require("node:fs");
|
|
83
|
+
let start = -1, cache = Buffer.alloc(0);
|
|
84
|
+
const read = (offset, length) => {
|
|
85
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || length < 0 || length > MAX_VERSION_INFO || offset + length > size) throw Error("bounds");
|
|
86
|
+
if (offset < start || offset + length > start + cache.length) {
|
|
87
|
+
start = offset;
|
|
88
|
+
cache = Buffer.alloc(Math.min(size - offset, Math.max(64 * 1024, length)));
|
|
89
|
+
let count = 0;
|
|
90
|
+
while (count < cache.length) {
|
|
91
|
+
const n = fs.readSync(fd, cache, count, cache.length - count, start + count);
|
|
92
|
+
if (!n) throw Error("unexpected EOF reading PE metadata");
|
|
93
|
+
count += n;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return cache.subarray(offset - start, offset - start + length);
|
|
97
|
+
};
|
|
98
|
+
return extractPeMetadata({ length: size,
|
|
99
|
+
readUInt16LE: offset => read(offset, 2).readUInt16LE(0),
|
|
100
|
+
readUInt32LE: offset => read(offset, 4).readUInt32LE(0),
|
|
101
|
+
toString: (encoding, begin, end) => read(begin, end - begin).toString(encoding),
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
module.exports = { extractPeMetadata, extractPeMetadataFile };
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
* (.dll/.exe/.so/.dylib) and hash each. Dependency archives (.jar/.war/.ear) are
|
|
4
4
|
* owned by the Maven codec's jar-scan.js, not here.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* hashed or reported.
|
|
6
|
+
* ELF magic is recognized regardless of filename; PE and Mach-O also require
|
|
7
|
+
* an appropriate extension. Other data and spoofed extensions are rejected.
|
|
9
8
|
*
|
|
10
9
|
* @author: N.BRAUN
|
|
11
10
|
* @email: pp9ping@gmail.com
|
|
@@ -23,50 +22,69 @@ const SKIP = new Set([
|
|
|
23
22
|
|
|
24
23
|
const MAGIC_BYTES = 8; // enough for every signature we sniff
|
|
25
24
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
sha1: crypto.createHash("sha1").update(buf).digest("hex"),
|
|
31
|
-
sha256: crypto.createHash("sha256").update(buf).digest("hex"),
|
|
32
|
-
metadata: kind === "pe" ? require("./pe-metadata").extractPeMetadata(buf) : null,
|
|
33
|
-
};
|
|
34
|
-
}
|
|
25
|
+
// Bound both memory and work: large files are explicitly unassessed, never
|
|
26
|
+
// silently dropped or loaded into a multi-gigabyte Buffer.
|
|
27
|
+
const MAX_FILE_BYTES = 512 * 1024 * 1024;
|
|
28
|
+
const HASH_CHUNK_BYTES = 1024 * 1024;
|
|
35
29
|
|
|
36
|
-
function
|
|
30
|
+
function inspectFile(fp, kind, detectOnly, opts = {}) {
|
|
37
31
|
let fd;
|
|
38
32
|
try {
|
|
39
33
|
fd = fs.openSync(fp, "r");
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
34
|
+
const before = fs.fstatSync(fd);
|
|
35
|
+
if (!before.isFile()) throw Error("not a regular file");
|
|
36
|
+
const magic = Buffer.alloc(MAGIC_BYTES);
|
|
37
|
+
const n = fs.readSync(fd, magic, 0, magic.length, 0);
|
|
38
|
+
const actual = sniffKind(magic.subarray(0, n));
|
|
39
|
+
if (!actual || (actual !== "elf" && actual !== kind)) return null;
|
|
40
|
+
kind = actual;
|
|
41
|
+
if (detectOnly) return { kind };
|
|
42
|
+
const limit = opts.maxFileBytes ?? MAX_FILE_BYTES;
|
|
43
|
+
if (before.size > limit) throw Error(`file size ${before.size} exceeds binary scan limit ${limit} bytes`);
|
|
44
|
+
const sha1 = crypto.createHash("sha1"), sha256 = crypto.createHash("sha256");
|
|
45
|
+
const chunk = Buffer.alloc(Math.min(HASH_CHUNK_BYTES, before.size));
|
|
46
|
+
let offset = 0;
|
|
47
|
+
while (offset < before.size) {
|
|
48
|
+
const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, before.size - offset), offset);
|
|
49
|
+
if (!count) throw Error("file changed or unexpected EOF while hashing");
|
|
50
|
+
sha1.update(chunk.subarray(0, count)); sha256.update(chunk.subarray(0, count));
|
|
51
|
+
offset += count;
|
|
52
|
+
}
|
|
53
|
+
const metadata = require("./metadata").extractMetadata(kind, fd, before.size, opts);
|
|
54
|
+
const after = fs.fstatSync(fd);
|
|
55
|
+
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs)
|
|
56
|
+
throw Error("file changed during binary scan");
|
|
57
|
+
return { kind, size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
|
|
58
|
+
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
45
59
|
}
|
|
46
60
|
|
|
47
61
|
/** Walk `dir`, return [{ path, kind, size, sha1, sha256, declaredName }]. */
|
|
48
62
|
function scanBinaries(dir, opts = {}) {
|
|
49
|
-
const { onProgress } = opts;
|
|
63
|
+
const { onProgress, onWarning } = opts;
|
|
64
|
+
const warn = (fp, error) => onWarning?.({ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: fp,
|
|
65
|
+
message: `binary scan incomplete for ${fp}: ${error.message}` });
|
|
50
66
|
const { makeDirFilter } = require("../../path-filter");
|
|
51
67
|
const skipDir = makeDirFilter({ srcRoot: opts.srcRoot || dir, defaultSkip: SKIP, excludePath: opts.excludePath, useDefaults: opts.defaultExcludes !== false });
|
|
52
68
|
const out = [];
|
|
53
69
|
const stack = [dir];
|
|
54
70
|
while (stack.length) {
|
|
55
71
|
const cur = stack.pop();
|
|
56
|
-
let entries; try { entries = fs.readdirSync(cur, { withFileTypes: true }); } catch { continue; }
|
|
72
|
+
let entries; try { entries = fs.readdirSync(cur, { withFileTypes: true }); } catch (error) { warn(cur, error); continue; }
|
|
57
73
|
for (const e of entries) {
|
|
58
74
|
const fp = path.join(cur, e.name);
|
|
59
75
|
if (e.isDirectory()) { if (!skipDir(fp, e.name)) stack.push(fp); continue; }
|
|
60
76
|
if (!e.isFile()) continue;
|
|
61
77
|
const ext = extKind(e.name);
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
78
|
+
try {
|
|
79
|
+
const h = inspectFile(fp, ext, opts.detectOnly, opts);
|
|
80
|
+
if (!h) continue;
|
|
81
|
+
if (onProgress) onProgress(fp);
|
|
82
|
+
out.push({ path: fp, ...h, declaredName: e.name });
|
|
83
|
+
if (opts.detectOnly) return out;
|
|
84
|
+
} catch (error) { warn(fp, error); }
|
|
67
85
|
}
|
|
68
86
|
}
|
|
69
87
|
return out;
|
|
70
88
|
}
|
|
71
89
|
|
|
72
|
-
module.exports = { scanBinaries };
|
|
90
|
+
module.exports = { scanBinaries, MAX_FILE_BYTES };
|
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* lib/codecs/binary/sniff.js — file-type confirmation for the binary codec.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* magic) is rejected. We never trust the extension alone.
|
|
4
|
+
* ELF is identified by magic irrespective of filename. PE and Mach-O retain
|
|
5
|
+
* extension and magic confirmation, avoiding ambiguous signatures.
|
|
7
6
|
*
|
|
8
7
|
* @author: N.BRAUN
|
|
9
8
|
* @email: pp9ping@gmail.com
|
|
10
9
|
*/
|
|
11
10
|
|
|
12
|
-
//
|
|
11
|
+
// Format detectors are ordered; extensions remain hints for formats whose
|
|
12
|
+
// signatures can overlap other file types (notably Mach-O fat binaries).
|
|
13
|
+
const detectors = [
|
|
14
|
+
{ kind: "pe", matches: b => b[0] === 0x4d && b[1] === 0x5a },
|
|
15
|
+
{ kind: "elf", matches: b => b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46 },
|
|
16
|
+
{ kind: "zip", matches: b => b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04 },
|
|
17
|
+
{ kind: "macho", matches: b => {
|
|
18
|
+
const signatures = [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf];
|
|
19
|
+
return signatures.includes(b.readUInt32BE(0)) || signatures.includes(b.readUInt32LE(0));
|
|
20
|
+
} },
|
|
21
|
+
];
|
|
13
22
|
function sniffKind(buf) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (b0 === 0x4d && b1 === 0x5a) return "pe"; // MZ
|
|
17
|
-
if (b0 === 0x7f && b1 === 0x45 && b2 === 0x4c && b3 === 0x46) return "elf"; // \x7FELF
|
|
18
|
-
if (b0 === 0x50 && b1 === 0x4b && b2 === 0x03 && b3 === 0x04) return "zip"; // PK\x03\x04
|
|
19
|
-
const be = ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) >>> 0;
|
|
20
|
-
const le = ((b3 << 24) | (b2 << 16) | (b1 << 8) | b0) >>> 0;
|
|
21
|
-
const machO = new Set([0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf]);
|
|
22
|
-
if (machO.has(be) || machO.has(le)) return "macho";
|
|
23
|
-
return null;
|
|
23
|
+
if (!buf || buf.length < 4) return null;
|
|
24
|
+
return detectors.find(d => d.matches(buf))?.kind || null;
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
const EXT_PE = /\.(dll|exe)$/i;
|
|
@@ -34,4 +35,4 @@ function extKind(name) {
|
|
|
34
35
|
return null;
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
module.exports = { sniffKind, extKind };
|
|
38
|
+
module.exports = { sniffKind, extKind, detectors };
|
|
@@ -17,10 +17,17 @@ module.exports = {
|
|
|
17
17
|
id: "binary",
|
|
18
18
|
label: "Binaries",
|
|
19
19
|
osvEcosystem: null, // no OSV ecosystem until identified
|
|
20
|
-
manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"],
|
|
20
|
+
manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"],
|
|
21
|
+
async detectFile(fp) {
|
|
22
|
+
const fs = require("fs"); let handle;
|
|
23
|
+
try { handle = await fs.promises.open(fp, "r"); const b = Buffer.alloc(4); const { bytesRead } = await handle.read(b, 0, 4, 0); return require("./binary/sniff").sniffKind(b.subarray(0, bytesRead)) === "elf"; } catch { return false; } finally { if (handle) await handle.close(); }
|
|
24
|
+
}, // lets detectCodecs include us in auto mode
|
|
21
25
|
|
|
22
26
|
detect(dir) {
|
|
23
|
-
try {
|
|
27
|
+
try {
|
|
28
|
+
let incomplete = false;
|
|
29
|
+
return scanBinaries(dir, { detectOnly: true, onWarning: () => { incomplete = true; } }).length > 0 || incomplete;
|
|
30
|
+
}
|
|
24
31
|
catch { return false; }
|
|
25
32
|
},
|
|
26
33
|
|
|
@@ -28,8 +35,8 @@ module.exports = {
|
|
|
28
35
|
const out = new Map();
|
|
29
36
|
const warnings = [];
|
|
30
37
|
let records;
|
|
31
|
-
try { records = scanBinaries(dir, { onProgress: opts.onBinaryProgress, srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
|
|
32
|
-
catch (e) { return { deps: out, warnings: [{ type: "scan-error", message: `binary scan failed: ${e.message}` }] }; }
|
|
38
|
+
try { records = scanBinaries(dir, { ...opts, onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
|
|
39
|
+
catch (e) { return { deps: out, warnings: [{ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: dir, message: `binary scan failed: ${e.message}` }] }; }
|
|
33
40
|
for (const r of records) {
|
|
34
41
|
const record = makeDepRecord({
|
|
35
42
|
ecosystem: "binary",
|
|
@@ -42,6 +49,22 @@ module.exports = {
|
|
|
42
49
|
});
|
|
43
50
|
if (r.metadata) record.binaryMetadata = r.metadata;
|
|
44
51
|
out.set(`binary:${r.path}`, record);
|
|
52
|
+
const goVersion = /^go(\d+)\.(\d+)(?:\.(\d+))?$/.exec(r.metadata?.go?.version || "");
|
|
53
|
+
if (goVersion) {
|
|
54
|
+
const version = `v${goVersion[1]}.${goVersion[2]}.${goVersion[3] || "0"}`;
|
|
55
|
+
const dep = makeDepRecord({ ecosystem: "go", name: "stdlib", version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
|
|
56
|
+
dep.coordKey = `binary-module:${r.path}:stdlib@${version}`;
|
|
57
|
+
dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", runtimeVersion: r.metadata.go.version, symbolReachability: "unknown" };
|
|
58
|
+
out.set(dep.coordKey, dep);
|
|
59
|
+
}
|
|
60
|
+
for (const module of r.metadata?.go?.modules || []) {
|
|
61
|
+
const selected = module.replace || module;
|
|
62
|
+
if (!selected.path || !/^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(selected.version || "")) continue;
|
|
63
|
+
const dep = makeDepRecord({ ecosystem: "go", name: selected.path, version: selected.version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
|
|
64
|
+
dep.coordKey = `binary-module:${r.path}:${selected.path}@${selected.version}`;
|
|
65
|
+
dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", original: module };
|
|
66
|
+
out.set(dep.coordKey, dep);
|
|
67
|
+
}
|
|
45
68
|
}
|
|
46
69
|
return { deps: out, warnings };
|
|
47
70
|
},
|
package/lib/codecs/go/parse.js
CHANGED
|
@@ -29,7 +29,7 @@ function parseReplaceLine(s) {
|
|
|
29
29
|
* Directory replaces have no scannable version — the dep is dropped and
|
|
30
30
|
* surfaced in `dropped` so the codec can emit a chapter-0 warning.
|
|
31
31
|
*/
|
|
32
|
-
function parseGoMod(text) {
|
|
32
|
+
function parseGoMod(text, { workspaceReplaces = [], replacementsOnly = false } = {}) {
|
|
33
33
|
const out = { module: null, goVersion: null, deps: [], dropped: [] };
|
|
34
34
|
const lines = String(text || "").split(/\r?\n/);
|
|
35
35
|
let inRequire = false;
|
|
@@ -69,12 +69,18 @@ function parseGoMod(text) {
|
|
|
69
69
|
if (rep) replaces.push(rep);
|
|
70
70
|
else if (/^replace\b/.test(noComment)) uncertainSyntax = true;
|
|
71
71
|
}
|
|
72
|
+
if (replacementsOnly) return replaces;
|
|
73
|
+
// Go checks exact versions before wildcard replacements within each file,
|
|
74
|
+
// and checks the workspace file before the module file (even a workspace
|
|
75
|
+
// wildcard overrides a module's exact-version replacement).
|
|
76
|
+
const replacement = (entries, dep) => entries.find(x => x.oldName === dep.name && x.oldVer === dep.version)
|
|
77
|
+
|| entries.find(x => x.oldName === dep.name && !x.oldVer);
|
|
72
78
|
// Apply replaces: versioned old matches that exact version only; versionless
|
|
73
79
|
// old matches every version of the module.
|
|
74
|
-
if (replaces.length) {
|
|
80
|
+
if (replaces.length || workspaceReplaces.length) {
|
|
75
81
|
const kept = [];
|
|
76
82
|
for (const dep of out.deps) {
|
|
77
|
-
const r =
|
|
83
|
+
const r = replacement(workspaceReplaces, dep) || replacement(replaces, dep);
|
|
78
84
|
if (!r) { kept.push(dep); continue; }
|
|
79
85
|
if (r.newVer) kept.push({ ...dep, name: r.newName, version: r.newVer, replaced: true, managerRelations: ["unknown"] });
|
|
80
86
|
else out.dropped.push({ name: dep.name, version: dep.version, path: r.newName });
|
|
@@ -123,7 +129,7 @@ function parseGoSum(text) {
|
|
|
123
129
|
return { deps: [...byMod.entries()].map(([name, version]) => ({ name, version, scope: "transitive", isDev: false })) };
|
|
124
130
|
}
|
|
125
131
|
|
|
126
|
-
function parseGoModFile(fp) { return parseGoMod(fs.readFileSync(fp, "utf8")); }
|
|
132
|
+
function parseGoModFile(fp, opts) { return parseGoMod(fs.readFileSync(fp, "utf8"), opts); }
|
|
127
133
|
function parseGoSumFile(fp) { return parseGoSum(fs.readFileSync(fp, "utf8")); }
|
|
128
134
|
|
|
129
135
|
module.exports = { parseGoMod, parseGoSum, parseGoModFile, parseGoSumFile, stripV };
|
package/lib/codecs/go.codec.js
CHANGED
|
@@ -55,18 +55,35 @@ module.exports = {
|
|
|
55
55
|
for (const g of findGoDirs(dir, dirFilter(dir, opts))) {
|
|
56
56
|
let modHadDeps = false;
|
|
57
57
|
const selectedHere = new Set();
|
|
58
|
-
//
|
|
59
|
-
let
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
58
|
+
// Honor the explicit workspace switch before looking for the nearest file.
|
|
59
|
+
let workspacePath = null;
|
|
60
|
+
if (process.env.GOWORK !== "off") {
|
|
61
|
+
if (process.env.GOWORK) workspacePath = path.resolve(process.env.GOWORK);
|
|
62
|
+
else for (let cur = g.dir; ; cur = path.dirname(cur)) {
|
|
63
|
+
const fp = path.join(cur, "go.work");
|
|
64
|
+
if (fs.existsSync(fp)) { workspacePath = fp; break; }
|
|
65
|
+
if (path.dirname(cur) === cur) break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const workspace = !!workspacePath;
|
|
69
|
+
let workspaceReplaces = [];
|
|
70
|
+
if (workspace) {
|
|
71
|
+
try {
|
|
72
|
+
workspaceReplaces = G.parseGoModFile(workspacePath, { replacementsOnly: true });
|
|
73
|
+
if (!parsedManifests.includes(workspacePath)) parsedManifests.push(workspacePath);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
warnings.push({ type: "parse-error", manifestPath: workspacePath, message: `go.work could not be read: ${error.message}` });
|
|
76
|
+
}
|
|
77
|
+
// Replaces alone cannot establish MVS across all workspace modules.
|
|
78
|
+
warnings.push({ type: "go-coverage", ecosystem: "go", reason: "workspace-graph-not-resolved", manifestPath: workspacePath,
|
|
79
|
+
message: "Go workspace graph was not resolved: recognized go.work replacements are applied, but workspace module selection and transitive versions remain uncertain. Inventory may be incomplete or include unselected versions." });
|
|
63
80
|
}
|
|
64
81
|
let goMinor = null;
|
|
65
82
|
if (g.names.has("go.mod")) {
|
|
66
83
|
const fp = path.join(g.dir, "go.mod");
|
|
67
84
|
parsedManifests.push(fp);
|
|
68
85
|
try {
|
|
69
|
-
const r = G.parseGoModFile(fp);
|
|
86
|
+
const r = G.parseGoModFile(fp, { workspaceReplaces });
|
|
70
87
|
const gm = /^1\.(\d+)/.exec(r.goVersion || "");
|
|
71
88
|
goMinor = gm ? Number(gm[1]) : null;
|
|
72
89
|
for (const d of r.dropped) {
|