vigievuln 1.3.3 → 1.4.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 +57 -0
- package/README.md +34 -19
- package/completions/vigievuln.bash +14 -3
- package/completions/vigievuln.zsh +11 -8
- package/lib/README.md +51 -0
- package/lib/{coverage-diagnostics.js → advisories/coverage-diagnostics.js} +1 -1
- package/lib/{cve-match.js → advisories/cve-match.js} +17 -12
- package/lib/{advisory-fixes.js → advisories/fixes.js} +1 -1
- package/lib/{advisory-freshness.js → advisories/freshness.js} +5 -1
- package/lib/{gap-adjudicate.js → advisories/gap-adjudicate.js} +3 -3
- package/lib/{native-package-match.js → advisories/native-package-match.js} +20 -11
- package/lib/{native-source-prepare.js → advisories/native-source-prepare.js} +15 -12
- package/lib/{native-advisories.js → advisories/native.js} +15 -13
- package/lib/{advisory-store-sqlite.js → advisories/store-sqlite.js} +5 -5
- package/lib/{advisory-store.js → advisories/store.js} +2 -2
- package/lib/{application-exports.js → applications/exports.js} +1 -1
- package/lib/{application-inventory.js → applications/inventory.js} +3 -1
- package/lib/applications/layout.js +199 -0
- package/lib/{application-providers → applications}/live-snapshot.js +10 -10
- package/lib/{application-plugins → applications/plugins}/drupal.js +2 -2
- package/lib/applications/plugins/ghost.js +36 -0
- package/lib/{application-plugins → applications/plugins}/index.js +1 -1
- package/lib/{application-plugins → applications/plugins}/prestashop.js +73 -15
- package/lib/applications/plugins/redmine.js +24 -0
- package/lib/{application-plugins → applications/plugins}/runner.js +89 -59
- package/lib/{application-plugins → applications/plugins}/spip.js +4 -4
- package/lib/{application-plugins → applications/plugins}/symfony.js +1 -1
- package/lib/{application-plugins → applications/plugins}/typo3.js +2 -2
- package/lib/{application-plugins → applications/plugins}/wave2-common.js +1 -1
- package/lib/{application-plugins → applications/plugins}/wordpress.js +52 -18
- package/lib/{application-providers → applications}/snapshot-cache.js +1 -1
- package/lib/{cms-snapshot-warm.js → applications/snapshot-warm.js} +21 -8
- package/lib/artifacts/access-warnings.js +24 -0
- package/lib/artifacts/applications.js +39 -8
- package/lib/artifacts/component-scope.js +11 -2
- package/lib/artifacts/cve-view.js +8 -5
- package/lib/artifacts/disk-wasm.mjs +3 -0
- package/lib/artifacts/disk.js +188 -0
- package/lib/artifacts/enrichment.js +31 -17
- package/lib/artifacts/go-main-identity.js +135 -36
- package/lib/artifacts/go-publisher-advisories.js +4 -3
- package/lib/artifacts/image-products.js +5 -4
- package/lib/artifacts/index.js +36 -13
- package/lib/artifacts/inventory-scope.js +53 -3
- package/lib/artifacts/product-advisories.js +51 -46
- package/lib/artifacts/product-catalog.js +6 -1
- package/lib/artifacts/release-catalogues.js +149 -0
- package/lib/artifacts/release-versions.js +101 -0
- package/lib/artifacts/remediation-report.js +1 -1
- package/lib/artifacts/report-inventory.js +15 -2
- package/lib/artifacts/report-path.js +29 -0
- package/lib/artifacts/report.js +66 -36
- package/lib/artifacts/retire.js +3 -3
- package/lib/artifacts/risk-report.js +12 -8
- package/lib/artifacts/sbom.js +33 -4
- package/lib/artifacts/scan.js +295 -67
- package/lib/artifacts/system-apps.js +98 -0
- package/lib/artifacts/system-maintenance.js +101 -0
- package/lib/artifacts/system-module-updates.js +104 -0
- package/lib/artifacts/system-report.js +232 -0
- package/lib/{airgap-project.js → cache/airgap-project.js} +25 -10
- package/lib/{cache-archive-sqlite.js → cache/archive.js} +6 -5
- package/lib/{cache-db.js → cache/db.js} +1 -1
- package/lib/{dump-format.js → cache/dump-format.js} +2 -2
- package/lib/{json-cache.js → cache/json.js} +1 -1
- package/lib/{proxy-cache.js → cache/proxy-cache.js} +9 -9
- package/lib/{proxy-scope.js → cache/proxy-scope.js} +1 -1
- package/lib/{record-freshness.js → cache/record-freshness.js} +1 -1
- package/lib/{cache-repository.js → cache/repository.js} +1 -1
- package/lib/{resource-cache → cache/resource}/engine.js +20 -14
- package/lib/{resource-cache → cache/resource}/fs-store.js +2 -2
- package/lib/{resource-cache → cache/resource}/sqlite-store.js +3 -3
- package/lib/{resource-cache → cache/resource}/validate.js +20 -6
- package/lib/{sqlite-driver.js → cache/sqlite-driver.js} +7 -5
- package/lib/certs/scan.js +17 -11
- package/lib/cli-collect.js +262 -0
- package/lib/cli-command-routing.js +30 -13
- package/lib/cli-groups.js +1 -1
- package/lib/cli-image.js +157 -46
- package/lib/cli-project-commands.js +10 -10
- package/lib/cli-setup.js +8 -8
- package/lib/cli-watch.js +3 -3
- package/lib/codecs/binary/scan.js +11 -3
- package/lib/codecs/binary.codec.js +1 -1
- package/lib/codecs/composer/platform.js +2 -2
- package/lib/codecs/composer/registry.js +12 -18
- package/lib/codecs/composer.codec.js +6 -5
- package/lib/codecs/go/parse.js +1 -1
- package/lib/codecs/go/registry.js +7 -7
- package/lib/codecs/go.codec.js +2 -2
- package/lib/codecs/gradle/parse.js +1 -1
- package/lib/codecs/gradle/versionless.js +2 -2
- package/lib/codecs/gradle.codec.js +7 -7
- package/lib/codecs/index.js +1 -1
- package/lib/{maven-airgap.js → codecs/maven/airgap.js} +4 -4
- package/lib/{maven-bom.js → codecs/maven/bom.js} +3 -3
- package/lib/codecs/maven/jar-scan.js +4 -4
- package/lib/{maven-license.js → codecs/maven/license.js} +2 -2
- package/lib/{core.js → codecs/maven/pom.js} +22 -11
- package/lib/{maven-reactor.js → codecs/maven/reactor.js} +18 -12
- package/lib/{transitive.js → codecs/maven/transitive.js} +79 -34
- package/lib/{maven-version.js → codecs/maven/version.js} +1 -1
- package/lib/codecs/maven.codec.js +18 -14
- package/lib/codecs/npm/collect.js +55 -8
- package/lib/codecs/npm/manifest-kind.js +16 -0
- package/lib/codecs/npm/parse.js +23 -7
- package/lib/codecs/npm/registry.js +28 -14
- package/lib/codecs/npm.codec.js +5 -5
- package/lib/codecs/nuget/registry.js +7 -7
- package/lib/codecs/nuget.codec.js +4 -4
- package/lib/codecs/pypi/registry.js +7 -7
- package/lib/codecs/pypi.codec.js +4 -4
- package/lib/codecs/recipes.js +2 -2
- package/lib/codecs/ruby/registry.js +7 -7
- package/lib/codecs/ruby.codec.js +2 -2
- package/lib/config.js +1 -1
- package/lib/{attribution.js → findings/attribution.js} +3 -3
- package/lib/findings/cve-descriptions.js +144 -0
- package/lib/{cve-record-coverage.js → findings/cve-record-coverage.js} +46 -41
- package/lib/{diff.js → findings/diff.js} +0 -0
- package/lib/{finding-enrichment.js → findings/enrichment.js} +45 -32
- package/lib/{eu-refs.js → findings/eu-refs.js} +3 -3
- package/lib/{gate.js → findings/gate.js} +1 -1
- package/lib/{malware.js → findings/malware.js} +30 -7
- package/lib/{merge-sources.js → findings/merge.js} +57 -9
- package/lib/{priority.js → findings/priority.js} +3 -3
- package/lib/findings/risk-evidence.js +24 -0
- package/lib/findings/severity.js +16 -0
- package/lib/{finding-summary.js → findings/summary.js} +5 -2
- package/lib/{suppress.js → findings/suppress.js} +2 -2
- package/lib/images/local-docker.js +72 -0
- package/lib/{image-network.js → images/network.js} +26 -16
- package/lib/{image-references.js → images/references.js} +29 -11
- package/lib/{image-registry.js → images/registry.js} +18 -9
- package/lib/{source-image-scan.js → images/source-scan.js} +3 -3
- package/lib/images/temp-roots.js +23 -0
- package/lib/{image-update.js → images/update.js} +3 -3
- package/lib/{dep-record.js → inventory/dep-record.js} +2 -2
- package/lib/{deps-descriptor.js → inventory/deps-descriptor.js} +3 -3
- package/lib/{descriptor-refs.js → inventory/descriptor-refs.js} +1 -1
- package/lib/{embedded.js → inventory/embedded.js} +4 -3
- package/lib/{license-policy.js → inventory/license-policy.js} +2 -2
- package/lib/{manifest-copy.js → inventory/manifest-copy.js} +2 -2
- package/lib/{module-names.js → inventory/module-names.js} +1 -1
- package/lib/{package-versions.js → inventory/package-versions.js} +2 -2
- package/lib/{parallel-walk.js → inventory/parallel-walk.js} +1 -1
- package/lib/{path-filter.js → inventory/path-filter.js} +1 -1
- package/lib/{private-deps.js → inventory/private-deps.js} +1 -1
- package/lib/{project-descriptor.js → inventory/project-descriptor.js} +3 -0
- package/lib/{purl.js → inventory/purl.js} +2 -2
- package/lib/{unmanaged.js → inventory/unmanaged.js} +6 -3
- package/lib/{commercial-support.js → maintenance/commercial-support.js} +5 -5
- package/lib/{outdated.js → maintenance/outdated.js} +20 -20
- package/lib/options-env.js +1 -1
- package/lib/{system-inventory/alpine-tracker.js → providers/alpine/tracker.js} +27 -7
- package/lib/{certfr.js → providers/certfr/enrich.js} +9 -9
- package/lib/{cve-download.js → providers/cveproject/download.js} +56 -36
- package/lib/{cve-legacy-ranges.js → providers/cveproject/legacy-ranges.js} +1 -1
- package/lib/{cve-npm-proxy.js → providers/cveproject/npm-proxy.js} +5 -5
- package/lib/{cve-packages-proxy.js → providers/cveproject/packages-proxy.js} +6 -6
- package/lib/{cve-version-verdict.js → providers/cveproject/version-verdict.js} +2 -2
- package/lib/{system-inventory/current-debian.js → providers/debian/current.js} +6 -6
- package/lib/{system-inventory/historical-debian.js → providers/debian/historical.js} +6 -6
- package/lib/providers/{debian.js → debian/index.js} +1 -0
- package/lib/{application-providers/drupal-advisories.js → providers/drupal/advisories.js} +13 -36
- package/lib/providers/{drupal.js → drupal/index.js} +4 -0
- package/lib/providers/{eol.js → eol/index.js} +1 -1
- package/lib/{epss.js → providers/epss/enrich.js} +16 -13
- package/lib/providers/{epss.js → epss/index.js} +2 -2
- package/lib/{euvd.js → providers/euvd/enrich.js} +13 -13
- package/lib/{system-inventory/freexian-ela.js → providers/freexian/ela.js} +6 -6
- package/lib/providers/{freexian.js → freexian/index.js} +3 -3
- package/lib/{system-inventory/freexian-release-evidence.js → providers/freexian/release-evidence.js} +8 -5
- package/lib/{system-inventory/freexian-tracker.js → providers/freexian/tracker.js} +33 -9
- package/lib/{gcve-feed.js → providers/gcve/feed.js} +4 -4
- package/lib/{gcve.js → providers/gcve/id.js} +1 -1
- package/lib/{gcve-index.js → providers/gcve/local-index.js} +4 -4
- package/lib/{application-providers/github-advisories.js → providers/github/advisories.js} +6 -2
- package/lib/providers/{github.js → github/index.js} +3 -1
- package/lib/{github-publisher-maven.js → providers/github/publisher-maven.js} +1 -1
- package/lib/providers/{go.js → go/index.js} +1 -1
- package/lib/{hash-id.js → providers/hashid/identify.js} +7 -7
- package/lib/providers/{hashid.js → hashid/index.js} +1 -1
- package/lib/providers/index.js +18 -13
- package/lib/{kev.js → providers/kev/enrich.js} +12 -9
- package/lib/{maven-cache.js → providers/maven/cache.js} +3 -3
- package/lib/providers/{maven.js → maven/index.js} +5 -3
- package/lib/{maven-presence.js → providers/maven/presence.js} +5 -5
- package/lib/{maven-repo.js → providers/maven/repo.js} +38 -21
- package/lib/providers/mit-kerberos/index.js +6 -0
- package/lib/{system-inventory/nginx-advisories.js → providers/nginx/advisories.js} +3 -3
- package/lib/providers/{npm.js → npm/index.js} +1 -1
- package/lib/providers/{nuget.js → nuget/index.js} +1 -1
- package/lib/{cpe.js → providers/nvd/cpe.js} +35 -47
- package/lib/{nvd.js → providers/nvd/enrich.js} +41 -40
- package/lib/providers/{nvd.js → nvd/index.js} +3 -3
- package/lib/{nvd-package-ranges.js → providers/nvd/package-ranges.js} +38 -22
- package/lib/{osv-db.js → providers/osv/db.js} +18 -16
- package/lib/providers/{osv.js → osv/index.js} +1 -1
- package/lib/{osv.js → providers/osv/query.js} +150 -80
- package/lib/providers/package-releases/index.js +26 -0
- package/lib/{packagist-audit.js → providers/packagist/audit.js} +31 -11
- package/lib/providers/{packagist.js → packagist/index.js} +1 -1
- package/lib/{proxy-throttle.js → providers/proxy-throttle.js} +17 -9
- package/lib/providers/{pypi.js → pypi/index.js} +1 -1
- package/lib/providers/redhat/bzip2.js +167 -0
- package/lib/providers/redhat/errata.js +75 -0
- package/lib/providers/redhat/index.js +10 -0
- package/lib/providers/redhat/oval.js +70 -0
- package/lib/providers/redhat/unfixed.js +127 -0
- package/lib/{registries.js → providers/registries.js} +4 -4
- package/lib/{retire.js → providers/retire/scan.js} +18 -18
- package/lib/providers/{ruby.js → ruby/index.js} +1 -1
- package/lib/providers/rubysec/advisories.js +177 -0
- package/lib/providers/rubysec/index.js +9 -0
- package/lib/{snyk.js → providers/snyk/client.js} +2 -2
- package/lib/{application-providers/spip-advisories.js → providers/spip/advisories.js} +5 -13
- package/lib/{vigievuln-advisories.js → providers/vigievuln/advisories.js} +4 -4
- package/lib/providers/wolfi/index.js +10 -0
- package/lib/providers/wolfi/secdb.js +47 -0
- package/lib/{application-providers/wordfence-client.js → providers/wordfence/client.js} +4 -4
- package/lib/providers/{wordfence.js → wordfence/index.js} +1 -1
- package/lib/{application-providers/wordfence-projection.js → providers/wordfence/projection.js} +14 -5
- package/lib/{resource-cache/wordfence.js → providers/wordfence/resource-cache.js} +2 -2
- package/lib/{application-providers/wordfence-v3.js → providers/wordfence/v3.js} +4 -5
- package/lib/providers/{wordpress.js → wordpress/index.js} +5 -0
- package/lib/providers/wpvulnerability/assess.js +181 -0
- package/lib/providers/wpvulnerability/index.js +12 -0
- package/lib/{charts.js → reports/charts.js} +25 -18
- package/lib/{csaf-export.js → reports/csaf-export.js} +16 -11
- package/lib/{cve-report.js → reports/cve-report.js} +453 -228
- package/lib/reports/detail.js +55 -0
- package/lib/{i18n.js → reports/i18n.js} +38 -2
- package/lib/{report-integrity.js → reports/integrity.js} +1 -1
- package/lib/{json-export.js → reports/json-export.js} +95 -24
- package/lib/{report-notices.js → reports/notices.js} +11 -6
- package/lib/{sarif-export.js → reports/sarif-export.js} +15 -10
- package/lib/{sbom-export.js → reports/sbom-export.js} +16 -11
- package/lib/{scan-completeness.js → scan/completeness.js} +1 -1
- package/lib/scan/coverage.js +114 -0
- package/lib/{provenance.js → scan/provenance.js} +12 -5
- package/lib/scan/reliability.js +157 -0
- package/lib/{source-health.js → scan/source-health.js} +52 -20
- package/lib/{source-profile.js → scan/source-profile.js} +3 -3
- package/lib/{hosted-proxy.js → service/hosted-proxy.js} +3 -3
- package/lib/{project-client.js → service/project-client.js} +20 -2
- package/lib/source-input.js +58 -0
- package/lib/system-inventory/advisories.js +89 -16
- package/lib/system-inventory/collect.js +33 -10
- package/lib/system-inventory/distribution-sources.js +32 -15
- package/lib/system-inventory/package-applicability.js +51 -0
- package/lib/system-inventory/targeted.js +8 -5
- package/lib/ui.js +11 -0
- package/package.json +49 -2
- package/vigievuln.js +483 -352
- package/lib/cache-archive.js +0 -676
- package/lib/osv-legacy.js +0 -57
- package/lib/risk-evidence.js +0 -18
- package/lib/scan-coverage.js +0 -61
- /package/lib/{application-plugins → applications/plugins}/joomla.js +0 -0
- /package/lib/{application-plugins → applications/plugins}/laravel.js +0 -0
- /package/lib/{application-plugins → applications/plugins}/magento.js +0 -0
- /package/lib/{application-plugins → applications/plugins}/plugin.interface.js +0 -0
- /package/lib/{application-plugins → applications/plugins}/select.js +0 -0
- /package/lib/{advisory-compression.js → cache/advisory-compression.js} +0 -0
- /package/lib/{compression-dictionary.js → cache/compression-dictionary.js} +0 -0
- /package/lib/{cache-directory.js → cache/directory.js} +0 -0
- /package/lib/{cache-policy.js → cache/policy.js} +0 -0
- /package/lib/{resource-cache → cache/resource}/snapshot-projection.js +0 -0
- /package/lib/{cache-startup.js → cache/startup.js} +0 -0
- /package/lib/{ruby-version.js → codecs/ruby/version.js} +0 -0
- /package/lib/{applicability-evidence.js → findings/applicability-evidence.js} +0 -0
- /package/lib/{line-stream.js → inventory/line-stream.js} +0 -0
- /package/lib/{package-metadata.js → inventory/package-metadata.js} +0 -0
- /package/lib/providers/{alpine.js → alpine/index.js} +0 -0
- /package/lib/providers/{certfr.js → certfr/index.js} +0 -0
- /package/lib/{native-cna-identities.js → providers/cveproject/cna-identities.js} +0 -0
- /package/lib/providers/{euvd.js → euvd/index.js} +0 -0
- /package/lib/providers/{gcve.js → gcve/index.js} +0 -0
- /package/lib/providers/{kev.js → kev/index.js} +0 -0
- /package/lib/providers/{nginx.js → nginx/index.js} +0 -0
- /package/lib/{nvd-bulk.js → providers/nvd/bulk.js} +0 -0
- /package/lib/providers/{osvdb.js → osvdb/index.js} +0 -0
- /package/lib/{request-failure.js → providers/request-failure.js} +0 -0
- /package/lib/providers/{retire.js → retire/index.js} +0 -0
- /package/lib/providers/{vigievuln.js → vigievuln/index.js} +0 -0
- /package/lib/{application-providers/wp-checksums.js → providers/wordpress/checksums.js} +0 -0
- /package/lib/{report-time.js → reports/time.js} +0 -0
- /package/lib/{xlsx-export.js → reports/xlsx-export.js} +0 -0
- /package/lib/{diagnostics.js → scan/diagnostics.js} +0 -0
- /package/lib/{account-client.js → service/account-client.js} +0 -0
- /package/lib/{account-session.js → service/account-session.js} +0 -0
- /package/lib/{account-terms.js → service/account-terms.js} +0 -0
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
// Enrichment adds independent risk evidence; it never changes OS advisory verdicts.
|
|
3
|
-
const {createCacheRepository}=require('../cache
|
|
4
|
-
const {getCacheDir}=require('../cache
|
|
3
|
+
const {createCacheRepository}=require('../cache/repository');
|
|
4
|
+
const {getCacheDir}=require('../cache/directory');
|
|
5
5
|
function cveIds(match){return [...new Set([match.cve?.id,...(match.cve?.aliases||[]),...(match.cve?.upstream||[])].filter(id=>/^CVE-\d{4}-\d{4,}$/i.test(id||'')))];}
|
|
6
6
|
function cveId(match){return cveIds(match)[0]||null;}
|
|
7
7
|
function relationship(cve,id){return cve.id===id || (cve.aliases||[]).includes(id) ? 'identity' : 'upstream';}
|
|
8
|
-
function proxies(matches){
|
|
8
|
+
function proxies(matches){
|
|
9
|
+
const ids=new Set(matches.flatMap(cveIds));
|
|
10
|
+
return [...ids].map(id=>({cve:{id}}));
|
|
11
|
+
}
|
|
9
12
|
function cveEvidence(cve,id){if(!Array.isArray(cve.cveEvidence))cve.cveEvidence=[];let value=cve.cveEvidence.find(x=>x.id===id);if(!value){value={id};cve.cveEvidence.push(value);}return value;}
|
|
10
13
|
// Hosted proxies offer a targeted KEV operation. Persist both positive and
|
|
11
14
|
// negative observations so an air-gapped replay does not need a global catalog.
|
|
@@ -18,37 +21,44 @@ async function enrichKevCopies(copies,opts){
|
|
|
18
21
|
for(let i=0;i<wanted.length;i+=100){
|
|
19
22
|
const group=wanted.slice(i,i+100),res=await require('../providers').getResource('kev','cves',{ids:group},{fetcher:opts.fetcher,noStore:true,streaming:true});
|
|
20
23
|
if(!res.ok)throw Error(`KEV HTTP ${res.status}`);const body=await res.json();if(!Array.isArray(body?.items))throw Error('invalid KEV response');
|
|
21
|
-
const seen=new Map();for(const row of body.items){if(!row || !group.includes(row.cve) || seen.has(row.cve) || (row.kev!=null && (typeof row.kev!=='object'||Array.isArray(row.kev))))throw Error('invalid KEV record');seen.set(row.cve,row.kev||null);}
|
|
24
|
+
const seen=new Map();for(const row of body.items){if(!row || !group.includes(row.cve) || seen.has(row.cve) || !Object.hasOwn(row,'kev') || (row.kev!=null && (typeof row.kev!=='object'||Array.isArray(row.kev))))throw Error('invalid KEV record');seen.set(row.cve,row.kev||null);}
|
|
25
|
+
if(seen.size!==group.length)throw Error('incomplete KEV response');
|
|
22
26
|
const stamp=Date.parse(res.headers?.get?.('x-fad-proxy-fetched-at')||'');const fetchedAt=Number.isFinite(stamp)&&stamp>0&&stamp<=Date.now()+300000?stamp:null,stale=fetchedAt===null || res.headers?.get?.('x-fad-proxy')==='stale';
|
|
23
27
|
for(const id of group)targeted.entries[id]={item:seen.get(id)||null,fetchedAt,stale};
|
|
24
28
|
repo.put('catalogue','kev-targeted',targeted);
|
|
25
29
|
}
|
|
26
30
|
}catch(error){failure=`KEV targeted lookup failed: ${error.message}`;}
|
|
27
|
-
}else if(!opts.offline)await require('../kev').enrichKev(copies,{...opts,hostedProxy:false});
|
|
28
|
-
else await require('../kev').enrichKev(copies,{...opts,offline:true});
|
|
31
|
+
}else if(!opts.offline)await require('../providers/kev/enrich').enrichKev(copies,{...opts,hostedProxy:false});
|
|
32
|
+
else await require('../providers/kev/enrich').enrichKev(copies,{...opts,offline:true});
|
|
29
33
|
const bulk=repo.get('catalogue','kev')?.value,hasBulk=!!bulk?.body?.byId && typeof bulk.body.byId==='object';let missing=0,stale=0;
|
|
30
|
-
for(const copy of copies){const saved=targeted.entries[copy.cve.id];if(saved && (opts.offline||hosted)){
|
|
31
|
-
if(saved.stale || !Number.isFinite(saved.fetchedAt) || saved.fetchedAt<=0 || saved.fetchedAt>Date.now()+300000)stale++;const item=saved.item;if(item){copy.cve.kev=true;copy.cve.kevDateAdded=item.dateAdded;copy.cve.kevDueDate=item.dueDate;copy.cve.kevRansomware=item.ransomware;}
|
|
34
|
+
for(const copy of copies){const saved=targeted.entries[copy.cve.id];if(saved && (opts.offline||hosted) && (!hasBulk || hosted || saved.fetchedAt >= bulk._fetchedAt)){
|
|
35
|
+
if(saved.stale || !Number.isFinite(saved.fetchedAt) || saved.fetchedAt<=0 || saved.fetchedAt>Date.now()+300000)stale++;const item=saved.item;delete copy.cve.kev;if(item){copy.cve.kev=true;copy.cve.kevDateAdded=item.dateAdded;copy.cve.kevDueDate=item.dueDate;copy.cve.kevRansomware=item.ransomware;}
|
|
32
36
|
}else if(!hasBulk)missing++;
|
|
33
37
|
}
|
|
34
|
-
return {complete:!failure && !missing && !stale,reason:failure || (missing?`KEV
|
|
38
|
+
return {complete:!failure && !missing && !stale,reason:failure || (missing?`CISA KEV membership could not be checked for ${missing} distinct CVE(s)${opts.offline ? ' using the offline cache' : ''}.`:`KEV observations stale for ${stale} eligible CVE(s).`)};
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
const enrichmentAdapters=[
|
|
38
42
|
{id:'kev',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};const state=await enrichKevCopies(copies,opts);const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.kev){const record=cveEvidence(m.cve,id);for(const key of ['kev','kevDateAdded','kevDueDate','kevRansomware'])if(item[key]!==undefined)record[key]=item[key];}}const hit=cveIds(m).map(id=>byId.get(id)).find(x=>x?.cve.kev);if(hit?.cve.kev){m.cve.kev=true;m.cve.kevDateAdded=hit.cve.kevDateAdded;m.cve.kevDueDate=hit.cve.kevDueDate;m.cve.kevRansomware=hit.cve.kevRansomware;m.cve.kevEvidence={source:'kev',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}}return state;}},
|
|
39
|
-
{id:'epss',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};await require('../epss').enrichEpss(copies,opts);const cache=createCacheRepository(opts.cacheDir||getCacheDir()).get('catalogue','epss')?.value;const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.epssScore!=null || item?.epssPercentile!=null){const record=cveEvidence(m.cve,id);if(item.epssScore!=null)record.epssScore=item.epssScore;if(item.epssPercentile!=null)record.epssPercentile=item.epssPercentile;}}const hit=cveIds(m).map(id=>byId.get(id)).filter(Boolean).sort((a,b)=>(b.cve.epssScore??-1)-(a.cve.epssScore??-1))[0];if(hit?.cve.epssScore!=null){m.cve.epssScore=hit.cve.epssScore;m.cve.epssEvidence={source:'epss',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}if(hit?.cve.epssPercentile!=null)m.cve.epssPercentile=hit.cve.epssPercentile;}
|
|
43
|
+
{id:'epss',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};let failure;await require('../providers/epss/enrich').enrichEpss(copies,{...opts,onEpssFailure:reason=>{failure=reason;}});const cache=createCacheRepository(opts.cacheDir||getCacheDir()).get('catalogue','epss')?.value;const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.epssScore!=null || item?.epssPercentile!=null){const record=cveEvidence(m.cve,id);if(item.epssScore!=null)record.epssScore=item.epssScore;if(item.epssPercentile!=null)record.epssPercentile=item.epssPercentile;}}const hit=cveIds(m).map(id=>byId.get(id)).filter(Boolean).sort((a,b)=>(b.cve.epssScore??-1)-(a.cve.epssScore??-1))[0];if(hit?.cve.epssScore!=null){m.cve.epssScore=hit.cve.epssScore;m.cve.epssEvidence={source:'epss',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}if(hit?.cve.epssPercentile!=null)m.cve.epssPercentile=hit.cve.epssPercentile;}const missing=copies.filter(m=>!Object.hasOwn(cache?.entries||{},m.cve.id)).length;return {complete:!failure && !missing,reason:failure || `FIRST EPSS queries for ${missing} distinct CVE(s) are absent from the auditor cache.`};}},
|
|
40
44
|
{id:'nvd',async run(matches,opts){
|
|
41
45
|
const copies=proxies(matches).map(m=>({...m,cve:{id:m.cve.id,severity:'UNKNOWN'}}));if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};
|
|
42
|
-
const nvd=require('../nvd'),absent=new Set(),failures=[];
|
|
43
|
-
|
|
44
|
-
|
|
46
|
+
const nvd=require('../providers/nvd/enrich'),absent=new Set(),failures=[];
|
|
47
|
+
const native=new Map(matches.filter(m=>m.cve?.nvdRecordEvidence?.status==='available' && m.cve.description).map(m=>[m.cve.id,m.cve]));
|
|
48
|
+
for(const copy of copies){const record=native.get(copy.cve.id);if(record && (opts.offline || !record.nvdRecordEvidence.stale)){copy.cve={...record};copy.source='nvd';}}
|
|
49
|
+
await nvd.enrichMatches(copies.filter(copy=>!copy.source),{...opts,onAbsent:id=>absent.add(id),onFailure:(id,reason)=>failures.push({id,reason}),onProgress:(completed,total)=>opts.onEnrichmentProgress?.({source:'nvd',completed,total})});
|
|
50
|
+
for(const copy of copies){
|
|
51
|
+
const record=native.get(copy.cve.id);
|
|
52
|
+
if(record && copy.cve.nvdRecordEvidence?.status==='unavailable'){copy.cve={...record};copy.source='nvd';}
|
|
53
|
+
}
|
|
54
|
+
if(opts.offline)for(const copy of copies)if(!copy.source && nvd.hasCachedAbsence(copy.cve.id,{cacheDir:opts.cacheDir,offline:true}))absent.add(copy.cve.id);
|
|
45
55
|
const byId=new Map(copies.map(x=>[x.cve.id,x]));
|
|
46
56
|
for(const m of matches){
|
|
47
57
|
const ids=cveIds(m), enriched=ids.map(id=>byId.get(id)).filter(x=>x?.source?.split('+').includes('nvd'));
|
|
48
58
|
for(const id of ids){const evidence=byId.get(id)?.cve?.nvdRecordEvidence;if(evidence)cveEvidence(m.cve,id).nvdRecordEvidence=evidence;}
|
|
49
59
|
const records=enriched.map(x=>({id:x.cve.id,relationship:relationship(m.cve,x.cve.id),severity:x.cve.severity||null,score:x.cve.score??null,
|
|
50
60
|
cvssVector:x.cve.cvssVector||null,cvssVersion:x.cve.cvssVersion||null,description:x.cve.description||null,
|
|
51
|
-
cwes:x.cve.cwes||[],references:x.cve.nvdRefs||[],published:x.cve.published||null,modified:x.cve.modified||null}));
|
|
61
|
+
cwes:x.cve.cwes||[],references:x.cve.nvdRefs||x.cve.references||[],published:x.cve.published||null,...(x.cve.nvdVulnStatus ? {vulnStatus:x.cve.nvdVulnStatus} : {}),modified:x.cve.modified||null}));
|
|
52
62
|
if(records.length){m.cve.nvdEvidence={...records[0],records};const sources=new Set(String(m.source||'').split('+').filter(Boolean));sources.add('nvd');m.source=[...sources].sort().join('+');}
|
|
53
63
|
// A single explicitly related CVE can fill missing display metadata without
|
|
54
64
|
// changing the distribution's advisory identity or affected/fixed verdict.
|
|
@@ -56,11 +66,15 @@ const enrichmentAdapters=[
|
|
|
56
66
|
// aggregate severity or score.
|
|
57
67
|
if(ids.length===1 && enriched.length===1){
|
|
58
68
|
const item=enriched[0].cve;let riskFilled=false;
|
|
69
|
+
if(item.nvdVulnStatus==='Rejected' && m.cve.id===item.id){
|
|
70
|
+
m.suppressed=true;m.suppressedReason='CVE identifier rejected by its assigning authority (NVD record).';
|
|
71
|
+
}
|
|
59
72
|
if((!m.cve.severity || String(m.cve.severity).toUpperCase()==='UNKNOWN') && item.severity && item.severity!=='UNKNOWN'){
|
|
60
73
|
m.cve.severity=item.severity; m.cve.severitySource='nvd'; riskFilled=true;
|
|
61
74
|
}
|
|
62
75
|
if(m.cve.score==null && typeof item.score==='number' && Number.isFinite(item.score)){m.cve.score=item.score;m.cve.scoreSource='nvd';riskFilled=true;}
|
|
63
76
|
if(riskFilled)m.cve.riskEvidence={source:'nvd',id:item.id,relationship:relationship(m.cve,item.id)};
|
|
77
|
+
if(!require('../findings/cve-record-coverage').usableText(m.cve.description) && item.description)m.cve.description=item.description;
|
|
64
78
|
if(!m.cve.cvssVector && item.cvssVector)m.cve.cvssVector=item.cvssVector;
|
|
65
79
|
if(!m.cve.cvssVersion && item.cvssVersion)m.cve.cvssVersion=item.cvssVersion;
|
|
66
80
|
if(!m.cve.cwes?.length && item.cwes?.length)m.cve.cwes=item.cwes;
|
|
@@ -77,11 +91,11 @@ async function enrichArtifactFindings(matches,opts={}) {
|
|
|
77
91
|
const registry=opts.enrichmentAdapters||enrichmentAdapters;if(!Array.isArray(registry)||registry.some(a=>!a||typeof a.id!=='string'||typeof a.run!=='function'))throw Error('Invalid enrichment adapter registry');
|
|
78
92
|
const selected=opts.enrich || ['nvd','kev','epss','gcve','euvd','certfr'];if(!Array.isArray(selected))throw Error('Invalid enrichment selection');
|
|
79
93
|
const coverage=[],warnings=[];
|
|
80
|
-
const european=opts.europeanAdapters || require('../
|
|
94
|
+
const european=opts.europeanAdapters || require('../findings/enrichment').europeanAdapters;
|
|
81
95
|
const europeanIds=new Set(european.map(a=>a.id));
|
|
82
|
-
for(const id of selected.filter(id=>!europeanIds.has(id))){if(opts[id]===false){const reason=`${id} is excluded by the selected source profile.`;coverage.push({capability:'sources',collector:id,execution:'not-applicable',result:'not-consulted',expected:false,reason});continue;}const adapter=registry.find(a=>a.id===id);if(!adapter)throw Error(`Unknown enrichment adapter ${id}`);try{opts.onEnrichmentProgress?.({source:id,completed:0,total:matches.length});const result=await adapter.run(matches,opts);opts.onEnrichmentProgress?.({source:id,completed:matches.length,total:matches.length});if(!result||typeof result.complete!=='boolean')throw Error('Invalid enrichment result');coverage.push({capability:'sources',collector:id,execution:result.notApplicable?'not-applicable':result.complete?'completed':'partial',result:result.notApplicable?'not-applicable':result.complete?(result.result||'available'):'indeterminate',...(result.notApplicable?{expected:false,reason:result.reason}:!result.complete?{reason:result.reason}:{})});if(!result.complete)warnings.push({type:'source-unavailable',capability:'sources',source:id,message:result.reason||`${id} unavailable`});}catch(e){coverage.push({capability:'sources',collector:id,execution:'partial',result:'indeterminate',reason:e.message});warnings.push({type:'source-unavailable',capability:'sources',source:id,message:`${id}: ${e.message}`});}}
|
|
96
|
+
for(const id of selected.filter(id=>!europeanIds.has(id))){if(opts[id]===false){const reason=`${id} is excluded by the selected source profile.`;coverage.push({capability:'sources',collector:id,execution:'not-applicable',result:'not-consulted',expected:false,reason});continue;}const adapter=registry.find(a=>a.id===id);if(!adapter)throw Error(`Unknown enrichment adapter ${id}`);const startedAt=Date.now();try{opts.onEnrichmentProgress?.({source:id,completed:0,total:matches.length});const result=await adapter.run(matches,opts);opts.onEnrichmentProgress?.({source:id,completed:matches.length,total:matches.length});if(!result||typeof result.complete!=='boolean')throw Error('Invalid enrichment result');coverage.push({capability:'sources',collector:id,execution:result.notApplicable?'not-applicable':result.complete?'completed':'partial',result:result.notApplicable?'not-applicable':result.complete?(result.result||'available'):'indeterminate',...(result.notApplicable?{expected:false,reason:result.reason}:!result.complete?{reason:result.reason}:{})});if(!result.complete)warnings.push({type:'source-unavailable',capability:'sources',source:id,message:result.reason||`${id} unavailable`});}catch(e){coverage.push({capability:'sources',collector:id,execution:'partial',result:'indeterminate',reason:e.message});warnings.push({type:'source-unavailable',capability:'sources',source:id,message:`${id}: ${e.message}`});}coverage.at(-1).durationMs=Date.now()-startedAt;}
|
|
83
97
|
const selectedEuropean=european.filter(a=>selected.includes(a.id) || (a.parent && selected.includes(a.parent)));
|
|
84
|
-
if(selectedEuropean.length){const result=await require('../
|
|
98
|
+
if(selectedEuropean.length){const result=await require('../findings/enrichment').enrichEuropeanFindings(matches,{...opts,europeanAdapters:selectedEuropean});coverage.push(...result.coverage);warnings.push(...result.warnings);}
|
|
85
99
|
return {coverage,warnings};
|
|
86
100
|
}
|
|
87
101
|
module.exports={enrichArtifactFindings,enrichmentAdapters,cveId};
|
|
@@ -1,45 +1,144 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
|
|
2
|
+
// A Go binary built from a checkout names its main module "(devel)": the application's own
|
|
3
|
+
// advisories cannot be matched without its version. A version is only ever *proposed*:
|
|
4
|
+
// - by the image's OCI labels (version + source repository holding the module), or
|
|
5
|
+
// - by the build itself, `-ldflags -X main.Version=…`, recorded in the binary.
|
|
6
|
+
// It is *proved* independently: the Go module proxy must record that this module at that
|
|
7
|
+
// version was cut from the very git revision embedded in the binary, itself built from an
|
|
8
|
+
// unmodified checkout. Neither a label, a tag nor a linker flag binds a version alone.
|
|
9
|
+
const {makeDepRecord}=require('../inventory/dep-record');
|
|
10
|
+
|
|
6
11
|
const VERSION=/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+incompatible)?$/;
|
|
7
|
-
|
|
12
|
+
const REVISION=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
|
|
13
|
+
const MAX_LINKER_CANDIDATES=3;
|
|
14
|
+
|
|
15
|
+
function repo(value){
|
|
16
|
+
try{
|
|
17
|
+
const u=new URL(value);
|
|
18
|
+
if(u.protocol!=='https:'||u.username||u.password||u.port||u.search||u.hash)return null;
|
|
19
|
+
const pathname=u.pathname.replace(/\/+$/,'').replace(/\.git$/i,'');
|
|
20
|
+
if(!pathname||pathname==='/'||pathname.split('/').some(x=>x==='.'||x==='..'))return null;
|
|
21
|
+
return `${u.hostname.toLowerCase()}${pathname}`;
|
|
22
|
+
}catch{return null;}
|
|
23
|
+
}
|
|
8
24
|
function escapeModule(value){return value.replace(/[A-Z]/g,c=>'!'+c.toLowerCase());}
|
|
9
|
-
|
|
25
|
+
// "1.23.8" and "v1.23.8" name the same Go module version.
|
|
26
|
+
function moduleVersion(raw){
|
|
27
|
+
const text=String(raw??'').trim(),version=/^\d/.test(text)?'v'+text:text;
|
|
28
|
+
return VERSION.test(version)?version:null;
|
|
29
|
+
}
|
|
30
|
+
// Versions the build wrote into the binary: -X main.Version=1.23.8, -X pkg/version.Version=v2.1.0.
|
|
31
|
+
// The toolchain's own versions (GoVersion, MakeVersion) are not the application's.
|
|
32
|
+
function linkerVersions(settings={}){
|
|
33
|
+
const found=[];
|
|
34
|
+
for(const m of String(settings['-ldflags']||'').matchAll(/-X\s+[\\"']*([A-Za-z0-9_./~-]+)=([^\s"'\\]+)/g)){
|
|
35
|
+
const name=m[1].split('.').pop();
|
|
36
|
+
if(!/version$/i.test(name)||/^(?:go|make|compiler|runtime|build)version$/i.test(name))continue;
|
|
37
|
+
const version=moduleVersion(m[2]);
|
|
38
|
+
if(version&&!found.includes(version))found.push(version);
|
|
39
|
+
}
|
|
40
|
+
return found.slice(0,MAX_LINKER_CANDIDATES);
|
|
41
|
+
}
|
|
42
|
+
// A module below the repository root is tagged "<directory>/<version>".
|
|
43
|
+
function tagRef(module,source,version){
|
|
44
|
+
const suffix=module.slice(source.length).split('/').filter(Boolean);
|
|
45
|
+
if(/^v(?:[2-9]|[1-9]\d+)$/.test(suffix.at(-1)||''))suffix.pop();
|
|
46
|
+
return `refs/tags/${suffix.length?suffix.join('/')+'/':''}${version}`;
|
|
47
|
+
}
|
|
48
|
+
function proves(info,candidate,module,revision){
|
|
49
|
+
const origin=info?.Origin||{};
|
|
50
|
+
if(info?.Version!==candidate.version||origin.VCS!=='git'||String(origin.Hash||'').toLowerCase()!==revision.toLowerCase())return false;
|
|
51
|
+
// Under a declared source repository the repository and the exact tag must match. A module
|
|
52
|
+
// served from a vanity path (code.gitea.io/gitea → github.com/go-gitea/gitea) has no such
|
|
53
|
+
// relation to check: the revision recorded by the proxy for that version is the proof.
|
|
54
|
+
if(candidate.source)return repo(origin.URL)===candidate.source&&origin.Ref===tagRef(module,candidate.source,candidate.version);
|
|
55
|
+
return origin.Ref===`refs/tags/${candidate.version}`||(String(origin.Ref||'').startsWith('refs/tags/')&&origin.Ref.endsWith('/'+candidate.version));
|
|
56
|
+
}
|
|
57
|
+
const validStamp=at=>Number.isFinite(at)&&at>0&&at<=Date.now()+300000;
|
|
58
|
+
|
|
10
59
|
async function resolveGoMainIdentities(target,options={}){
|
|
11
|
-
const metadata=target?.metadata||{},labels=metadata.imageConfig?.labels||{}
|
|
60
|
+
const metadata=target?.metadata||{},labels=metadata.imageConfig?.labels||{};
|
|
61
|
+
const labelVersion=moduleVersion(labels['org.opencontainers.image.version']),labelSource=repo(labels['org.opencontainers.image.source']);
|
|
62
|
+
const configDigest=/^sha256:[a-f0-9]{64}$/i.test(metadata.configDigest||'')?metadata.configDigest:null;
|
|
12
63
|
const outputs=[],warnings=[],seen=new Set();let candidates=0,unavailable=0,conflicts=0,stale=0;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
if(
|
|
19
|
-
|
|
64
|
+
const lookup=options.lookup || (async(module,version)=>{
|
|
65
|
+
const providers=require('../providers');
|
|
66
|
+
const response=await providers.getResource('go','module-info',{module:escapeModule(module),version},{offline:false,fetcher:options.fetcher,...(options.store?{store:options.store}:{})});
|
|
67
|
+
if(!response.ok)throw Object.assign(Error(`Go proxy HTTP ${response.status}`),{status:response.status});
|
|
68
|
+
const proxied=providers.hasProxyRoute(),stamp=Date.parse(response.headers.get('x-fad-proxy-fetched-at')||'');
|
|
69
|
+
if(proxied&&!validStamp(stamp))throw Error('Go proxy evidence has no valid observation timestamp');
|
|
70
|
+
return {info:await response.json(),observedAt:proxied?stamp:Date.now(),stale:proxied&&response.headers.get('x-fad-proxy')==='stale'};
|
|
71
|
+
});
|
|
72
|
+
let repository;const cacheRepo=()=>repository||(repository=require('../cache/repository').createCacheRepository(options.cacheDir||require('../cache/directory').getCacheDir()));
|
|
73
|
+
const requests=new Map();
|
|
74
|
+
const warn=message=>{if(!warnings.some(w=>w.message===message))warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message});};
|
|
75
|
+
|
|
76
|
+
for(const binary of target?.deps||[]){
|
|
77
|
+
if(binary.ecosystem!=='binary')continue;
|
|
78
|
+
const go=binary.binaryMetadata?.go,settings=go?.settings||{},main=(go?.modules||[]).filter(m=>m.kind==='mod');
|
|
79
|
+
if(main.length!==1||main[0].version!=='(devel)'||main[0].replace||!main[0].path)continue;
|
|
20
80
|
const module=main[0].path,revision=settings['vcs.revision'],binaryPath=binary.artifactPath||binary.manifestPaths?.[0];
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
81
|
+
// The publisher's label speaks for the modules of the repository it names, in an image.
|
|
82
|
+
const labelled=!!(configDigest&&labelVersion&&labelSource&&(module===labelSource||module.startsWith(labelSource+'/')));
|
|
83
|
+
const proposals=[...(labelled?[{version:labelVersion,source:labelSource,proposedBy:'oci-label'}]:[]),
|
|
84
|
+
...linkerVersions(settings).filter(v=>!labelled||v!==labelVersion).map(version=>({version,source:null,proposedBy:'linker-flag'}))];
|
|
85
|
+
if(!proposals.length)continue;
|
|
86
|
+
const clean=settings.vcs==='git'&&settings['vcs.modified']==='false'&&REVISION.test(revision||'')&&binaryPath&&/^[a-f0-9]{64}$/i.test(binary.hashes?.sha256||'');
|
|
87
|
+
const platformConflict=(settings.GOOS&&metadata.platform?.os&&settings.GOOS!==metadata.platform.os)||(settings.GOARCH&&metadata.platform?.architecture&&settings.GOARCH!==metadata.platform.architecture);
|
|
88
|
+
// A labelled binary that cannot be verified contradicts the label; one that only carries a
|
|
89
|
+
// linker flag simply offers nothing to verify.
|
|
90
|
+
if(!clean||platformConflict){if(labelled)conflicts++;continue;}
|
|
91
|
+
candidates++;
|
|
92
|
+
let identified=false,conflicting=false,failed=false;
|
|
93
|
+
for(const candidate of proposals){
|
|
94
|
+
const {version}=candidate,key=JSON.stringify([module,version,candidate.source,revision.toLowerCase()]);
|
|
95
|
+
let observation;
|
|
96
|
+
try{
|
|
97
|
+
if(options.offline){
|
|
98
|
+
const saved=cacheRepo().get('go-main-identity',key);
|
|
99
|
+
if(!saved)throw Error('no cached Go proxy version evidence');
|
|
100
|
+
observation={info:saved.value,observedAt:saved.fetchedAt,stale:saved.stale};
|
|
101
|
+
}else{
|
|
102
|
+
const requestKey=`${module}\0${version}`;
|
|
103
|
+
if(!requests.has(requestKey))requests.set(requestKey,Promise.resolve().then(()=>lookup(module,version)));
|
|
104
|
+
const value=await requests.get(requestKey);
|
|
105
|
+
observation=value?.info?value:{info:value,observedAt:Date.now(),stale:false};
|
|
106
|
+
}
|
|
107
|
+
if(!validStamp(observation.observedAt))throw Error('invalid Go proxy evidence timestamp');
|
|
108
|
+
}catch(error){
|
|
109
|
+
// The proxy does not know this version of the module: the proposal was wrong, not the source.
|
|
110
|
+
if(!options.offline&&[404,410].includes(error.status)){conflicting=true;continue;}
|
|
111
|
+
let saved;try{if(!options.offline)saved=cacheRepo().get('go-main-identity',key);}catch{}
|
|
112
|
+
if(saved&&validStamp(saved.fetchedAt)){
|
|
113
|
+
observation={info:saved.value,observedAt:saved.fetchedAt,stale:true};
|
|
114
|
+
warn(`Go module version refresh failed for ${module}@${version}; cached evidence is stale: ${error.message}`);
|
|
115
|
+
}else{failed=true;warn(`Go module version evidence unavailable for ${module}@${version}: ${error.message}`);continue;}
|
|
116
|
+
}
|
|
117
|
+
const info=observation.info,origin=info?.Origin||{};
|
|
118
|
+
if(!proves(info,candidate,module,revision)){
|
|
119
|
+
conflicting=true;
|
|
120
|
+
if(!options.offline)try{cacheRepo().delete('go-main-identity',key);}catch{}
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if(observation.stale){stale++;if(!warnings.some(w=>w.message.includes(`${module}@${version}`)))warn(`Go module version evidence is stale for ${module}@${version}.`);}
|
|
124
|
+
if(!options.offline)try{cacheRepo().put('go-main-identity',key,info,{fetchedAt:observation.observedAt,stale:!!observation.stale,metadata:{source:'go-module-proxy',module,version}});}
|
|
125
|
+
catch(error){warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy-cache',message:`Could not cache Go module version evidence for ${module}@${version}: ${error.message}`});}
|
|
126
|
+
identified=true;
|
|
127
|
+
const occurrence=`${binaryPath}\0${module}\0${version}`;
|
|
128
|
+
if(seen.has(occurrence))break;
|
|
129
|
+
seen.add(occurrence);
|
|
130
|
+
const dep=makeDepRecord({ecosystem:'go',name:module,version,manifestPath:binaryPath,provenance:'binary-module',scope:'runtime'});
|
|
131
|
+
dep.coordKey=`binary-module:${binaryPath}:${module}@${version}`;
|
|
132
|
+
dep.binaryEvidence={binaryPath,source:'go-vcs-and-module-proxy',versionProposedBy:candidate.proposedBy,binarySha256:binary.hashes.sha256,original:main[0],revision,modified:false,configDigest,
|
|
133
|
+
declaredSource:candidate.source?labels['org.opencontainers.image.source']:null,declaredVersion:version,
|
|
134
|
+
proxyOrigin:{VCS:origin.VCS,URL:origin.URL,Ref:origin.Ref,Hash:origin.Hash},observedAt:observation.observedAt,stale:!!observation.stale};
|
|
135
|
+
outputs.push(dep);
|
|
136
|
+
break;
|
|
32
137
|
}
|
|
33
|
-
|
|
34
|
-
if(info?.Version!==version||origin.VCS!=='git'||repo(origin.URL)!==source||origin.Ref!==tagRef(module,source,version)||String(origin.Hash||'').toLowerCase()!==revision.toLowerCase()){conflicts++;if(!options.offline)try{cacheRepo().delete('go-main-identity',key);}catch{}continue;}
|
|
35
|
-
if(observation.stale){stale++;if(!warnings.some(w=>w.source==='go-proxy' && w.message.includes(`${module}@${version}`)))warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version evidence is stale for ${module}@${version}.`});}
|
|
36
|
-
if(!options.offline)try{cacheRepo().put('go-main-identity',key,info,{fetchedAt:observation.observedAt,stale:!!observation.stale,metadata:{source:'go-module-proxy',module,version}});}catch(error){warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy-cache',message:`Could not cache Go module version evidence: ${error.message}`});}
|
|
37
|
-
const occurrence=`${binaryPath}\0${module}\0${version}`;if(seen.has(occurrence))continue;seen.add(occurrence);
|
|
38
|
-
const dep=makeDepRecord({ecosystem:'go',name:module,version,manifestPath:binaryPath,provenance:'binary-module',scope:'runtime'});
|
|
39
|
-
dep.coordKey=`binary-module:${binaryPath}:${module}@${version}`;
|
|
40
|
-
dep.binaryEvidence={binaryPath,source:'go-vcs-and-module-proxy',binarySha256:binary.hashes.sha256,original:main[0],revision,modified:false,configDigest:metadata.configDigest,declaredSource:labels['org.opencontainers.image.source'],declaredVersion:version,proxyOrigin:{VCS:origin.VCS,URL:origin.URL,Ref:origin.Ref,Hash:origin.Hash},observedAt:observation.observedAt,stale:!!observation.stale,verification:'vcs-metadata-consistent',symbolReachability:'unknown'};
|
|
41
|
-
outputs.push(dep);
|
|
138
|
+
if(!identified){if(failed)unavailable++;else if(conflicting)conflicts++;}
|
|
42
139
|
}
|
|
43
|
-
|
|
140
|
+
const examined=candidates||conflicts;
|
|
141
|
+
return {deps:outputs,warnings,coverage:{collector:'go-main-identity',execution:unavailable||conflicts||stale?'partial':candidates?'completed':'not-applicable',
|
|
142
|
+
result:outputs.length?'identified':unavailable?'unavailable':conflicts?'conflicting-evidence':examined?'no-match':'no-candidate',count:outputs.length,candidates,conflicts,stale}};
|
|
44
143
|
}
|
|
45
|
-
module.exports={resolveGoMainIdentities};
|
|
144
|
+
module.exports={resolveGoMainIdentities,linkerVersions,moduleVersion};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
// Publisher advisories are separate from CVEProject/OSV. Only a verified Go
|
|
3
3
|
// main-module repository and exact typed package can produce a candidate.
|
|
4
|
-
const {createCacheRepository}=require('../cache
|
|
5
|
-
const {compareSemver}=require('../osv
|
|
4
|
+
const {createCacheRepository}=require('../cache/repository');
|
|
5
|
+
const {compareSemver}=require('../providers/osv/db');
|
|
6
6
|
const GHSA=/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i,CVE=/^CVE-\d{4}-\d{4,}$/i;
|
|
7
7
|
function repository(dep){const e=dep.binaryEvidence;if(e?.source!=='go-vcs-and-module-proxy'||e.verification!=='vcs-metadata-consistent')return null;try{const u=new URL(e.proxyOrigin.URL);if(u.protocol!=='https:'||u.hostname!=='github.com'||u.username||u.password||u.port||u.search||u.hash)return null;const m=/^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(u.pathname);if(!m)return null;const root=`github.com/${m[1]}/${m[2]}`;return dep.name===root||dep.name?.startsWith(root+'/')?`${m[1]}/${m[2]}`:null;}catch{return null;}}
|
|
8
8
|
function affected(version,range){if(typeof range!=='string'||range.length>500||compareSemver(version,version)==null)return null;const branches=range.split(/\s*\|\|\s*/);if(!branches.length||branches.length>20)return null;let unknown=false;for(const branch of branches){const parts=branch.split(',').map(x=>x.trim());if(!parts.length||parts.some(x=>!x))return null;let yes=true;for(const part of parts){const m=/^(<=|>=|<|>|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(part);if(!m){unknown=true;yes=false;break;}const cmp=compareSemver(version,m[2]);if(cmp==null){unknown=true;yes=false;break;}const op=m[1]||'=';if(!({'<':cmp<0,'<=':cmp<=0,'>':cmp>0,'>=':cmp>=0,'=':cmp===0}[op]))yes=false;}if(yes)return true;}return unknown?null:false;}
|
|
9
9
|
async function assessGoPublisherAdvisories(deps,options={}){
|
|
10
10
|
const groups=new Map();for(const dep of deps instanceof Map?deps.values():deps||[]){if(dep.ecosystem!=='go'||!dep.version)continue;const repo=repository(dep);if(repo){if(!groups.has(repo))groups.set(repo,[]);groups.get(repo).push(dep);}}
|
|
11
|
-
const matches=[],coverage=[],warnings=[];if(!groups.size)return {matches,coverage,warnings};const cache=createCacheRepository(options.cacheDir||require('../cache
|
|
11
|
+
const matches=[],coverage=[],warnings=[];if(!groups.size)return {matches,coverage,warnings};const cache=createCacheRepository(options.cacheDir||require('../cache/directory').getCacheDir()),providers=require('../providers');
|
|
12
12
|
for(const [repo,items] of groups){let snapshot,observedAt,stale=false,failed=null;let cached=null;try{cached=cache.get('publisher-go-advisories',repo);}catch{}
|
|
13
13
|
try{if(options.offline){if(!cached)throw Error('publisher advisory snapshot is not cached');snapshot=cached.value;observedAt=cached.fetchedAt;stale=cached.stale;}else{
|
|
14
14
|
const advisories=[];let end=false;observedAt=Date.now();const max=options.maxPublisherPages??10;if(!Number.isSafeInteger(max)||max<1||max>100)throw Error('invalid publisher page limit');
|
|
@@ -17,6 +17,7 @@ async function assessGoPublisherAdvisories(deps,options={}){
|
|
|
17
17
|
}}catch(error){failed=error.message;if(!options.offline&&cached){snapshot=cached.value;observedAt=cached.fetchedAt;stale=true;try{cache.put('publisher-go-advisories',repo,snapshot,{fetchedAt:observedAt,stale:true,metadata:{source:'github-publisher',repo}})}catch{}}else snapshot=null;}
|
|
18
18
|
if(!snapshot||!Array.isArray(snapshot.advisories)||!Number.isFinite(observedAt)||observedAt<=0||observedAt>Date.now()+300000){warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory feed unavailable for ${repo}: ${failed||'invalid cached evidence'}`});coverage.push({collector:'github-publisher',execution:'partial',result:'indeterminate',repository:repo});continue;}
|
|
19
19
|
let unknown=0;for(const dep of items)for(const advisory of snapshot.advisories){if(!GHSA.test(advisory?.ghsa_id||'')||!Array.isArray(advisory.vulnerabilities)){unknown++;continue;}for(const v of advisory.vulnerabilities){if(String(v?.package?.ecosystem||'').toLowerCase()!=='go'||v.package.name!==dep.name)continue;const verdict=affected(dep.version,v.vulnerable_version_range);if(verdict===null){unknown++;continue;}if(!verdict)continue;const id=CVE.test(advisory.cve_id||'')?advisory.cve_id.toUpperCase():advisory.ghsa_id;const score=Number.isFinite(advisory.cvss?.score)&&advisory.cvss.score>=0&&advisory.cvss.score<=10?advisory.cvss.score:null;const severity=String(advisory.severity||'UNKNOWN').toUpperCase().replace('MODERATE','MEDIUM');matches.push({dep,source:'github-publisher',confidence:'exact',advisoryId:advisory.ghsa_id,cve:{id,aliases:id===advisory.ghsa_id?[]:[advisory.ghsa_id],description:typeof advisory.description==='string'?advisory.description:'',severity:['CRITICAL','HIGH','MEDIUM','LOW'].includes(severity)?severity:'UNKNOWN',score,fixVersion:typeof v.patched_versions==='string'&&/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.patched_versions)?v.patched_versions:null,published:advisory.published_at||null,modified:advisory.updated_at||null,advisorySource:advisory.html_url||null,publisherEvidence:{repository:repo,observedAt,stale,range:v.vulnerable_version_range,scope:'explicit-go-package'}}});}}
|
|
20
|
+
if(!stale&&!failed&&!unknown)for(const dep of items)options.onPackageConsulted?.(dep,'github-publisher');
|
|
20
21
|
if(stale||failed)warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory evidence for ${repo} is stale${failed?`: ${failed}`:'.'}`});coverage.push({collector:'github-publisher',execution:stale||unknown?'partial':'completed',result:unknown?'indeterminate':'consulted',repository:repo,unknown,count:matches.filter(m=>items.includes(m.dep)).length,observedAt,fetchedAt:observedAt,scope:'explicit-go-package'});
|
|
21
22
|
}
|
|
22
23
|
return {matches,coverage,warnings};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { makeDepRecord } = require('../dep-record');
|
|
3
|
+
const { makeDepRecord } = require('../inventory/dep-record');
|
|
4
4
|
const { catalog, binaryProduct, imageProduct } = require('./product-catalog');
|
|
5
5
|
|
|
6
6
|
function describe(dep) {
|
|
@@ -89,7 +89,7 @@ function applyProductVersions(deps) {
|
|
|
89
89
|
deps.push(...additions.filter((d) => !linkedFiles.has(JSON.stringify([d.artifactPath, d.name]))));
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
function productCoverage(target, checks, assessedPackages, matches) {
|
|
92
|
+
function productCoverage(target, checks, assessedPackages, matches, distributionState) {
|
|
93
93
|
const affected = new Set(
|
|
94
94
|
matches.filter((m) => m.dep?.artifactTargetId === target.id).map((m) => m.dep.coordKey)
|
|
95
95
|
);
|
|
@@ -132,8 +132,8 @@ function productCoverage(target, checks, assessedPackages, matches) {
|
|
|
132
132
|
advisoryCheck =
|
|
133
133
|
keys.length && keys.every((k) => assessedPackages.has(k))
|
|
134
134
|
? 'distribution-no-match'
|
|
135
|
-
: 'distribution-incomplete';
|
|
136
|
-
} else if (relevant.length && relevant.every((c) => c.execution === 'completed'))
|
|
135
|
+
: distributionState || 'distribution-incomplete';
|
|
136
|
+
} else if (relevant.length && relevant.every((c) => c.execution === 'completed' && !c.unknown))
|
|
137
137
|
advisoryCheck = 'no-match';
|
|
138
138
|
else if (relevant.length && relevant.every((c) => c.execution === 'not-applicable'))
|
|
139
139
|
advisoryCheck = 'disabled';
|
|
@@ -142,6 +142,7 @@ function productCoverage(target, checks, assessedPackages, matches) {
|
|
|
142
142
|
else if (!relevant.length) reason = 'no-upstream-check';
|
|
143
143
|
entries.push({
|
|
144
144
|
...product,
|
|
145
|
+
componentKey:dep.coordKey,
|
|
145
146
|
name: dep.name,
|
|
146
147
|
path: dep.artifactPath,
|
|
147
148
|
version,
|
package/lib/artifacts/index.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
+
// An OCI 1.1 manifest or descriptor may state its artifactType. One that names the image config
|
|
3
|
+
// type is an ordinary image (cgr.dev publishes its indexes that way); any other is an artifact.
|
|
4
|
+
const IMAGE_CONFIG_TYPES = ['application/vnd.oci.image.config.v1+json', 'application/vnd.docker.container.image.v1+json'];
|
|
5
|
+
const foreignArtifact = type => !!type && !IMAGE_CONFIG_TYPES.includes(type);
|
|
2
6
|
|
|
3
7
|
// Image archives are untrusted data. Nothing in them is executed, and no archive
|
|
4
8
|
// path is ever handed directly to a host filesystem API.
|
|
@@ -19,8 +23,12 @@ function limits(options) {
|
|
|
19
23
|
for (const [k, v] of Object.entries(result)) if (!Number.isSafeInteger(v) || v < 1) throw new Error(`Invalid artifact limit ${k}`);
|
|
20
24
|
return result;
|
|
21
25
|
}
|
|
26
|
+
// Backslashes and drive prefixes are ordinary file name characters on POSIX
|
|
27
|
+
// (systemd ships `system-systemd\x2dcryptsetup.slice`); on Windows they would
|
|
28
|
+
// be separators or drives, so such entries are skipped there before extraction.
|
|
29
|
+
const hostUnsafe = value => path.sep !== '/' && (value.includes('\\') || /^[A-Za-z]:/.test(value));
|
|
22
30
|
function cleanName(value, lim) {
|
|
23
|
-
if (typeof value !== 'string' || value.includes('\0') || value
|
|
31
|
+
if (typeof value !== 'string' || value.includes('\0') || hostUnsafe(value) || value.startsWith('/')) throw new Error(`Unsafe archive path: ${value}`);
|
|
24
32
|
const parts = value.split('/').filter(p => p && p !== '.');
|
|
25
33
|
if (parts.includes('..') || parts.length > lim.maxDepth) throw new Error(`Unsafe archive path: ${value}`);
|
|
26
34
|
return parts.join('/');
|
|
@@ -66,12 +74,14 @@ async function readTar(file, workspace, state, options, expectedDiffId) {
|
|
|
66
74
|
const entries = []; const extract = tar.extract(); let failure;
|
|
67
75
|
extract.on('entry', (header, stream, next) => {
|
|
68
76
|
(async () => {
|
|
69
|
-
const
|
|
77
|
+
const skip = typeof header.name === 'string' && (hostUnsafe(header.name) || (['symlink', 'link'].includes(header.type) && hostUnsafe(String(header.linkname || ''))));
|
|
78
|
+
const name = skip ? header.name : cleanName(header.name, state.limits);
|
|
70
79
|
if (Buffer.byteLength(header.name) + Buffer.byteLength(header.linkname || '') + Buffer.byteLength(JSON.stringify(header.pax || {})) > state.limits.maxMetadataBytes) throw new Error('Archive metadata size limit exceeded');
|
|
71
80
|
if (++state.entries > state.limits.maxEntries) throw new Error('Archive entry limit exceeded');
|
|
72
81
|
if (!Number.isSafeInteger(header.size) || header.size < 0 || header.size > state.limits.maxFileBytes) throw new Error(`Archive file size limit exceeded: ${name}`);
|
|
73
82
|
state.bytes += header.size;
|
|
74
83
|
if (state.bytes > state.limits.maxBytes) throw new Error('Archive decompressed size limit exceeded');
|
|
84
|
+
if (skip) { state.warnings.push(`Skipped archive entry whose name cannot be represented on this host: ${header.name}`); for await (const _ of stream) {} next(); return; }
|
|
75
85
|
const entry = { name, type: header.type, linkname: header.linkname, size: header.size };
|
|
76
86
|
if (header.type === 'file' || header.type === 'contiguous-file') {
|
|
77
87
|
entry.file = path.join(workspace, `entry-${state.serial++}`);
|
|
@@ -92,14 +102,15 @@ async function safePath(root, name, lim, followFinal = false) {
|
|
|
92
102
|
let parts = cleanName(name, lim).split('/').filter(Boolean), resolved = [], hops = 0;
|
|
93
103
|
while (parts.length) {
|
|
94
104
|
const p = parts.shift();
|
|
95
|
-
|
|
105
|
+
// Like Linux at `/`, `..` at the artifact root stays at the root.
|
|
106
|
+
if (p === '..') { resolved.pop(); continue; }
|
|
96
107
|
if (!p || p === '.') continue;
|
|
97
108
|
const candidate = path.join(root, ...resolved, p); let st;
|
|
98
109
|
try { st = await fsp.lstat(candidate); } catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; }
|
|
99
110
|
if (st && st.isSymbolicLink() && (parts.length || followFinal)) {
|
|
100
111
|
if (++hops > 40) throw new Error('Too many symbolic links');
|
|
101
112
|
const link = await fsp.readlink(candidate);
|
|
102
|
-
if (link
|
|
113
|
+
if (hostUnsafe(link) || link.includes('\0')) throw new Error('Unsafe symbolic link');
|
|
103
114
|
if (link.startsWith('/')) resolved = [];
|
|
104
115
|
parts = [...link.split('/'), ...parts]; continue;
|
|
105
116
|
}
|
|
@@ -123,8 +134,12 @@ async function applyLayer(root, entries, state, whiteouts) {
|
|
|
123
134
|
if (whiteouts) for (const e of entries) {
|
|
124
135
|
const base = path.posix.basename(e.name), dir = path.posix.dirname(e.name);
|
|
125
136
|
if (!base.startsWith('.wh.')) continue;
|
|
126
|
-
const parent = await safePath(root, dir === '.' ? '' : dir, lim, true);
|
|
127
137
|
if (base === '.wh..wh..opq') {
|
|
138
|
+
// An opaque directory replaces what lower layers had at `dir`. A lower symlink
|
|
139
|
+
// there is replaced by the directory itself, never followed to its target.
|
|
140
|
+
const parent = await safePath(root, dir === '.' ? '' : dir, lim); let st;
|
|
141
|
+
try { st = await fsp.lstat(parent); } catch (err) { if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw err; }
|
|
142
|
+
if (st && !st.isDirectory()) { await remove(parent); await fsp.mkdir(parent, { mode: 0o700 }); continue; }
|
|
128
143
|
let names = []; try { names = await fsp.readdir(parent); } catch (err) { if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw err; }
|
|
129
144
|
for (const n of names) await remove(path.join(parent, n));
|
|
130
145
|
} else {
|
|
@@ -135,6 +150,8 @@ async function applyLayer(root, entries, state, whiteouts) {
|
|
|
135
150
|
const deferred = new Map();
|
|
136
151
|
for (const e of entries) {
|
|
137
152
|
if (!e.name || (whiteouts && path.posix.basename(e.name).startsWith('.wh.'))) continue;
|
|
153
|
+
// Device nodes, pipes and sockets (dev/null, dev/console, dev/initctl) hold no content to inventory.
|
|
154
|
+
if (['character-device', 'block-device', 'fifo', 'socket'].includes(e.type)) continue;
|
|
138
155
|
if (!['file', 'contiguous-file', 'directory', 'symlink', 'link'].includes(e.type)) { state.warnings.push(`Unsupported archive entry type ${e.type}: ${e.name}`); continue; }
|
|
139
156
|
deferred.delete(e.name);
|
|
140
157
|
await parents(root, e.name, lim);
|
|
@@ -153,10 +170,10 @@ async function applyLayer(root, entries, state, whiteouts) {
|
|
|
153
170
|
} else {
|
|
154
171
|
await remove(p);
|
|
155
172
|
if (e.type === 'symlink') {
|
|
156
|
-
if (typeof e.linkname !== 'string' || e.linkname.includes('\0') || e.linkname
|
|
157
|
-
// Store absolute container links as relative host links;
|
|
173
|
+
if (typeof e.linkname !== 'string' || e.linkname.includes('\0') || hostUnsafe(e.linkname)) throw new Error(`Unsafe link: ${e.name}`);
|
|
174
|
+
// Store absolute container links as relative host links; `..` clamps at the root as on Linux.
|
|
158
175
|
const targetParts = e.linkname.startsWith('/') ? [] : e.name.split('/').slice(0, -1);
|
|
159
|
-
for (const segment of e.linkname.split('/')) { if (!segment || segment === '.') continue; if (segment === '..')
|
|
176
|
+
for (const segment of e.linkname.split('/')) { if (!segment || segment === '.') continue; if (segment === '..') targetParts.pop(); else targetParts.push(segment); }
|
|
160
177
|
const target = path.join(root, ...targetParts); await fsp.symlink(path.relative(path.dirname(p), target) || '.', p);
|
|
161
178
|
} else await fsp.copyFile(e.file, p);
|
|
162
179
|
}
|
|
@@ -192,9 +209,9 @@ async function openArtifact(input, options = {}) {
|
|
|
192
209
|
return result;
|
|
193
210
|
}
|
|
194
211
|
}
|
|
195
|
-
const temp = await fsp.mkdtemp(path.join(options.tmpdir || os.tmpdir(), 'vigievuln-artifact-'));
|
|
212
|
+
const temp = require('../images/temp-roots').track(await fsp.mkdtemp(path.join(options.tmpdir || os.tmpdir(), 'vigievuln-artifact-')));
|
|
196
213
|
const state = { limits: lim, entries: 0, bytes: 0, serial: 0, warnings: [] }; let cleaned = false;
|
|
197
|
-
const cleanup = async () => { if (!cleaned) { cleaned = true; await remove(temp); } };
|
|
214
|
+
const cleanup = async () => { if (!cleaned) { cleaned = true; await remove(temp); require('../images/temp-roots').untrack(temp); } };
|
|
198
215
|
try {
|
|
199
216
|
const targets = [];
|
|
200
217
|
const root = async () => { const dir = path.join(temp, `root-${targets.length}`); await fsp.mkdir(dir); return dir; };
|
|
@@ -245,13 +262,13 @@ async function openArtifact(input, options = {}) {
|
|
|
245
262
|
};
|
|
246
263
|
const index = await readJson(await get('index.json'), state), globalWarnings = [];
|
|
247
264
|
const visit = async (desc, ancestry = [], platform) => {
|
|
248
|
-
if (desc.artifactType || desc.annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' || (desc.platform?.os === 'unknown' && desc.platform?.architecture === 'unknown')) {
|
|
265
|
+
if (foreignArtifact(desc.artifactType) || desc.annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' || (desc.platform?.os === 'unknown' && desc.platform?.architecture === 'unknown')) {
|
|
249
266
|
globalWarnings.push(`Skipped non-image artifact ${desc.digest || '(unknown digest)'}`); return;
|
|
250
267
|
}
|
|
251
268
|
if (ancestry.includes(desc.digest) || ancestry.length >= lim.maxDepth) throw new Error('OCI index cycle or depth limit');
|
|
252
269
|
const document = await readJson(await blob(desc), state);
|
|
253
270
|
if (Array.isArray(document.manifests)) { for (const child of document.manifests) await visit(child, [...ancestry, desc.digest], child.platform || platform); return; }
|
|
254
|
-
if (document.artifactType || document.subject || (document.config?.mediaType && !['application/vnd.oci.image.config.v1+json', 'application/vnd.docker.container.image.v1+json'].includes(document.config.mediaType))) {
|
|
271
|
+
if (foreignArtifact(document.artifactType) || document.subject || (document.config?.mediaType && !['application/vnd.oci.image.config.v1+json', 'application/vnd.docker.container.image.v1+json'].includes(document.config.mediaType))) {
|
|
255
272
|
globalWarnings.push(`Skipped non-image artifact ${desc.digest}`); return;
|
|
256
273
|
}
|
|
257
274
|
if (!document.config || !Array.isArray(document.layers)) throw new Error('Invalid OCI image manifest');
|
|
@@ -267,6 +284,12 @@ async function openArtifact(input, options = {}) {
|
|
|
267
284
|
for (const target of targets) target.metadata.warnings.push(...globalWarnings);
|
|
268
285
|
}
|
|
269
286
|
return { targets, cleanup };
|
|
270
|
-
} catch (e) {
|
|
287
|
+
} catch (e) {
|
|
288
|
+
await cleanup();
|
|
289
|
+
if (e.code === 'ENOSPC') throw Object.assign(new Error(
|
|
290
|
+
'Temporary space exhausted while extracting the image in ' + path.dirname(temp) +
|
|
291
|
+
'. Set TMPDIR to a filesystem with more free space.', { cause: e }), { code: e.code });
|
|
292
|
+
throw e;
|
|
293
|
+
}
|
|
271
294
|
}
|
|
272
295
|
module.exports = { openArtifact, DEFAULT_LIMITS };
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// A saved inventory is validated before this transformation. Filtering an old
|
|
4
4
|
// snapshot cannot reconstruct descriptors that its collectors never observed.
|
|
5
|
-
const { IMAGE_COMPONENT_SCOPE, isNpmPackageDescriptor, imageComponentRole, imageComponentSource } = require('./component-scope');
|
|
5
|
+
const { IMAGE_COMPONENT_SCOPE, isSystemProjectPath, isNpmPackageDescriptor, imageComponentRole, imageComponentSource } = require('./component-scope');
|
|
6
6
|
const SCOPE_REASON = 'image-inventory-scope-outdated';
|
|
7
7
|
const SCOPE_MESSAGE = 'The saved image inventory predates the current component scope or contains package metadata fragments. Reacquire the image to establish its current inventory.';
|
|
8
8
|
|
|
@@ -22,12 +22,62 @@ function applyComponentScope(target, { checkPolicy = true } = {}) {
|
|
|
22
22
|
const result = structuredClone(target);
|
|
23
23
|
// Publisher SBOM contents are explicit evidence, not filesystem descriptors.
|
|
24
24
|
if (result.kind === 'sbom') return result;
|
|
25
|
+
const systemApps = result.metadata?.systemApplications;
|
|
26
|
+
if (systemApps) {
|
|
27
|
+
// Older collectors used the same result for completed enumeration and failed
|
|
28
|
+
// reads. Only a completed inventory with an explicit count can be normalized.
|
|
29
|
+
const enumerators = new Set(['dpkg','apk','rpm','installed-applications','native-binaries','project-lockfiles']);
|
|
30
|
+
for (const check of result.coverage || []) {
|
|
31
|
+
if (check.capability==='inventory' && check.execution==='completed' && check.result==='indeterminate' &&
|
|
32
|
+
!check.reason && Number.isSafeInteger(check.count) && check.count>=0 && enumerators.has(check.collector))
|
|
33
|
+
check.result='inventoried';
|
|
34
|
+
}
|
|
35
|
+
// Legacy collections could promote example manifests bundled in a gem to
|
|
36
|
+
// projects. The installed gemspec is the evidence for its installed version.
|
|
37
|
+
const storeProjects=new Set(systemApps.applications.filter(a=>a.type==='project' && !isSystemProjectPath(a.root)).map(a=>a.id));
|
|
38
|
+
if(storeProjects.size){
|
|
39
|
+
for(const field of ['applications','inventory','relations','diagnostics','coverage']){
|
|
40
|
+
if(systemApps[field])systemApps[field]=systemApps[field].filter(item=>!storeProjects.has(field==='applications'?item.id:item.applicationId));
|
|
41
|
+
}
|
|
42
|
+
result.coverage=(result.coverage || []).filter(item=>!storeProjects.has(item.applicationId));
|
|
43
|
+
for(const dep of result.deps || []){
|
|
44
|
+
if(dep.systemApplicationIds?.some(id=>storeProjects.has(id))){
|
|
45
|
+
dep.systemApplicationIds=dep.systemApplicationIds.filter(id=>!storeProjects.has(id));
|
|
46
|
+
if(!dep.systemApplicationIds.length){dep.systemSection='dependency';dep.imageRole='transitive';dep.scope='transitive';}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if(result.metadata.projectDescriptors)result.metadata.projectDescriptors=result.metadata.projectDescriptors.filter(isSystemProjectPath);
|
|
50
|
+
}
|
|
51
|
+
const replaced = require('../applications/layout').reconcileApplications(systemApps,result.deps || []);
|
|
52
|
+
if (replaced) {
|
|
53
|
+
require('../applications/layout').reparentAssessments(result,systemApps.embeddedApplications || []);
|
|
54
|
+
result.coverage=(result.coverage || []).filter(c=>!replaced.has(c.applicationId));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const layout = systemApps && require('../applications/layout').extensionLayout(systemApps.applications,systemApps.inventory);
|
|
58
|
+
const relations = new Map();
|
|
59
|
+
for (const item of systemApps?.inventory || []) {
|
|
60
|
+
if (!['direct','transitive','indirect'].includes(item.managerRelation) || !item.coord) continue;
|
|
61
|
+
for (const proof of item.evidence || []) relations.set(JSON.stringify([proof.path,item.coord,item.version]),item.managerRelation);
|
|
62
|
+
}
|
|
25
63
|
let filtered = false;
|
|
26
64
|
result.deps = (result.deps || []).filter(dep => {
|
|
65
|
+
if(systemApps && dep.provenance==='lockfile' && dep.artifactPath && !isSystemProjectPath(dep.artifactPath))return false;
|
|
27
66
|
if (isNpmFragment(dep)) { filtered = true; return false; }
|
|
28
|
-
dep.imageRole = imageComponentRole(dep);
|
|
67
|
+
if (!result.metadata?.systemApplications || !dep.systemSection) dep.imageRole = imageComponentRole(dep);
|
|
29
68
|
dep.imageSource = imageComponentSource(dep);
|
|
30
|
-
dep.
|
|
69
|
+
if (systemApps && dep.systemApplicationIds?.length && dep.provenance === 'lockfile') {
|
|
70
|
+
const coord = [dep.namespace, dep.name].filter(Boolean).join('/');
|
|
71
|
+
const npmDirect = !dep.managerRelation && dep.ecosystem === 'npm' &&
|
|
72
|
+
['prod','dev','optional','peer'].includes(dep.scope);
|
|
73
|
+
const relation = dep.managerRelation === 'unknown' || !dep.managerRelation
|
|
74
|
+
? relations.get(JSON.stringify([dep.artifactPath,coord,dep.version])) : dep.managerRelation;
|
|
75
|
+
if (relation) dep.managerRelation=relation;
|
|
76
|
+
if (npmDirect || relation === 'direct') { dep.systemSection = 'project'; dep.imageRole = 'direct'; }
|
|
77
|
+
if (relation === 'transitive' || relation === 'indirect') dep.imageRole = 'transitive';
|
|
78
|
+
}
|
|
79
|
+
if (layout) require('../applications/layout').applyExtensionScope(dep,layout);
|
|
80
|
+
if (dep.provenance !== 'lockfile') dep.scope = dep.imageRole === 'transitive' ? 'transitive' : 'runtime';
|
|
31
81
|
return true;
|
|
32
82
|
});
|
|
33
83
|
result.warnings = (result.warnings || []).filter(w => {
|