vigievuln 1.3.1 → 1.3.3

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.
Files changed (110) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/data/fingerprints/index.js +80 -0
  4. package/data/fingerprints/interpreters/javascript/bun.json +23 -0
  5. package/data/fingerprints/interpreters/javascript/deno.json +10 -0
  6. package/data/fingerprints/interpreters/javascript/electron.json +20 -0
  7. package/data/fingerprints/interpreters/javascript/gjs.json +8 -0
  8. package/data/fingerprints/interpreters/javascript/javascriptcore.json +14 -0
  9. package/data/fingerprints/interpreters/javascript/jscgtk.json +10 -0
  10. package/data/fingerprints/interpreters/javascript/node.json +26 -0
  11. package/data/fingerprints/interpreters/javascript/nwjs.json +8 -0
  12. package/data/fingerprints/interpreters/javascript/webkitgtk.json +10 -0
  13. package/data/fingerprints/interpreters/javascript/wpewebkit.json +10 -0
  14. package/data/fingerprints/interpreters/languages/dotnet.json +8 -0
  15. package/data/fingerprints/interpreters/languages/erlang.json +9 -0
  16. package/data/fingerprints/interpreters/languages/gawk.json +10 -0
  17. package/data/fingerprints/interpreters/languages/guile.json +9 -0
  18. package/data/fingerprints/interpreters/languages/java.json +8 -0
  19. package/data/fingerprints/interpreters/languages/julia.json +9 -0
  20. package/data/fingerprints/interpreters/languages/lua.json +11 -0
  21. package/data/fingerprints/interpreters/languages/luajit.json +10 -0
  22. package/data/fingerprints/interpreters/languages/perl.json +11 -0
  23. package/data/fingerprints/interpreters/languages/php.json +22 -0
  24. package/data/fingerprints/interpreters/languages/powershell.json +17 -0
  25. package/data/fingerprints/interpreters/languages/pypy.json +8 -0
  26. package/data/fingerprints/interpreters/languages/python.json +24 -0
  27. package/data/fingerprints/interpreters/languages/r.json +9 -0
  28. package/data/fingerprints/interpreters/languages/racket.json +9 -0
  29. package/data/fingerprints/interpreters/languages/raku.json +8 -0
  30. package/data/fingerprints/interpreters/languages/ruby.json +21 -0
  31. package/data/fingerprints/interpreters/languages/tcl.json +9 -0
  32. package/data/fingerprints/interpreters/shells/bash.json +10 -0
  33. package/data/fingerprints/interpreters/shells/dash.json +8 -0
  34. package/data/fingerprints/interpreters/shells/fish.json +9 -0
  35. package/data/fingerprints/interpreters/shells/ksh.json +8 -0
  36. package/data/fingerprints/interpreters/shells/zsh.json +9 -0
  37. package/data/fingerprints/services/databases/clickhouse.json +8 -0
  38. package/data/fingerprints/services/databases/elasticsearch.json +8 -0
  39. package/data/fingerprints/services/databases/etcd.json +9 -0
  40. package/data/fingerprints/services/databases/mariadb.json +9 -0
  41. package/data/fingerprints/services/databases/memcached.json +9 -0
  42. package/data/fingerprints/services/databases/mongo.json +8 -0
  43. package/data/fingerprints/services/databases/mysql.json +9 -0
  44. package/data/fingerprints/services/databases/opensearch.json +8 -0
  45. package/data/fingerprints/services/databases/postgres.json +18 -0
  46. package/data/fingerprints/services/databases/redis.json +9 -0
  47. package/data/fingerprints/services/databases/valkey.json +8 -0
  48. package/data/fingerprints/services/dns-directory/bind.json +8 -0
  49. package/data/fingerprints/services/dns-directory/dnsmasq.json +8 -0
  50. package/data/fingerprints/services/dns-directory/slapd.json +8 -0
  51. package/data/fingerprints/services/dns-directory/unbound.json +8 -0
  52. package/data/fingerprints/services/mail/cyrus.json +8 -0
  53. package/data/fingerprints/services/mail/dovecot.json +8 -0
  54. package/data/fingerprints/services/mail/exim.json +9 -0
  55. package/data/fingerprints/services/mail/opendkim.json +8 -0
  56. package/data/fingerprints/services/mail/opensmtpd.json +8 -0
  57. package/data/fingerprints/services/mail/postfix.json +8 -0
  58. package/data/fingerprints/services/mail/rspamd.json +8 -0
  59. package/data/fingerprints/services/mail/sendmail.json +8 -0
  60. package/data/fingerprints/services/messaging/kafka.json +8 -0
  61. package/data/fingerprints/services/messaging/mosquitto.json +8 -0
  62. package/data/fingerprints/services/messaging/nats.json +9 -0
  63. package/data/fingerprints/services/messaging/rabbitmq.json +8 -0
  64. package/data/fingerprints/services/remote-access/dropbear.json +8 -0
  65. package/data/fingerprints/services/remote-access/openssh.json +10 -0
  66. package/data/fingerprints/services/remote-access/proftpd.json +8 -0
  67. package/data/fingerprints/services/remote-access/samba.json +8 -0
  68. package/data/fingerprints/services/remote-access/vsftpd.json +8 -0
  69. package/data/fingerprints/services/web-proxies/apache.json +18 -0
  70. package/data/fingerprints/services/web-proxies/caddy.json +9 -0
  71. package/data/fingerprints/services/web-proxies/envoy.json +8 -0
  72. package/data/fingerprints/services/web-proxies/haproxy.json +10 -0
  73. package/data/fingerprints/services/web-proxies/lighttpd.json +8 -0
  74. package/data/fingerprints/services/web-proxies/nginx.json +14 -0
  75. package/data/fingerprints/services/web-proxies/squid.json +8 -0
  76. package/data/fingerprints/services/web-proxies/tomcat.json +8 -0
  77. package/data/fingerprints/services/web-proxies/traefik.json +9 -0
  78. package/data/fingerprints/services/web-proxies/varnish.json +8 -0
  79. package/lib/artifacts/component-scope.js +26 -3
  80. package/lib/artifacts/elf-product.js +215 -0
  81. package/lib/artifacts/image-products.js +180 -0
  82. package/lib/artifacts/install-version.js +44 -0
  83. package/lib/artifacts/inventory-scope.js +2 -1
  84. package/lib/artifacts/pe-product.js +28 -0
  85. package/lib/artifacts/product-advisories.js +207 -0
  86. package/lib/artifacts/product-catalog.js +62 -0
  87. package/lib/artifacts/report-inventory.js +7 -1
  88. package/lib/artifacts/report.js +42 -7
  89. package/lib/artifacts/retire.js +80 -0
  90. package/lib/artifacts/scan.js +40 -13
  91. package/lib/cli-image.js +6 -1
  92. package/lib/codecs/binary/elf-metadata.js +6 -0
  93. package/lib/codecs/binary/metadata.js +1 -1
  94. package/lib/codecs/binary/pe-metadata.js +47 -11
  95. package/lib/codecs/binary/scan.js +1 -1
  96. package/lib/cve-report.js +26 -3
  97. package/lib/i18n.js +2 -0
  98. package/lib/image-references.js +21 -1
  99. package/lib/json-export.js +2 -2
  100. package/lib/providers/nvd.js +16 -2
  101. package/lib/report-notices.js +1 -1
  102. package/lib/resource-cache/engine.js +3 -2
  103. package/lib/resource-cache/validate.js +1 -0
  104. package/lib/retire.js +12 -10
  105. package/lib/source-image-scan.js +1 -0
  106. package/lib/system-inventory/collect.js +1 -1
  107. package/lib/system-inventory/distribution-sources.js +1 -1
  108. package/lib/system-inventory/nginx-advisories.js +26 -8
  109. package/package.json +1 -1
  110. package/vigievuln.js +3 -1
@@ -98,11 +98,48 @@ function renderImageCves(projectInfo = {}, matches = [], locale = 'en', helpers
98
98
  if(!groups.length)return explanation+`<p>${noFindings} ${t('Reference-only images have not been scanned.','Les images uniquement déclarées n’ont pas été analysées.')}</p>`;
99
99
  return explanation+groups.map(({artifact,matches:rows})=>{
100
100
  const anchor=artifactAnchor(artifact.id),heading=`${esc(artifactTitle(artifact,artifacts))} (${rows.length})`;
101
- const detail=rows.length && typeof render==='function' ? render(rows,{image:artifact}) : `<p>${noFindings}</p>`;
101
+ const detail=rows.length && typeof render==='function' ? groupImageSources(rows,m=>m.dep,locale).map(group=>
102
+ `<details class="report-subsection" open data-image-source="${esc(group.category)}"><summary><h4>${esc(group.label)} (${group.items.length})</h4></summary><div>${render(group.items,{image:artifact})}</div></details>`).join('') : `<p>${noFindings}</p>`;
102
103
  const content=`${renderImageSummary(artifact,locale)}<p class="image-section-nav"><a class="report-section-link" href="#${anchor}">${t('Image inventory and coverage','Inventaire et couverture de l’image')}<span aria-hidden="true">→</span></a></p>${detail}`;
103
104
  return typeof minor==='function' ? minor(heading,content,{id:anchor+'-cves'}) : `<details class="report-subsection" open id="${anchor}-cves"><summary><h3>${heading}</h3></summary><div>${content}</div></details>`;
104
105
  }).join('');
105
106
  }
107
+ function renderProductCoverage(artifact,locale) {
108
+ const inventory=artifact.productInventory;
109
+ if (!inventory) return '';
110
+ const t=tr(locale);
111
+ const states={affected:t('Advisory found','Avis trouvé'),'no-match':t('No matching NVD CPE','Aucune correspondance CPE dans NVD'),
112
+ 'distribution-no-match':t('No matching distribution advisory','Aucun avis correspondant dans la distribution'),'distribution-incomplete':t('Distribution coverage incomplete','Couverture de la distribution incomplète'),disabled:t('Source disabled','Source désactivée'),
113
+ 'go-module':t('See Go module coverage','Voir la couverture du module Go'),indeterminate:t('Not established','Non établi')};
114
+ const reasons={'version-unknown':t('Version unknown','Version inconnue'),'no-upstream-check':t('No applicable upstream check','Aucun contrôle amont applicable')};
115
+ const methods={'jsc-build-markers':t('JavaScriptCore build markers','Marqueurs de compilation JavaScriptCore'),'embedded-version-banner':t('Compiled version banner','Bannière de version compilée'),'bun-module-graph':t('Bun module graph','Graphe de modules Bun'),
116
+ 'node-release-and-inspector':t('Node.js release and inspector','Version de distribution et inspecteur Node.js'),
117
+ 'pe-version-info':'PE VERSIONINFO','pe-rcdata-version-info':'PE RCDATA / VERSIONINFO','system-package':t('Installed OS package','Paquet système installé'),
118
+ 'jdk-release':t('JDK release file','Fichier de version du JDK'),'tcl-build-config':'tclConfig.sh'};
119
+ const rows=inventory.entries.map(e=>`<tr><td>${esc(e.label)}</td><td>${esc(e.path||e.name)}${e.resourceOffset!=null?' · PE @'+esc(e.resourceOffset):''}</td><td>${esc(e.version || t('Unknown','Inconnue'))}</td><td>${esc(methods[e.versionSource] || e.versionSource || t('Name only','Nom seul'))}${e.evidencePath&&e.evidencePath!==e.path?' · '+esc(e.evidencePath):''}</td><td>${esc(states[e.advisoryCheck])}${e.reason?'<br>'+esc(reasons[e.reason]||e.reason):''}</td></tr>`).join('');
120
+ const table=rows?`<table><thead><tr>${[t('Product','Produit'),t('Location','Emplacement'),t('Version','Version'),t('Evidence','Preuve'),t('CVE check','Contrôle CVE')].map(v=>'<th>'+v+'</th>').join('')}</tr></thead><tbody>${rows}</tbody></table>`:t('No catalogued product identified.','Aucun produit du catalogue identifié.');
121
+ const links=inventory.links?.length?`<details><summary>${t('Runtime library references','Bibliothèques de runtime référencées')} (${inventory.links.length})</summary><ul>${inventory.links.map(l=>`<li><code>${esc(l.requiredBy)}</code> → <code>${esc(l.library)}</code> · ${l.fileObserved?t('library inventoried','bibliothèque inventoriée'):t('referenced only, file not observed','référence seule, fichier non observé')}</li>`).join('')}</ul></details>`:'';
122
+ const unknown=inventory.unidentified||[];
123
+ const unknownFiles=unknown.length?`<details><summary>${t('Unidentified native files','Fichiers natifs non identifiés')} (${unknown.length})</summary><ul>${unknown.slice(0,100).map(f=>`<li><code>${esc(f.path)}</code> · ${esc(f.format)}</li>`).join('')}</ul>${unknown.length>100?t('First 100 shown. The JSON report contains the full list.','Les 100 premiers sont affichés. Le rapport JSON contient la liste complète.'):''}</details>`:'';
124
+ const scope=inventory.scope==='older-inventory'?t('Older inventory. Reacquire the image to inspect executable fingerprints.','Inventaire ancien. Réanalyser le contenu de l’image pour lire les empreintes.'):
125
+ inventory.scope==='publisher-sbom'?t('Based on publisher SBOM declarations. Executables were not inspected.','Selon les déclarations du SBOM éditeur. Les exécutables n’ont pas été inspectés.'):'';
126
+ return `<details open><summary>${t('Interpreter and service detection','Détection des interpréteurs et des services')}</summary>${scope?'<p>'+scope+'</p>':''}${table}${links}${unknownFiles}<details><summary>${t('Catalogued products without observed evidence','Produits du catalogue sans preuve observée')} (${inventory.unobserved.length})</summary>${esc(inventory.unobserved.join(', '))}</details><p>${t('Static inventory. Network exposure and execution are unknown. An unobserved product may still be present.','Inventaire statique. L’exécution et l’exposition réseau restent inconnues. Un produit sans preuve observée peut être présent.')}</p></details>`;
127
+ }
128
+ function groupImageSources(items,depOf,locale) {
129
+ const t=tr(locale),groups=new Map(),order=['interpreter','service','system','global','project','vendored','other'];
130
+ const labels={interpreter:t('Interpreters and runtime engines','Interpréteurs et moteurs d’exécution'),service:t('Network services','Services réseau'),system:t('System packages','Paquets système'),global:t('Global installations','Installations globales'),project:t('Applications with a root descriptor','Applications avec un descripteur racine'),vendored:t('Bundled JavaScript (RetireJS)','JavaScript embarqué (RetireJS)'),other:t('Other components and sub-dependencies','Autres composants et sous-dépendances')};
131
+ const managers={dpkg:'APT / dpkg',deb:'APT / dpkg',apk:'APK',rpm:'RPM',npm:'npm -g',python:'Python',ruby:'RubyGems',composer:'Composer'};
132
+ for(const item of items){
133
+ const dep=depOf(item),source=dep.imageSource || require('./component-scope').imageComponentSource(dep);
134
+ const product=require('./product-catalog').imageProduct(dep);
135
+ const category=product?.category || (order.includes(source.category)?source.category:'other');
136
+ const suffix=['system','global'].includes(category)?managers[source.manager] || source.manager:category==='project'?source.root:'';
137
+ const key=JSON.stringify([category,suffix]);
138
+ if(!groups.has(key))groups.set(key,{category,label:labels[category]+(suffix?' — '+suffix:''),items:[]});
139
+ groups.get(key).items.push(item);
140
+ }
141
+ return [...groups.values()].sort((a,b)=>order.indexOf(a.category)-order.indexOf(b.category)||a.label.localeCompare(b.label));
142
+ }
106
143
  function stats(group) {
107
144
  const matches=visible(group.matches),components=new Set(),advisories=new Set(),cves=new Set(),severity={critical:0,high:0,medium:0,low:0,unknown:0},updates=new Map();
108
145
  for(const m of matches) {
@@ -174,10 +211,7 @@ function renderArtifactEvidence(projectInfo = {}, locale = 'en', matches = []) {
174
211
  return `<tr><td><code>${esc(c.namespace?c.namespace+'/'+c.name:c.name||c.artifactId||c.coord||'')}</code><br>${esc(c.packageType||c.ecosystem||'')}${c._fromFinding?`<br><small>${t('From finding; not present in inventory','Issu d’un résultat ; absent de l’inventaire')}</small>`:''}</td><td>${esc(c.version||'—')}</td><td>${fixes.map(esc).join('<br>')||'—'}</td><td>${links||'—'}</td><td>${esc(c.architecture||'—')}</td><td>${esc(c.artifactPath||'—')}</td><td>${esc((c.osPackageOwners||[]).map(o=>`${o.name}@${o.version}`).join(', ')||'—')}</td></tr>`;
175
212
  }).join('');
176
213
  const table=items=>items.length?`<table class="image-inventory"><thead><tr><th>${t('Component','Composant')}</th><th>${t('Installed','Installé')}</th><th>${t('Candidate corrections','Corrections proposées')}</th><th>${t('Advisories','Avis')}</th><th>Arch</th><th>${t('Location','Emplacement')}</th><th>${t('OS package owner','Paquet système propriétaire')}</th></tr></thead><tbody>${componentRows(items)}</tbody></table>`:`<p>${t('No components observed.','Aucun composant observé.')}</p>`;
177
- const direct=inventory.filter(c=>c.imageRole==='direct'),subdeps=inventory.filter(c=>c.imageRole==='transitive'),unclassified=inventory.filter(c=>!['direct','transitive'].includes(c.imageRole));
178
- const componentSections=`<h5>${t('Direct image components','Composants directs de l’image')} (${direct.length})</h5>${table(direct)}`+
179
- `<h5>${t('Image sub-dependencies','Sous-dépendances de l’image')} (${subdeps.length})</h5>${table(subdeps)}`+
180
- (unclassified.length?`<h5>${t('Unclassified image components','Composants de l’image non classés')} (${unclassified.length})</h5>${table(unclassified)}`:'');
214
+ const componentSections=groupImageSources(inventory,c=>c,locale).map(group=>`<h5>${esc(group.label)} (${group.items.length})</h5>${table(group.items)}`).join('');
181
215
  const totals=[[t('Components','Composants'),Number(a.componentCount ?? a.components?.length ?? 0)],[t('Affected packages','Paquets affectés'),s.components],[t('Advisories','Avis'),s.advisories],[t('Unique CVEs','CVE distinctes'),s.cves]];
182
216
  const totalsTable=`<table class="image-totals"><thead><tr>${totals.map(([label])=>`<th scope="col">${label}</th>`).join('')}</tr></thead><tbody><tr>${totals.map(([,value])=>`<td class="image-total-value">${value}</td>`).join('')}</tr><tr><td colspan="4"><span class="image-severity-label">${t('CVE row severities','Sévérités des lignes CVE')}</span>${renderSeverityCounts(s.severity,locale)}</td></tr></tbody>${group.matches.length?`<tfoot><tr><td colspan="4"><a class="report-section-link" href="#${anchor}-cves">${t('View vulnerability details','Voir les vulnérabilités')}<span aria-hidden="true">→</span></a></td></tr></tfoot>`:''}</table>`;
183
217
  const noCve=visible(group.matches).filter(m=>m.dep?.ecosystem==='system' && !linkedCves(m.cve).length);
@@ -190,10 +224,11 @@ function renderArtifactEvidence(projectInfo = {}, locale = 'en', matches = []) {
190
224
  return `<details class="report-subsection" open id="${anchor}"><summary><h3>${esc(artifactTitle(a,artifacts))}</h3></summary><div>`+
191
225
  renderImageSummary(a,locale)+
192
226
  totalsTable+
227
+ renderProductCoverage(a,locale)+
193
228
  imageAction+
194
229
  (rows?`<details open><summary>${t('Coverage checks','Contrôles de couverture')}</summary><table><thead><tr><th>${t('Capability','Capacité')}</th><th>${t('Source','Source')}</th><th>${t('Execution','Exécution')}</th><th>${t('Result / limitation','Résultat / limite')}</th></tr></thead><tbody>${rows}</tbody></table></details>`:`<p>${t('Coverage information unavailable.','Informations de couverture indisponibles.')}</p>`)+
195
- renderAdvisoryObservations(a,locale)+nonCveAdvisories+`<details class="report-subsection"><summary><h4>${t('Component inventory and candidate corrections','Inventaire des composants et corrections proposées')} (${inventory.length})</h4></summary><p>${t('Libraries are listed with or without findings; system packages and native binaries are detailed when associated with an advisory. Roles describe the image inventory, not project dependency scope.','Les bibliothèques sont listées avec ou sans résultat ; les paquets système et binaires natifs sont détaillés lorsqu’un avis leur est associé. Les rôles décrivent l’inventaire de l’image et non la portée des dépendances du projet.')}</p><p>${t('Candidate versions come from individual advisories. Verify them in the replacement image; they do not establish that a particular image tag or digest is corrected.','Les versions proposées proviennent d’avis individuels. Vérifiez-les dans l’image de remplacement ; elles ne prouvent pas qu’un tag ou une empreinte d’image est corrigé.')}</p>${componentSections}</details></div></details>`;
230
+ renderAdvisoryObservations(a,locale)+nonCveAdvisories+`<details class="report-subsection"><summary><h4>${t('Component inventory and candidate corrections','Inventaire des composants et corrections proposées')} (${inventory.length})</h4></summary><p>${t('Catalogued interpreters, services and direct applications remain visible without findings. Other system packages and native binaries are detailed when associated with an advisory. Roles describe the image inventory, not project dependency scope.','Les interpréteurs et services du catalogue ainsi que les applications directes restent visibles sans CVE. Les autres paquets système et binaires natifs sont détaillés lorsqu’un avis leur est associé. Les rôles décrivent l’inventaire de l’image et non la portée des dépendances du projet.')}</p><p>${t('Candidate versions come from individual advisories. Verify them in the replacement image; they do not establish that a particular image tag or digest is corrected.','Les versions proposées proviennent d’avis individuels. Vérifiez-les dans l’image de remplacement ; elles ne prouvent pas qu’un tag ou une empreinte d’image est corrigé.')}</p>${componentSections}</details></div></details>`;
196
231
  }).join('');
197
- return referenceNotice+overview+(groups.length?`<p>${t('A raw finding is an advisory affecting a component. An advisory can link several CVEs; the CVE section groups linked CVE identifiers while advisories without linked CVEs remain below.','Un résultat brut correspond à un avis affectant un composant. Un avis peut être lié à plusieurs CVE ; la section CVE regroupe les identifiants liés et les avis sans CVE liée restent ci-dessous.')}</p>`:'')+cards+renderReferences(projectInfo,artifacts,locale);
232
+ return renderReferences(projectInfo,artifacts,locale)+referenceNotice+overview+(groups.length?`<p>${t('A raw finding is an advisory affecting a component. An advisory can link several CVEs; the CVE section groups linked CVE identifiers while advisories without linked CVEs remain below.','Un résultat brut correspond à un avis affectant un composant. Un avis peut être lié à plusieurs CVE ; la section CVE regroupe les identifiants liés et les avis sans CVE liée restent ci-dessous.')}</p>`:'')+cards;
198
233
  }
199
234
  module.exports={artifactAnchor,artifactTitle,artifactGroups,renderImageCves,renderArtifactEvidence};
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+ // Inspect image bytes only. Do not execute the image's JavaScript or follow its
3
+ // symlinks. Persist identities, then reassess them with the current signature DB.
4
+ const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
5
+ const retire=require('retire/lib/retire');
6
+ const POLICY='image-retire/1';
7
+ const EXCLUDED=new Set(['node_modules','bower_components','jspm_packages','vendor','site-packages','dist-packages','__pypackages__','.git','.npm','.yarn','.pnpm-store','.cache','.m2','.gradle','.nuget']);
8
+ async function repository(options){
9
+ const helper=require('../retire');
10
+ const refreshed=await helper.warmRetireSignatures({...options,force:options.forceUpdate});
11
+ const entry=helper.cachedSignatureEntry(options.cacheDir);
12
+ if(!entry || !refreshed.ok && !options.offline && require('../providers').hasHostedProxy())throw Error(refreshed.error || 'RetireJS signatures are unavailable');
13
+ const repo=JSON.parse(retire.replaceVersion(entry.value));
14
+ if(!repo || typeof repo!=='object' || Array.isArray(repo))throw Error('Invalid RetireJS signatures');
15
+ for(const [name,record] of Object.entries(repo))if(name.startsWith('$'))delete repo[name];else if(!record?.extractors)throw Error('Invalid RetireJS extractor');
16
+ return {repo,signaturesAt:new Date(entry.fetchedAt).toISOString(),refreshError:refreshed.ok?null:refreshed.error || 'RetireJS signatures could not be refreshed'};
17
+ }
18
+ const warning=(error,capability='inventory')=>({type:'dependency-coverage',capability,reason:'image-retire-incomplete',message:error.message});
19
+ async function collectImageJs(root,options={},ownedPaths=[]){
20
+ const deps=[],warnings=[],coverage={collector:'image-retire',capability:'inventory',execution:'completed',result:'indeterminate',files:0,excludedDirectories:[...EXCLUDED],policy:POLICY};
21
+ const owned=new Set(ownedPaths.map(p=>path.posix.normalize('/'+String(p).replace(/\\/g,'/').replace(/^\/+/,''))));
22
+ coverage.excludedOwnedFiles=0;
23
+ let signatures;
24
+ try{signatures=await repository(options);coverage.signaturesAt=signatures.signaturesAt;if(signatures.refreshError)warnings.push(warning(Error(signatures.refreshError)));}
25
+ catch(error){return {deps,warnings:[warning(error)],coverage:{...coverage,execution:'not-run',reason:error.message}};}
26
+ const maxFile=options.maxImageJsFileBytes ?? 16*1024*1024,maxBytes=options.maxImageJsBytes ?? 128*1024*1024,maxFiles=options.maxImageJsFiles ?? 10000;
27
+ let bytes=0,stopped=false;const stack=[root];
28
+ while(stack.length && !stopped){
29
+ options.signal?.throwIfAborted();
30
+ const dir=stack.pop();let entries;
31
+ try{entries=fs.readdirSync(dir,{withFileTypes:true});}catch(error){warnings.push(warning(error));continue;}
32
+ for(const entry of entries){
33
+ const fp=path.join(dir,entry.name),rel=path.relative(root,fp).split(path.sep).join('/');
34
+ if(entry.isDirectory()){
35
+ if(!EXCLUDED.has(entry.name) && !['proc','sys','dev','usr/share/nodejs'].includes(rel))stack.push(fp);
36
+ continue;
37
+ }
38
+ if(!entry.isFile() || !/\.(?:js|mjs|cjs)$/i.test(entry.name))continue;
39
+ // OS-owned libraries may be backported without changing their embedded
40
+ // upstream version. Their distribution advisories remain authoritative.
41
+ if(owned.has('/'+rel)){coverage.excludedOwnedFiles++;continue;}
42
+ try{
43
+ const size=fs.statSync(fp).size;
44
+ if(size>maxFile){warnings.push(warning(Error(`RetireJS file exceeds ${maxFile} bytes: ${rel}`)));continue;}
45
+ if(++coverage.files>maxFiles || bytes+size>maxBytes){warnings.push(warning(Error('RetireJS image scan resource limit reached')));stopped=true;break;}
46
+ bytes+=size;
47
+ let results=retire.scanFileName(rel,signatures.repo);
48
+ if(!results.length)results=retire.scanFileContent(fs.readFileSync(fp),signatures.repo,{sha1:text=>crypto.createHash('sha1').update(text).digest('hex')});
49
+ for(const result of results){
50
+ if(!result.component || !result.version)continue;
51
+ const dep=require('../dep-record').makeDepRecord({ecosystem:'npm',name:result.component,version:result.version,manifestPath:rel,provenance:'vendored',scope:'vendored'});
52
+ dep.coordKey=`retire:${rel}:${result.component}@${result.version}`;
53
+ dep.ecosystemType='retire';dep.installEvidence={source:'retire',path:rel,detection:result.detection};deps.push(dep);
54
+ }
55
+ }catch(error){warnings.push(warning(Error(`${rel}: ${error.message}`)));}
56
+ }
57
+ }
58
+ coverage.bytes=bytes;coverage.count=deps.length;if(warnings.length)coverage.execution='partial';
59
+ return {deps,warnings,coverage};
60
+ }
61
+ async function assessImageJs(target,options={}){
62
+ const coverage={artifactTargetId:target.id,capability:'advisories',collector:'image-retire',execution:'completed',result:'no-match'};
63
+ if(!options.imageRetire)return {matches:[],warnings:[],coverage:{...coverage,execution:'not-applicable',result:'not-consulted',expected:false}};
64
+ const collected=target.coverage.find(c=>c.collector==='image-retire' && c.capability==='inventory');
65
+ if(!collected || collected.policy!==POLICY)return {matches:[],warnings:[warning(Error('RetireJS image inventory is unavailable; reacquire image contents with --image-retire.'))],coverage:{...coverage,execution:'not-run',result:'indeterminate'}};
66
+ try{
67
+ const {repo,signaturesAt,refreshError}=await repository(options),matches=[],missing=[];
68
+ for(const dep of target.deps.filter(d=>d.installEvidence?.source==='retire' && !d.osPackageOwners?.length)){
69
+ if(!repo[dep.name]){missing.push(dep.name);continue;}
70
+ const raw=[{file:dep.artifactPath,results:retire.check(dep.name,dep.version,repo)}];
71
+ matches.push(...require('../retire').normaliseRetireResults(raw).map(m=>({...m,dep})));
72
+ }
73
+ const incomplete=collected.execution!=='completed'||missing.length>0||!!refreshError;
74
+ const warnings=[];
75
+ if(missing.length)warnings.push(warning(Error(`RetireJS no longer identifies: ${[...new Set(missing)].join(', ')}`),'advisories'));
76
+ if(refreshError)warnings.push(warning(Error(refreshError),'advisories'));
77
+ return {matches,warnings,coverage:{...coverage,signaturesAt,execution:incomplete?'partial':'completed',result:matches.length?'affected':incomplete?'indeterminate':'no-match'}};
78
+ }catch(error){return {matches:[],warnings:[warning(error,'advisories')],coverage:{...coverage,execution:'not-run',result:'indeterminate',reason:error.message}};}
79
+ }
80
+ module.exports={POLICY,EXCLUDED,collectImageJs,assessImageJs};
@@ -4,7 +4,7 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const crypto = require('node:crypto');
6
6
  const { makeDepRecord } = require('../dep-record');
7
- const {IMAGE_COMPONENT_SCOPE,imageComponentRole} = require('./component-scope');
7
+ const {IMAGE_COMPONENT_SCOPE,imageComponentRole,imageComponentSource} = require('./component-scope');
8
8
  const { openArtifact } = require('./index');
9
9
  const { collectInstalledApplications } = require('./applications');
10
10
  const { collectSystemInventory, assessSystemInventory, syncSystemAdvisories } = require('../system-inventory');
@@ -50,10 +50,20 @@ function systemDep(pkg, targetId, distribution) {
50
50
  async function inventoryTarget(target, options = {}) {
51
51
  const system = await collectSystemInventory(target.root, options);
52
52
  const applications = await collectInstalledApplications(target.root, options);
53
- const binaries = await require('../codecs/binary.codec').collect(target.root, { ...options, defaultExcludes: false, srcRoot: target.root });
53
+ const imageJs = options.imageRetire ? await require('./retire').collectImageJs(target.root,options,system.packages.flatMap(p=>p.ownedPaths || [])) : null;
54
+ const binaries = await require('../codecs/binary.codec').collect(target.root, { ...options, defaultExcludes: false, imageProducts:true, srcRoot: target.root });
55
+ for (const dep of binaries.deps.values()) {
56
+ const product=require('./product-catalog').binaryProduct(dep.name);
57
+ if (!['tcl','java'].includes(product?.id) || dep.binaryMetadata?.format!=='elf') continue;
58
+ const location=path.relative(target.root,dep.manifestPaths[0]);
59
+ try {
60
+ const evidence=require('./install-version').installedVersion(target.root,location,dep.binaryMetadata,product);
61
+ if (evidence) (dep.binaryMetadata.products ||= []).push(evidence);
62
+ } catch { dep.binaryMetadata.productReadError=true; }
63
+ }
54
64
  const order = (a, b) => JSON.stringify([a.ecosystem, a.manager, a.namespace, a.name, a.version, a.architecture, a.manifestPath, a.manifestPaths]).localeCompare(JSON.stringify([b.ecosystem, b.manager, b.namespace, b.name, b.version, b.architecture, b.manifestPath, b.manifestPaths]));
55
65
  const packages = portable(system.packages, target.root).map(p => ({ ...p, ...(p.ownedPaths ? { ownedPaths: [...p.ownedPaths].sort() } : {}) })).sort(order);
56
- const appDeps = portable([...applications.deps.values(), ...binaries.deps.values()], target.root).sort(order);
66
+ const appDeps = portable([...applications.deps.values(), ...binaries.deps.values(), ...(imageJs?.deps || [])], target.root).sort(order);
57
67
  const id = target.kind === 'rootfs' && target.metadata.format === 'directory'
58
68
  ? `rootfs-inventory:sha256:${sha(JSON.stringify({ distribution: system.distribution, packages, deps: appDeps }))}` : target.id;
59
69
  const owners = new Map();
@@ -79,10 +89,17 @@ async function inventoryTarget(target, options = {}) {
79
89
  const owned = evidence && !aggregate ? owners.get(pathKey(evidence)) : null;
80
90
  return qualify(owned?.length ? { ...d, osPackageOwners: owned } : d, id);
81
91
  })];
82
- for(const dep of deps){dep.imageRole=imageComponentRole(dep);dep.scope=dep.imageRole==='transitive'?'transitive':'runtime';}
83
- const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings,
92
+ require('./image-products').applyProductVersions(deps);
93
+ for(const dep of deps){dep.imageRole=imageComponentRole(dep);dep.imageSource=imageComponentSource(dep);dep.scope=dep.imageRole==='transitive'?'transitive':'runtime';}
94
+ const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings, ...(imageJs?.warnings || []),
84
95
  ...(target.metadata.warnings || [])]), target.root);
85
96
  const coverage = coverageRecords(system.coverage, id, 'inventory');
97
+ const productErrors=deps.filter(d=>d.binaryMetadata?.productReadError || d.binaryMetadata?.partial);
98
+ if(productErrors.length) {
99
+ coverage.push({artifactTargetId:id,capability:'inventory',collector:'image-product-metadata',execution:'partial',result:'indeterminate',count:productErrors.length});
100
+ warnings.push({capability:'inventory',type:'dependency-coverage',reason:'image-product-metadata-incomplete',message:'Product metadata could not be fully read in '+productErrors.length+' executable(s).'});
101
+ }
102
+ if(imageJs)coverage.push({...imageJs.coverage,artifactTargetId:id});
86
103
  coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'installed-applications',
87
104
  execution: applications.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: applications.deps.size });
88
105
  coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'native-binaries',
@@ -166,7 +183,7 @@ async function acquireInventories(input, options = {}) {
166
183
  if (cache) cache.put('image-inventory', cacheKey, createSnapshot(targets));
167
184
  return targets;
168
185
  };
169
- if (cache && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
186
+ if (cache && !options.imageRetire && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
170
187
  let targets;
171
188
  try {
172
189
  const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
@@ -175,7 +192,9 @@ async function acquireInventories(input, options = {}) {
175
192
  const digest = targets?.[0]?.metadata?.acquisition?.indexDigest;
176
193
  // Publisher SBOMs can be updated independently of the image digest.
177
194
  const scoped = targets?.map(require('./inventory-scope').applyComponentScope);
178
- if (digest && scoped.every(t => t.evidence === 'content-inventory' && t.metadata?.componentScope === require('./component-scope').IMAGE_COMPONENT_SCOPE && !t.warnings.some(w => w.reason === require('./inventory-scope').SCOPE_REASON) && t.metadata?.acquisition?.indexDigest === digest)) {
195
+ // Older APK inventories discarded the maintainer needed to identify vendor NGINX.
196
+ const vendorMetadataComplete=scoped?.every(t=>(t.packages||[]).every(p=>p.manager!=='apk'||p.sourceName!=='nginx'||p.packageMetadata));
197
+ if (digest && vendorMetadataComplete && scoped.every(t => t.evidence === 'content-inventory' && t.metadata?.componentScope === require('./component-scope').IMAGE_COMPONENT_SCOPE && !t.warnings.some(w => w.reason === require('./inventory-scope').SCOPE_REASON) && t.metadata?.acquisition?.indexDigest === digest)) {
179
198
  const current = ref.reference.includes(':') ? ref.reference : await require('../image-registry').fetchRegistryDigest(input,
180
199
  {...options, fetcher:options.registryFetcher || options.fetcher, limits:options.registryLimits});
181
200
  if (current === digest) return scoped.map(target => ({...target, evidence:'cached-inventory', originalEvidence:target.originalEvidence || target.evidence}));
@@ -184,7 +203,7 @@ async function acquireInventories(input, options = {}) {
184
203
  let registry = null, opened = null, sbomAttempt = null;
185
204
  try {
186
205
  if (options.registry) {
187
- if (options.preferSbom) {
206
+ if (options.preferSbom && !options.imageRetire) {
188
207
  try {
189
208
  const discovered = await require('../image-registry').fetchRegistrySboms(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
190
209
  // Never drop image platforms when only a subset has publisher metadata.
@@ -239,7 +258,7 @@ async function assessInventories(targets, options = {}) {
239
258
  }
240
259
  const resolvedDeps = new Map(), cveMatches = [], warnings = [], artifacts = [], warmed = new Set();
241
260
  const nativeDeps=new Map();
242
- for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
261
+ for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && dep.ecosystem!=='image-product' && dep.installEvidence?.source!=='retire' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
243
262
  let native={matches:[],unknown:[],coverage:{status:'not-applicable'}},nativePreparation={sources:[],coverage:[],warnings:[]};
244
263
  if(nativeDeps.size){
245
264
  const nativeOptions={...options};
@@ -314,8 +333,12 @@ async function assessInventories(targets, options = {}) {
314
333
  coverage.push(...coverageRecords(distribution.coverage,target.id,'advisories'));
315
334
  targetWarnings.push(...normalizeWarnings(distribution.warnings,'advisories'));
316
335
  for(const match of distribution.matches){const dep=systemDep(match.dep,target.id,target.distribution);cveMatches.push({...match,dep:resolvedDeps.get(dep.coordKey)||dep});}
336
+ const imageJsAssessment=await require('./retire').assessImageJs(target,options);
337
+ cveMatches.push(...imageJsAssessment.matches);
338
+ coverage.push(imageJsAssessment.coverage);
339
+ targetWarnings.push(...imageJsAssessment.warnings);
317
340
  options.onArtifactProgress?.({stage:'Application advisories'});
318
- const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
341
+ const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && d.ecosystem !== 'image-product' && d.installEvidence?.source !== 'retire' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
319
342
  if (appDeps.size && options.osv === false) {
320
343
  coverage.push({ artifactTargetId: target.id, capability:'advisories',collector:'osv-application',execution:'not-applicable',result:'not-consulted',expected:false,reason:'OSV is excluded by source configuration.' });
321
344
  } else if (appDeps.size) {
@@ -338,7 +361,11 @@ async function assessInventories(targets, options = {}) {
338
361
  cveMatches.push(...publisher.matches);
339
362
  coverage.push(...coverageRecords(publisher.coverage,target.id,'advisories'));
340
363
  targetWarnings.push(...normalizeWarnings(publisher.warnings,'advisories'));
341
- const identifiedBinaryPaths=new Set(target.deps.filter(d=>d.binaryEvidence?.source==='go-vcs-and-module-proxy').map(d=>d.binaryEvidence.binaryPath));
364
+ const products=await require('./product-advisories').assessProductAdvisories(target,options);
365
+ cveMatches.push(...products.matches);
366
+ coverage.push(...coverageRecords(products.coverage,target.id,'advisories'));
367
+ const productInventory=require('./image-products').productCoverage(target,products.coverage,assessedPackages,[...cveMatches,...native.matches]);
368
+ const identifiedBinaryPaths=new Set(target.deps.filter(d=>(d.ecosystem==='binary' && d.binaryEvidence?.product && d.version) || d.binaryEvidence?.source==='go-vcs-and-module-proxy').map(d=>d.binaryEvidence.binaryPath));
342
369
  const unknownBinaries = target.deps.filter(d => d.ecosystem === 'binary' && !d.osPackageOwners?.length && !identifiedBinaryPaths.has(d.artifactPath));
343
370
  if (unknownBinaries.length) {
344
371
  coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'native-binaries', execution: 'partial', result: 'indeterminate', count: unknownBinaries.length, reason: 'Native binary identities cannot all be established from embedded metadata.' });
@@ -364,9 +391,9 @@ async function assessInventories(targets, options = {}) {
364
391
  warnings.push(...targetWarnings.map(w => ({ artifactTargetId: target.id, ...w })));
365
392
  artifacts.push({ id: target.id, kind: target.kind, metadata: target.metadata, evidence: target.evidence,
366
393
  originalEvidence: target.originalEvidence, distribution: target.distribution, inventoryAt: target.inventoryAt,
367
- componentCount: target.deps.length, coverage, advisoryObservations:distribution.observations, components: target.deps.map(d => ({ ecosystem: d.ecosystem, packageType: d.packageType,
394
+ componentCount: target.deps.length, coverage, productInventory, advisoryObservations:distribution.observations, components: target.deps.map(d => ({ ecosystem: d.ecosystem, packageType: d.packageType,
368
395
  namespace: d.namespace, name: d.name, version: d.version, sourceName:d.sourceName || null, sourceVersion:d.sourceVersion || null, packageOrigin:d.packageOrigin || null, architecture: d.architecture, artifactPath: d.artifactPath,
369
- provenance: d.provenance, imageRole:d.imageRole || null, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
396
+ imageProduct:require('./image-products').describe(d), provenance: d.provenance, imageRole:d.imageRole || null, imageSource:d.imageSource || imageComponentSource(d), installEvidence:d.installEvidence, manager:d.manager, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
370
397
  purl: require('../purl').purlFor(d) })) });
371
398
  }
372
399
  const combined=require('../merge-sources').mergeBySource(cveMatches,native.matches);
package/lib/cli-image.js CHANGED
@@ -62,6 +62,8 @@ function makeCommand() {
62
62
  .option('--allow-insecure-http', 'allow HTTP to the configured advisory proxy for this invocation')
63
63
  .option('--registry', 'obtain input directly from an OCI registry; offline uses a prepared cached inventory')
64
64
  .option('--platform <os/arch[/variant]>', 'select an image platform; otherwise inspect all available platforms')
65
+ .option('--no-image-retire', 'disable RetireJS inspection of image contents')
66
+ .option('--image-retire', 'scan bundled JavaScript in image contents with RetireJS (excludes package stores)', false)
65
67
  .option('--prefer-sbom', 'prefer publisher SBOMs when associated with the selected images; signatures remain unverified')
66
68
  .option('--registry-auth <file>', 'JSON credentials {username,password,token,authOrigins}; never invokes credential helpers')
67
69
  .option('--insecure', 'allow HTTP registry endpoints explicitly')
@@ -75,7 +77,7 @@ function makeCommand() {
75
77
  .option('--no-osv', 'exclude OSV advisory matching')
76
78
  .option('--no-distro-advisories', 'exclude independent distribution tracker consultations')
77
79
  .option('--no-publisher-advisories', 'exclude publisher advisory feeds')
78
- .option('--no-nvd', 'exclude NVD enrichment')
80
+ .option('--no-nvd', 'exclude NVD enrichment and image product CVE checks')
79
81
  .option('--no-kev', 'exclude CISA KEV enrichment')
80
82
  .option('--no-epss', 'exclude EPSS enrichment')
81
83
  .option('--no-gcve', 'exclude native GCVE advisory matching and derived aliases')
@@ -156,6 +158,9 @@ async function run(args, injected = {}) {
156
158
  }
157
159
  if (opts.exportInventory) await writeSnapshot(opts.exportInventory, targets);
158
160
  const result = await assessInventories(targets, options);
161
+ result.warnings.push(...require('./image-references').unpinnedImageWarnings([
162
+ ...imageReferences,...(options.registry?[{reference:input}]:[]),
163
+ ]));
159
164
  if (opts.prepareCache) {
160
165
  const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
161
166
  if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
@@ -36,6 +36,12 @@ function extractElfMetadataFile(fd, size, options = {}) {
36
36
  }
37
37
  result.go = require('./go-buildinfo').extractGoBuildInfo({read, segments, mapped, max});
38
38
  if (!result.go) delete result.go;
39
+ if (options.imageBinaryName) {
40
+ try {
41
+ const products = require('../../artifacts/elf-product').embeddedProducts(options.imageBinaryName, {read, header, size, bits, word, u16, u32, mapped, max, segments, machine:result.machine, soname:result.soname});
42
+ if (products.length) result.products = products;
43
+ } catch { result.productReadError = true; }
44
+ }
39
45
  return result;
40
46
  } catch (error) { return { format:'elf', status:'unavailable', reason:error.message }; }
41
47
  }
@@ -1,6 +1,6 @@
1
1
  // Format registry keeps new binary parsers independent of the walker.
2
2
  const extractors = new Map([
3
- ['pe', (fd,size) => require('./pe-metadata').extractPeMetadataFile(fd,size)],
3
+ ['pe', (fd,size,opts) => require('./pe-metadata').extractPeMetadataFile(fd,size,opts)],
4
4
  ['elf', (fd,size,opts) => require('./elf-metadata').extractElfMetadataFile(fd,size,opts)],
5
5
  ]);
6
6
  function extractMetadata(kind,fd,size,opts) { const fn=extractors.get(kind); return fn ? fn(fd,size,opts) : {format:kind,status:'unsupported'}; }
@@ -4,7 +4,7 @@
4
4
  const MAX_RESOURCE = 64 * 1024 * 1024;
5
5
  const MAX_VERSION_INFO = 1024 * 1024;
6
6
 
7
- function extractPeMetadata(buf) {
7
+ function extractPeMetadata(buf, options = {}) {
8
8
  try {
9
9
  const ok = (p, n, end = buf.length) => Number.isSafeInteger(p) && p >= 0 && n >= 0 && p + n <= end;
10
10
  const u16 = p => { if (!ok(p, 2)) throw Error('bounds'); return buf.readUInt16LE(p); };
@@ -17,7 +17,7 @@ function extractPeMetadata(buf) {
17
17
  const magic = u16(opt), dir = opt + (magic === 0x10b ? 96 : magic === 0x20b ? 112 : optSize);
18
18
  if (dir + 24 > opt + optSize) return null;
19
19
  const resourceRva = u32(dir + 16), resourceSize = u32(dir + 20);
20
- if (!resourceRva || !resourceSize || resourceSize > MAX_RESOURCE) return null;
20
+ if (!resourceRva || !resourceSize || resourceSize > (options.imageProducts ? 512 * 1024 * 1024 : MAX_RESOURCE)) return null;
21
21
  const sec = opt + optSize;
22
22
  if (!ok(sec, sections * 40)) return null;
23
23
  function rvaOffset(rva, length) {
@@ -40,9 +40,35 @@ function extractPeMetadata(buf) {
40
40
  if (count > 1024 || !ok(p + 16, count * 8, end)) throw Error('entries');
41
41
  return Array.from({length: count}, (_, i) => [u32(p + 16 + i * 8), u32(p + 20 + i * 8)]);
42
42
  }
43
- const version = directory(0).find(([id, ref]) => id === 16 && (ref & 0x80000000));
44
- if (!version) return null;
45
- const values = [];
43
+ const rootEntries=directory(0);
44
+ const products=[];
45
+ let partial=false;
46
+ // Inspect direct, uncompressed PE payloads in RT_RCDATA. Keep the host's
47
+ // resources independent and bound traversal to one embedding level.
48
+ if (options.imageProducts && !options.child) {
49
+ const rcdata=rootEntries.find(([id,ref])=>id===10 && (ref & 0x80000000));
50
+ let examined=0;
51
+ const inspected=new Set();
52
+ for (const [resourceId,name] of rcdata ? directory(rcdata[1]&0x7fffffff) : []) {
53
+ if (!(name & 0x80000000)) continue;
54
+ for (const [,lang] of directory(name&0x7fffffff)) {
55
+ if ((lang & 0x80000000) || !ok(root+lang,16,end)) continue;
56
+ const entry=root+lang, length=u32(entry+4), start=rvaOffset(u32(entry),length);
57
+ if (start===null || length<64 || buf.toString('ascii',start,start+2)!=='MZ') continue;
58
+ if (inspected.has(start)) continue;
59
+ inspected.add(start);
60
+ if (++examined>16) { partial=true; break; }
61
+ const nested={length,readUInt16LE:p=>u16(start+p),readUInt32LE:p=>u32(start+p),
62
+ toString:(enc,a,b)=>buf.toString(enc,start+a,start+b)};
63
+ const child=extractPeMetadata(nested,{...options,child:true});
64
+ if (!child?.products?.length) partial=true;
65
+ for (const item of child?.products||[]) products.push({...item,source:'pe-rcdata-version-info',resourceId,resourceOffset:start});
66
+ }
67
+ }
68
+ }
69
+ const version = rootEntries.find(([id, ref]) => id === 16 && (ref & 0x80000000));
70
+ if (!version) return products.length || partial ? {format:'pe',products,partial} : null;
71
+ const values = [], versionTables=[];
46
72
  for (const [, nameRef] of directory(version[1] & 0x7fffffff)) {
47
73
  if (!(nameRef & 0x80000000)) continue;
48
74
  for (const [, langRef] of directory(nameRef & 0x7fffffff)) {
@@ -51,9 +77,9 @@ function extractPeMetadata(buf) {
51
77
  if (!ok(entry, 16, end)) continue;
52
78
  const size = u32(entry + 4), data = rvaOffset(u32(entry), size);
53
79
  if (data === null || size > MAX_VERSION_INFO || size < 6) continue;
54
- const strings = {};
80
+ const strings = {}, tables=[];
55
81
  const align = n => Math.ceil(n / 4) * 4;
56
- function block(p, limit, depth) {
82
+ function block(p, limit, depth, table=null, parent='') {
57
83
  if (depth > 5 || !ok(p, 6, limit)) return;
58
84
  const length = u16(p), valueLength = u16(p + 2), type = u16(p + 4), stop = p + length;
59
85
  if (length < 6 || stop > limit) return;
@@ -61,24 +87,34 @@ function extractPeMetadata(buf) {
61
87
  while (ok(q, 2, stop) && u16(q) !== 0) q += 2;
62
88
  if (!ok(q, 2, stop)) return;
63
89
  const key = buf.toString('utf16le', p + 6, q); q = align(q + 2);
90
+ if (options.imageProducts && depth===2 && parent==='StringFileInfo' && /^[0-9a-f]{8}$/i.test(key)) { table={}; tables.push(table); }
64
91
  const bytes = type === 1 ? valueLength * 2 : valueLength;
65
92
  if (!ok(q, bytes, stop)) return;
66
- if (type === 1 && key.length <= 256 && bytes > 0 && bytes <= 8192)
93
+ if (type === 1 && key.length <= 256 && bytes > 0 && bytes <= 8192) {
67
94
  Object.defineProperty(strings, key, { value: buf.toString('utf16le', q, q + bytes).replace(/\0+$/, ''), enumerable: true, configurable: true, writable: true });
95
+ if (table && depth===3)
96
+ Object.defineProperty(table,key,{value:strings[key],enumerable:true,configurable:true});
97
+ }
68
98
  q = align(q + bytes);
69
- while (ok(q, 6, stop)) { const n = u16(q); if (!n || q + n > stop) break; block(q, stop, depth + 1); q = align(q + n); }
99
+ while (ok(q, 6, stop)) { const n = u16(q); if (!n || q + n > stop) break; block(q, stop, depth + 1,table,key); q = align(q + n); }
70
100
  }
71
101
  block(data, data + size, 0);
72
102
  if (Object.keys(strings).length) values.push(strings);
103
+ if (options.imageProducts && tables.length) versionTables.push(...tables);
73
104
  }
74
105
  }
106
+ if (options.imageProducts) {
107
+ const item=require('../../artifacts/pe-product').versionResource(versionTables);
108
+ if (item) products.push(item);
109
+ if (products.length || partial) return {format:'pe',versionStrings:values,products,partial};
110
+ }
75
111
  return values.length ? { versionStrings: values } : null;
76
112
  } catch { return null; }
77
113
  }
78
114
 
79
115
  // Adapt the bounded parser to a file descriptor. One 64 KiB cache serves the
80
116
  // many small header/string reads; even a distant resource never loads the file.
81
- function extractPeMetadataFile(fd, size) {
117
+ function extractPeMetadataFile(fd, size, options = {}) {
82
118
  const fs = require("node:fs");
83
119
  let start = -1, cache = Buffer.alloc(0);
84
120
  const read = (offset, length) => {
@@ -99,7 +135,7 @@ function extractPeMetadataFile(fd, size) {
99
135
  readUInt16LE: offset => read(offset, 2).readUInt16LE(0),
100
136
  readUInt32LE: offset => read(offset, 4).readUInt32LE(0),
101
137
  toString: (encoding, begin, end) => read(begin, end - begin).toString(encoding),
102
- });
138
+ },options);
103
139
  }
104
140
 
105
141
  module.exports = { extractPeMetadata, extractPeMetadataFile };
@@ -50,7 +50,7 @@ function inspectFile(fp, kind, detectOnly, opts = {}) {
50
50
  sha1.update(chunk.subarray(0, count)); sha256.update(chunk.subarray(0, count));
51
51
  offset += count;
52
52
  }
53
- const metadata = require("./metadata").extractMetadata(kind, fd, before.size, opts);
53
+ const metadata = require("./metadata").extractMetadata(kind, fd, before.size, opts.imageProducts ? { ...opts, imageBinaryName: path.basename(fp) } : opts);
54
54
  const after = fs.fstatSync(fd);
55
55
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs)
56
56
  throw Error("file changed during binary scan");
package/lib/cve-report.js CHANGED
@@ -1092,6 +1092,17 @@ function formatCwesVerbose(cwes) {
1092
1092
  }).join("")}</ul>`;
1093
1093
  }
1094
1094
 
1095
+ let detailPool = null;
1096
+ function sharedDetailPanel(m, opts) {
1097
+ const html = renderDetailPanel(m, opts);
1098
+ if (!detailPool) return html;
1099
+ const existing = detailPool.get(html);
1100
+ if (existing) return `<div data-detail-ref="${existing}"><a href="#${existing}">${esc(m.cve.id)}</a></div>`;
1101
+ const id = `shared-cve-detail-${detailPool.size + 1}`;
1102
+ detailPool.set(html, id);
1103
+ return `<div id="${id}">${html}</div>`;
1104
+ }
1105
+
1095
1106
  function renderCveRow(m, opts = {}) {
1096
1107
  const { withAction } = opts;
1097
1108
  const advisoryId = String(m.cve.id || "");
@@ -1122,7 +1133,7 @@ function renderCveRow(m, opts = {}) {
1122
1133
  <td>${source}</td>
1123
1134
  ${actionCell}
1124
1135
  </tr>
1125
- <tr class="detail-row"><td colspan="${colspan}">${renderDetailPanel(m, opts)}</td></tr>`;
1136
+ <tr class="detail-row"><td colspan="${colspan}">${sharedDetailPanel(m, opts)}</td></tr>`;
1126
1137
  }
1127
1138
 
1128
1139
  function renderActionCell(m) {
@@ -2010,6 +2021,7 @@ function numberedSubsections(chapter, entries) {
2010
2021
  }
2011
2022
 
2012
2023
  const WARNING_HEADINGS = {
2024
+ "image-unpinned": { icon: "⚠️", title: "Image references without a digest" },
2013
2025
  "cve-enrichment-summary": { icon: "ℹ️", title: "CVE records" },
2014
2026
  "image-scan-failed": { icon: "⚠️", title: "Image analysis blocked" },
2015
2027
  "image-source-unavailable": { icon: "⚠️", title: "Unavailable from public sources" },
@@ -2345,6 +2357,7 @@ function renderExecutiveSummary({ projectInfo, prodStats, devStats, retireStats,
2345
2357
  }
2346
2358
 
2347
2359
  function warningMessage(w) {
2360
+ if (w.type === "image-unpinned") return esc(t(require('./image-references').UNPINNED_IMAGE_MESSAGE));
2348
2361
  if (w.type === "image-source-unavailable") return esc(t("Some images or their advisory data are unavailable from public sources. See the affected images and reasons below."));
2349
2362
  if (w.type === "cve-enrichment-summary") return esc(require('./cve-record-coverage').formatCveRecordWarning(w, RENDER_CTX.locale));
2350
2363
  if (w.type === "commercial-build") {
@@ -3507,10 +3520,20 @@ function browserI18nScript() {
3507
3520
  function generateHtmlReport(payload) {
3508
3521
  // The body is built FIRST: buildBody is what declares the report's language, and the
3509
3522
  // <title> and the lang attribute both need it to be set already.
3510
- const body = injectColgroups(buildBody(payload));
3523
+ let body;
3524
+ // Share only byte-identical panels: applicability, paths, fixes and image
3525
+ // identity must all agree. The browser restores them before copy/print hooks.
3526
+ detailPool = new Map();
3527
+ try { body = injectColgroups(buildBody(payload)); }
3528
+ finally { detailPool = null; }
3511
3529
  return `<!doctype html>
3512
3530
  <html lang="${esc(RENDER_CTX.locale)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${t("VigieVuln Report")}</title><style>${CSS}</style></head>
3513
- <body>${body}${browserI18nScript()}${TOGGLE_SCRIPT}${COPY_SCRIPT}${CHART_COPY_SCRIPT}<script>
3531
+ <body>${body}<script>
3532
+ document.querySelectorAll('[data-detail-ref]').forEach(function(panel) {
3533
+ var source = document.getElementById(panel.getAttribute('data-detail-ref'));
3534
+ if (source) panel.innerHTML = source.innerHTML;
3535
+ });
3536
+ </script>${browserI18nScript()}${TOGGLE_SCRIPT}${COPY_SCRIPT}${CHART_COPY_SCRIPT}<script>
3514
3537
  (${localizeReportTimes.toString()})();
3515
3538
  </script></body></html>`;
3516
3539
  }
package/lib/i18n.js CHANGED
@@ -466,6 +466,8 @@ const fr = {
466
466
  "Scanned dependency descriptors": "Descripteurs de dépendances analysés",
467
467
  "Ignored directories": "Répertoires ignorés",
468
468
  "Methodology, data sources & limitations": "Méthodologie, sources de données et limites",
469
+ "Image references without a digest": "Références d’images sans digest",
470
+ "Image references without a digest use mutable tags, including version tags and implicit latest. Their content can change between the scan, build and deployment. Pin each reference with @sha256:<digest>; the digest observed during a scan does not pin the declaration.": "Les références d’images sans digest utilisent des tags modifiables, y compris les tags de version et latest implicite. Leur contenu peut changer entre le scan, la construction et le déploiement. Fixez chaque référence avec @sha256:<digest> ; le digest observé pendant un scan ne fixe pas la déclaration.",
469
471
  "Image analysis blocked": "Analyse d’image bloquée",
470
472
  "Warnings & scan-completeness": "Avertissements et complétude du scan",
471
473
  "Cached source data used; dates indicate the saved response and may need refreshing.": "Données de sources en cache utilisées ; les dates indiquent les réponses conservées, qui peuvent nécessiter une actualisation.",
@@ -200,4 +200,24 @@ function referenceWarnings(references) {
200
200
  (reference.role === 'base' ? ' A Dockerfile base is not evidence of the final built image.' : '') }));
201
201
  }
202
202
 
203
- module.exports = { discoverImageReferences, referenceWarnings, bindImageDefinitions, dockerfileReferences, yamlReferences, resolveVariables, classifyImageReference, DEFAULT_EXTRACTORS };
203
+ // Pinning is a property of the declaration, never of the digest resolved during
204
+ // a scan. Even numeric version tags can be reassigned by a registry publisher.
205
+ const UNPINNED_IMAGE_MESSAGE='Image references without a digest use mutable tags, including version tags and implicit latest. Their content can change between the scan, build and deployment. Pin each reference with @sha256:<digest>; the digest observed during a scan does not pin the declaration.';
206
+ function unpinnedImageWarnings(references=[]) {
207
+ const items=[],seen=new Set();
208
+ for(const ref of references){
209
+ if(ref.localBuild || ref.classification==='local-build' || !ref.reference)continue;
210
+ // Invalid or unresolved references cannot establish whether a pin is valid.
211
+ let parsed;try{parsed=require('./image-registry').parseReference(ref.reference);}catch{continue;}
212
+ if(parsed.reference.includes(':'))continue;
213
+ const key=JSON.stringify([ref.reference,ref.path,ref.line,ref.location]);if(seen.has(key))continue;seen.add(key);
214
+ const location=ref.path ? `${ref.path}${ref.line?':'+ref.line:''}${ref.location?' ('+ref.location+')':''}` : null;
215
+ items.push({id:ref.reference,reference:ref.reference,declared:ref.declared||ref.reference,
216
+ ...(ref.path?{manifestPaths:[ref.path]}:{}),...(ref.line?{line:ref.line}:{}),...(ref.location?{location:ref.location}:{}),
217
+ ...(location?{detail:location}:{})});
218
+ }
219
+ return items.length ? [{type:'image-unpinned',reason:'mutable-image-reference',severity:'warning',affectsCompleteness:false,
220
+ count:items.length,items,message:UNPINNED_IMAGE_MESSAGE,_groupedDiagnostics:true}] : [];
221
+ }
222
+
223
+ module.exports = { unpinnedImageWarnings, UNPINNED_IMAGE_MESSAGE, discoverImageReferences, referenceWarnings, bindImageDefinitions, dockerfileReferences, yamlReferences, resolveVariables, classifyImageReference, DEFAULT_EXTRACTORS };
@@ -86,7 +86,7 @@ function depBrief(dep) {
86
86
  installEvidence: dep.installEvidence || null,
87
87
  sbomEvidence: dep.sbomEvidence || null,
88
88
  artifactTargetId: dep.artifactTargetId || null,
89
- ...(dep.artifactTargetId ? {imageRole:dep.imageRole || null} : {}),
89
+ ...(dep.artifactTargetId ? {imageProduct:require('./artifacts/image-products').describe(dep),imageRole:dep.imageRole || null,imageSource:require('./artifacts/component-scope').imageComponentSource(dep)} : {}),
90
90
  artifactPath: dep.artifactPath || null,
91
91
  packageType: dep.packageType || null,
92
92
  manager: dep.manager || null,
@@ -290,7 +290,7 @@ function buildFindings(payload = {}) {
290
290
 
291
291
  function writeFindings(payload, outputPath) {
292
292
  const doc = buildFindings(payload);
293
- fs.writeFileSync(outputPath, JSON.stringify(doc, null, 2) + "\n");
293
+ fs.writeFileSync(outputPath, JSON.stringify(doc) + "\n");
294
294
  return doc;
295
295
  }
296
296