diff --git a/CHANGELOG.md b/CHANGELOG.md index c036999..a967082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ version tag (`v1.2.3`) is pushed. ## [Unreleased] ### Added +- **Direct and transitive dependencies, and through which package.** `SbomFilterExtractor.ps1` names for a transitive + component the direct dependencies it comes in through (`Via`, from the dependency graph), and lockfiles with a graph + give direct / transitive too (`package-lock.json` v2 / v3, `pnpm-lock.yaml`, `packages.lock.json`, `Gemfile.lock`, + `Cargo.lock`, `uv.lock`). `metascraper.ps1` (build 2026-12-04a) writes `DependencyScope` and `Via` per entry. Shown + in the Results tab (column *Dep.*, tooltip, details, CSV, search `is:direct`, `is:transitive`, `via:`), the + Workbench, the attack paths, the Auto Report, the SBOM comparison and the inventory window (column *Via*); the Heavy + mode scan takes it from the inventory. Script test `tests/dependency-graph.ps1`, smoke area `dependency`. - **Attack paths: components per arrow.** An arrow with more than one finding names, in a second, smaller line, how many components the findings are in (*5 entries* / *in 3 components*) - in the GUI graph and the report graph. The *Long list* next to the graph is 25 % wider (475 instead of 380 pixels). The STRIDE categories of a finding are diff --git a/Compare-Sbom.ps1 b/Compare-Sbom.ps1 index 3041e13..44d958c 100644 --- a/Compare-Sbom.ps1 +++ b/Compare-Sbom.ps1 @@ -209,6 +209,8 @@ foreach ($k in $keys) { OldComponent = $co; NewComponent = $cn; OldTriage = $(if ($ro) { $to } else { $null }); NewTriage = $(if ($rn) { $tn } else { $null }) OldVersionStatus = $(if ($o) { "$($o.VersionStatus)" } else { '' }); NewVersionStatus = $(if ($n) { "$($n.VersionStatus)" } else { '' }) Why = ($why -join '; ') + # Direct or transitive dependency (metascraper.ps1 2026-12-04a) on the side that counts: the new one, else the old. + Dependency = $(if ("$($e.DependencyScope)" -eq 'transitive') { 'transitive' + $(if ($e.Via) { " via $($e.Via)" }) } else { "$($e.DependencyScope)" }) }) } $order = @{ new = 0; changed = 1; resolved = 2; unchanged = 3 } @@ -226,8 +228,8 @@ $result = [pscustomobject]@{ } $utf8 = New-Object System.Text.UTF8Encoding($false) [IO.File]::WriteAllText((Join-Path $OutDir 'sbom_compare.json'), ($result | ConvertTo-Json -Depth 6), $utf8) -$csvRows = @($sorted | Where-Object { $IncludeUnchanged -or $_.Change -ne 'unchanged' } | Select-Object Change, Id, Cve, Severity, Exploited, OldComponent, NewComponent, OldTriage, NewTriage, OldVersionStatus, NewVersionStatus, Why) -$csv = if ($csvRows.Count) { $csvRows | ConvertTo-Csv -NoTypeInformation } else { '"Change","Id","Cve","Severity","Exploited","OldComponent","NewComponent","OldTriage","NewTriage","OldVersionStatus","NewVersionStatus","Why"' } +$csvRows = @($sorted | Where-Object { $IncludeUnchanged -or $_.Change -ne 'unchanged' } | Select-Object Change, Id, Cve, Severity, Exploited, OldComponent, NewComponent, OldTriage, NewTriage, OldVersionStatus, NewVersionStatus, Dependency, Why) +$csv = if ($csvRows.Count) { $csvRows | ConvertTo-Csv -NoTypeInformation } else { '"Change","Id","Cve","Severity","Exploited","OldComponent","NewComponent","OldTriage","NewTriage","OldVersionStatus","NewVersionStatus","Dependency","Why"' } [IO.File]::WriteAllText((Join-Path $OutDir 'sbom_compare.csv'), (($csv -join "`r`n") + "`r`n"), $utf8) # --------------------------------------------------------------------------------------------------------------- @@ -267,6 +269,7 @@ foreach ($g in $groups) { $id = if ($r.Url) { "$(HtmlText $r.Id)" } else { HtmlText $r.Id } $oldC = if ($r.OldComponent) { HtmlText $r.OldComponent } else { '—' } $newC = if ($r.NewComponent) { HtmlText $r.NewComponent } else { 'removed' } + if ($r.Dependency -like 'transitive*') { $newC += "
$(HtmlText $r.Dependency)" } [void]$sb.Append("$($r.Change)$id$(if ($r.Exploited) { ' KEV' })$(HtmlText $r.Severity)$oldC→$newC$(Format-Triage $r.OldTriage)→$(Format-Triage $r.NewTriage)$(HtmlText $r.Why)") } [void]$sb.Append('') diff --git a/README.md b/README.md index 2212f4e..5cbab54 100644 --- a/README.md +++ b/README.md @@ -784,6 +784,24 @@ from the dependency graph) get **-5**, `scope: optional` components **-10** on t the reason says *"(transitive dependency -5)"*. OSV confirmations (100) and VEX are not changed. Without a dependency graph nothing is deducted. +**Direct or transitive - and through which package** (script build 2026-12-04a): each entry carries +`DependencyScope` - *direct* when one matched component is a direct dependency of the main component, *transitive* +when every matched component with a known scope is transitive - and, for a transitive one, `Via`: the direct +dependencies it comes in through (`express@4.17.1; lodash@4.17.20`). The fix is mostly an update of that direct +dependency. Where it shows: + +| Where | What | +|---|---| +| Results | column **Dep.** (*direct* / *transitive*, the tooltip names the way in), the line *Dependency* in the details, CSV columns `DependencyScope` and `Via`; search `is:direct`, `is:transitive`, `via:express`, `dep:transitive` | +| Workbench | *Dependency* in the details and the CSV; a change is noted like other changes | +| Attack paths | a transitive finding shows *transitive via ...* in the lists (GUI and report) | +| Auto Report | *transitive via ...* in the column Fix | +| SBOM comparison | column *Dependency* (window, CSV, HTML) | +| Inventory window | column *Via* (read-only) next to *Direct* | + +The graph comes from the SBOM (CycloneDX `dependencies`, SPDX `DEPENDS_ON` / `DEPENDENCY_OF`) or from a lockfile that +has one (see the lockfiles in 2.3). Without a graph the column stays empty. + **Shadow comparison ("what do the stricter rules suppress?"):** for every entry the script also computes the applicability it would get without the suppressing rules (ignored generic keywords, generic product names, umbrella vendors, dependency scope, structured "not affected", VEX). If that is higher, the entry carries @@ -1670,7 +1688,10 @@ a project (direct and indirect): `package-lock.json` / `npm-shrinkwrap.json`, `y `poetry.lock`, `uv.lock`, `Pipfile.lock`, `requirements*.txt` (pinned `==` only), `composer.lock`, `go.sum`, `Cargo.lock`, `Gemfile.lock`, `packages.lock.json` (.NET), `gradle.lockfile`. Each package becomes a component with a purl (exact OSV / GHSA matching); development-only packages count as scope *excluded* (`-IncludeExcluded` keeps -them). A lockfile covers the libraries of one project only - operating system and server software (PostgreSQL, +them). Direct or transitive, and the way in (`Via`), come from the lockfiles that record the dependency graph: +`package-lock.json` v2 / v3, `pnpm-lock.yaml`, `packages.lock.json`, `Gemfile.lock`, `Cargo.lock`, `uv.lock`. The +others (`yarn.lock`, `poetry.lock`, `Pipfile.lock`, `requirements*.txt`, `composer.lock`, `go.sum`, `gradle.lockfile`) +do not say which packages the project uses itself: there it stays unknown. A lockfile covers the libraries of one project only - operating system and server software (PostgreSQL, OpenSSL ...) still need an SBOM or Dependency-Track. ```powershell diff --git a/SbomFilterExtractor.ps1 b/SbomFilterExtractor.ps1 index bdbbccd..56a7940 100644 --- a/SbomFilterExtractor.ps1 +++ b/SbomFilterExtractor.ps1 @@ -372,16 +372,37 @@ function ConvertFrom-Lockfile($file) { $lines = $text -split "`r?`n" $list = New-Object System.Collections.Generic.List[object] $add = { param($c) if ($c) { $list.Add($c) } } + $addR = { param($c) if ($c) { $list.Add($c) }; $c } # the same, returns the component + # The dependency graph where the lockfile has one (asked 2026-12-04): the project's own (direct) dependencies and + # which package needs which - as purls; the result gets a main component and CycloneDX dependencies, so direct / + # transitive and Via come out as for an SBOM. + $rootDeps = New-Object System.Collections.Generic.List[string] + $edges = @{} + $edge = { param($from, $to) if (-not $from -or -not $to -or $from -eq $to) { return }; if (-not $edges.ContainsKey($from)) { $edges[$from] = New-Object System.Collections.Generic.List[string] }; if (-not $edges[$from].Contains($to)) { $edges[$from].Add($to) } } + $direct = { param($p) if ($p -and -not $rootDeps.Contains($p)) { $rootDeps.Add($p) } } switch -Regex ($name) { '^(package-lock|npm-shrinkwrap)\.json$' { # The root package has the key "" - ConvertFrom-Json does not accept an empty property name. $j = ($text -replace '([{,]\s*)""\s*:', '$1"__root__":') | ConvertFrom-Json if ($j.PSObject.Properties['packages']) { + $byPath = @{} foreach ($p in $j.packages.PSObject.Properties) { if (-not $p.Name -or $p.Name -notmatch 'node_modules/') { continue } $n = ($p.Name -split 'node_modules/')[-1] $s = Split-NpmName $n - & $add (New-LockComponent 'npm' $s[0] $s[1] "$($p.Value.version)" ([bool]$p.Value.dev)) + $c = & $addR (New-LockComponent 'npm' $s[0] $s[1] "$($p.Value.version)" ([bool]$p.Value.dev)) + if ($c) { $byPath[$p.Name] = $c.purl } + } + # A dependency of the package at path P: P/node_modules/name, else the same one level up (npm's lookup). + $resolve = { param($path, $dep) $base = $path; while ($true) { $cand = if ($base) { "$base/node_modules/$dep" } else { "node_modules/$dep" }; if ($byPath.ContainsKey($cand)) { return $byPath[$cand] }; if (-not $base) { return $null }; $i = $base.LastIndexOf('/node_modules/'); $base = if ($i -ge 0) { $base.Substring(0, $i) } else { '' } } } + $depNames = { param($v) foreach ($sec in 'dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies') { if ($v.PSObject.Properties[$sec] -and $v.$sec) { $v.$sec.PSObject.Properties.Name } } } + foreach ($p in $j.packages.PSObject.Properties) { + $isRoot = $p.Name -eq '__root__' + if (-not $isRoot -and -not $byPath.ContainsKey($p.Name)) { continue } + foreach ($dn in @(& $depNames $p.Value)) { + $to = & $resolve $(if ($isRoot) { '' } else { $p.Name }) $dn + if ($isRoot) { & $direct $to } else { & $edge $byPath[$p.Name] $to } + } } } elseif ($j.PSObject.Properties['dependencies']) { $walk = { param($deps) foreach ($p in $deps.PSObject.Properties) { $s = Split-NpmName $p.Name; & $add (New-LockComponent 'npm' $s[0] $s[1] "$($p.Value.version)" ([bool]$p.Value.dev)); if ($p.Value.dependencies) { & $walk $p.Value.dependencies } } } @@ -402,14 +423,67 @@ function ConvertFrom-Lockfile($file) { if ($l -match '^\S') { $inPkgs = $false; continue } if ($inPkgs -and $l -match "^\s{2}['""]?/?(@?[^@\s'""/]+(?:/[^@\s'""]+)?)@([^()'"":\s]+)") { $s = Split-NpmName $Matches[1]; & $add (New-LockComponent 'npm' $s[0] $s[1] $Matches[2]) } } + # The graph: the project's dependencies (importers "." in v6 / v9, top-level dependencies in v5) and the + # dependencies of each package (snapshots in v9, packages before) - "name: version" with peer suffixes. + $pnpmPurl = { param($n, $v) $v = ("$v" -replace '\(.*$', '' -replace "['""]", '').Trim(); if ($v -match '^(link|file|workspace):') { return $null }; $s = Split-NpmName $n; $c = New-LockComponent 'npm' $s[0] $s[1] $v; if ($c) { $c.purl } } + $sec = ''; $importer = ''; $pkg = $null; $depBlock = $false; $depName = $null + foreach ($l in $lines) { + if ($l -match '^(\S[^:]*):\s*$') { $sec = $Matches[1]; $importer = ''; $pkg = $null; $depBlock = $false; continue } + if ($sec -eq 'importers') { + if ($l -match "^ {2}(?! )['""]?([^'"":\s]+)['""]?:\s*$") { $importer = $Matches[1]; $depBlock = $false; continue } + if ($importer -eq '.' -and $l -match '^ {4}(?! )(dependencies|optionalDependencies|devDependencies):\s*$') { $depBlock = $true; continue } + if ($importer -eq '.' -and $l -match '^ {4}(?! )\S') { $depBlock = $false; continue } + if ($importer -eq '.' -and $depBlock -and $l -match "^ {6}(?! )['""]?([^'"":\s]+)['""]?:\s*$") { $depName = $Matches[1]; continue } + if ($importer -eq '.' -and $depBlock -and $depName -and $l -match '^ {8}(?! )version:\s*(\S+)') { & $direct (& $pnpmPurl $depName $Matches[1]); $depName = $null } + continue + } + if ($sec -in 'dependencies', 'optionalDependencies', 'devDependencies') { + # v5: " name: 1.2.3" or " name:" + " version: 1.2.3" + if ($l -match "^ {2}(?! )['""]?([^'"":\s]+)['""]?:\s*(\S+)\s*$") { & $direct (& $pnpmPurl $Matches[1] $Matches[2]) } + elseif ($l -match "^ {2}(?! )['""]?([^'"":\s]+)['""]?:\s*$") { $depName = $Matches[1] } + elseif ($depName -and $l -match '^ {4}(?! )version:\s*(\S+)') { & $direct (& $pnpmPurl $depName $Matches[1]); $depName = $null } + continue + } + if ($sec -in 'packages', 'snapshots') { + if ($l -match "^ {2}(?! )['""]?/?(@?[^@\s'""/]+(?:/[^@\s'""]+)?)@([^'"":\s]+)['""]?:\s*$") { $pkg = & $pnpmPurl $Matches[1] $Matches[2]; $depBlock = $false; continue } + if ($pkg -and $l -match '^ {4}(?! )(dependencies|optionalDependencies):\s*$') { $depBlock = $true; continue } + if ($pkg -and $l -match '^ {4}(?! )\S') { $depBlock = $false; continue } + if ($pkg -and $depBlock -and $l -match "^ {6}(?! )['""]?([^'"":\s]+)['""]?:\s*['""]?([^'""\s]+)") { & $edge $pkg (& $pnpmPurl $Matches[1] $Matches[2]) } + } + } } '^(poetry|uv)\.lock$|^Cargo\.lock$' { $type = if ($name -eq 'Cargo.lock') { 'cargo' } else { 'pypi' } $n = $null; $v = $null + # The graph (Cargo.lock, uv.lock): a package without registry source is the project itself (Cargo: no + # "source" line; uv: source virtual / editable "."); its dependencies are the direct ones. Poetry has no + # project entry: no graph. + $norm = { param($x) if ($type -eq 'pypi') { "$x".ToLower() -replace '[_.]', '-' } else { "$x" } } + $pkgs = New-Object System.Collections.Generic.List[object] + $cur = $null; $sub = $null; $inDeps = $false foreach ($l in @($lines) + '[[package]]') { - if ($l -match '^\[\[package\]\]') { if ($n -and $v) { & $add (New-LockComponent $type $null $(if ($type -eq 'pypi') { $n.ToLower() -replace '[_.]', '-' } else { $n }) $v) }; $n = $null; $v = $null; continue } + if ($l -match '^\[\[package\]\]') { + if ($n -and $v) { $c = & $addR (New-LockComponent $type $null (& $norm $n) $v); if ($c -and $cur) { $cur.Purl = $c.purl; $cur.Name = (& $norm $n); $cur.Version = $v; $pkgs.Add($cur) } } + $n = $null; $v = $null; $cur = [pscustomobject]@{ Purl = $null; Name = $null; Version = $null; Root = ($type -eq 'cargo'); Deps = (New-Object System.Collections.Generic.List[string]) }; $sub = $null; $inDeps = $false; continue + } + if ($l -match '^\[') { $sub = $l; $inDeps = $false; continue } + if ($sub) { continue } if ($l -match '^name\s*=\s*"([^"]+)"') { $n = $Matches[1] } elseif ($l -match '^version\s*=\s*"([^"]+)"') { $v = $Matches[1] } + elseif ($l -match '^source\s*=\s*(.*)$' -and $cur) { $cur.Root = ($Matches[1] -match '(virtual|editable)\s*=\s*"\."') } + elseif ($l -match '^dependencies\s*=\s*\[(.*)$' -and $cur) { $inDeps = $Matches[1] -notmatch '\]\s*$'; foreach ($m in [regex]::Matches($Matches[1], '(?:name\s*=\s*)?"([^"]+)"')) { $cur.Deps.Add($m.Groups[1].Value) } } + elseif ($inDeps -and $cur) { if ($l -match '^\s*\]') { $inDeps = $false } else { $m = [regex]::Match($l, '(?:name\s*=\s*)?"([^"]+)"'); if ($m.Success) { $cur.Deps.Add($m.Groups[1].Value) } } } + } + if ($type -eq 'pypi' -and -not @($pkgs | Where-Object Root).Count) { $pkgs.Clear() } + foreach ($pk in $pkgs) { + if ($pk.Root) { & $direct $pk.Purl } + foreach ($d in $pk.Deps) { + $parts = $d -split '\s+'; $dn = & $norm $parts[0] + $cands = @($pkgs | Where-Object { $_.Name -eq $dn }) + if ($parts.Count -gt 1) { $cands = @($cands | Where-Object { $_.Version -eq $parts[1] }) } + if ($cands.Count -ne 1) { continue } + if ($pk.Root) { & $direct $cands[0].Purl } else { & $edge $pk.Purl $cands[0].Purl } + } } } '^Pipfile\.lock$' { @@ -440,16 +514,31 @@ function ConvertFrom-Lockfile($file) { } } '^Gemfile\.lock$' { - $inSpecs = $false + # The graph: the dependency lines under a spec (6 spaces) and the section DEPENDENCIES (the Gemfile's own). + $inSpecs = $false; $inDeps = $false; $gem = $null; $gemPurl = @{}; $gemEdges = New-Object System.Collections.Generic.List[object]; $gemDirect = New-Object System.Collections.Generic.List[string] foreach ($l in $lines) { if ($l -match '^\s{2}specs:\s*$') { $inSpecs = $true; continue } - if ($l -match '^\S') { $inSpecs = $false; continue } - if ($inSpecs -and $l -match '^\s{4}([A-Za-z0-9._-]+) \(([^)\s-]+)(-[^)]*)?\)\s*$') { & $add (New-LockComponent 'gem' $null $Matches[1] $Matches[2]) } + if ($l -match '^DEPENDENCIES\s*$') { $inDeps = $true; $inSpecs = $false; continue } + if ($l -match '^\S') { $inSpecs = $false; $inDeps = $false; continue } + if ($inSpecs -and $l -match '^\s{4}([A-Za-z0-9._-]+) \(([^)\s-]+)(-[^)]*)?\)\s*$') { $gem = $Matches[1]; $c = & $addR (New-LockComponent 'gem' $null $Matches[1] $Matches[2]); if ($c) { $gemPurl[$gem] = $c.purl } } + elseif ($inSpecs -and $gem -and $l -match '^\s{6}([A-Za-z0-9._-]+)') { $gemEdges.Add(@($gem, $Matches[1])) } + elseif ($inDeps -and $l -match '^\s{2}([A-Za-z0-9._-]+)') { $gemDirect.Add($Matches[1]) } } + foreach ($g in $gemDirect) { & $direct $gemPurl[$g] } + foreach ($e in $gemEdges) { & $edge $gemPurl[$e[0]] $gemPurl[$e[1]] } } '^packages\.lock\.json$' { $j = $text | ConvertFrom-Json - foreach ($tfm in $j.dependencies.PSObject.Properties) { foreach ($p in $tfm.Value.PSObject.Properties) { if ($p.Value.resolved) { & $add (New-LockComponent 'nuget' $null $p.Name "$($p.Value.resolved)") } } } + # "type": Direct / Transitive / Project, and the dependencies of each package (the graph). + foreach ($tfm in $j.dependencies.PSObject.Properties) { + $nuPurl = @{} + foreach ($p in $tfm.Value.PSObject.Properties) { if ($p.Value.resolved) { $c = & $addR (New-LockComponent 'nuget' $null $p.Name "$($p.Value.resolved)"); if ($c) { $nuPurl[$p.Name.ToLower()] = $c.purl } } } + foreach ($p in $tfm.Value.PSObject.Properties) { + $from = $nuPurl[$p.Name.ToLower()] + if ("$($p.Value.type)" -eq 'Direct') { & $direct $from } + if ($p.Value.PSObject.Properties['dependencies'] -and $p.Value.dependencies) { foreach ($dn in $p.Value.dependencies.PSObject.Properties.Name) { & $edge $from $nuPurl[$dn.ToLower()] } } + } + } } '^gradle\.lockfile$' { foreach ($l in $lines) { @@ -463,7 +552,13 @@ function ConvertFrom-Lockfile($file) { } # The same package once (a lockfile can list it for several paths). $seen = @{}; $unique = foreach ($c in $list) { if (-not $seen.ContainsKey($c.purl)) { $seen[$c.purl] = $true; $c } } - [pscustomobject]@{ bomFormat = 'CycloneDX'; specVersion = 'lockfile'; metadata = $null; components = @($unique); dependencies = $null } + $meta = $null; $deps = $null + if ($rootDeps.Count) { + $rootRef = "lockfile:$name" + $meta = [pscustomobject]@{ component = [pscustomobject]@{ type = 'application'; name = $name; 'bom-ref' = $rootRef } } + $deps = @([pscustomobject]@{ ref = $rootRef; dependsOn = [string[]]$rootDeps }) + @(foreach ($k in $edges.Keys) { [pscustomobject]@{ ref = $k; dependsOn = [string[]]$edges[$k] } }) + } + [pscustomobject]@{ bomFormat = 'CycloneDX'; specVersion = 'lockfile'; metadata = $meta; components = @($unique); dependencies = $deps } } # Reads a CycloneDX document (JSON or XML) from a file; $null with a warning when it is not usable. Lockfiles are @@ -732,6 +827,7 @@ $rows = New-Object System.Collections.Generic.List[object] $vexList = New-Object System.Collections.Generic.List[object] $serviceList = New-Object System.Collections.Generic.List[object] $rootRefs = New-Object 'System.Collections.Generic.HashSet[string]' +$refNames = @{} # Collects the VEX statements of one CycloneDX document; affects[].ref may be a BOM-Link (urn:cdx:...#ref). function Add-VexStatements($bom, [string]$sbomName, [string]$rootRef) { foreach ($v in @($bom.vulnerabilities)) { @@ -797,9 +893,30 @@ foreach ($file in $files) { if ($entry) { $direct = @($entry.dependsOn) } } if ($DirectOnly -and $null -eq $direct) { Write-Warning "$($file.Name): no dependency graph for the main component - using all components." } + # Through which direct dependency a transitive one comes in (asked 2026-12-04: the fix is mostly an update of the + # direct one): every component reachable from a direct dependency in the graph notes that direct dependency. + $viaRefs = @{} + if ($null -ne $direct -and -not $DirectOnly) { + $depMap = @{} + foreach ($d in @($bom.dependencies)) { if ($d -and $d.ref) { $depMap["$($d.ref)"] = @($d.dependsOn | Where-Object { $_ } | ForEach-Object { "$_" }) } } + foreach ($dr in @($direct | Where-Object { $_ } | ForEach-Object { "$_" })) { + $seenVia = New-Object 'System.Collections.Generic.HashSet[string]' + $queue = New-Object 'System.Collections.Generic.Queue[string]' + foreach ($x in @($depMap[$dr])) { $queue.Enqueue($x) } + while ($queue.Count) { + $vr = $queue.Dequeue() + if ($vr -eq $dr -or -not $seenVia.Add($vr)) { continue } + if (-not $viaRefs.ContainsKey($vr)) { $viaRefs[$vr] = New-Object System.Collections.Generic.List[string] } + if (-not $viaRefs[$vr].Contains($dr)) { $viaRefs[$vr].Add($dr) } + foreach ($x in @($depMap[$vr])) { if (-not $seenVia.Contains($x)) { $queue.Enqueue($x) } } + } + } + } $components = @(Get-AllComponents $bom.components) if ($IncludeRoot -and $root) { $components = @($root) + $components } + # name@version per bom-ref: the name of a direct dependency that is not in the inventory itself (Via). + foreach ($c in $components) { if ($c.'bom-ref') { $refNames["$($file.Name)|$($c.'bom-ref')"] = "$($c.name)" + $(if ($c.version) { "@$($c.version)" } else { '' }) } } foreach ($c in $components) { if ($skipTypes -contains $c.type) { continue } @@ -887,6 +1004,7 @@ foreach ($file in $files) { Type = $c.type Scope = $c.scope Direct = $isDirect + ViaRefs = [string[]]$(if ($isDirect -eq $false -and $viaRefs.ContainsKey("$ref")) { $viaRefs["$ref"] } else { @() }) Purl = $c.purl Cpe = $c.cpe Sbom = $file.Name @@ -992,6 +1110,7 @@ $seenInv = New-Object 'System.Collections.Generic.HashSet[string]' ([StringCompa # Inventory label per de-duplication key and per SBOM bom-ref (for the VEX file). The label is built # exactly like in metascraper.ps1 (Import-Inventory): vendor/product@version. $labelByKey = @{}; $labelByRef = @{}; $invByKey = @{} +$viaPending = New-Object System.Collections.Generic.List[object] # For VEX documents (no SBOM context): bom-ref in any SBOM, and purl. $labelsByAnyRef = @{}; $labelsByPurl = @{} $addLabel = { param($table, $k, $label) if (-not $k) { return }; $k = "$k".ToLower(); if (-not $table.ContainsKey($k)) { $table[$k] = New-Object System.Collections.Generic.List[string] }; if (-not $table[$k].Contains($label)) { $table[$k].Add($label) } } @@ -1026,6 +1145,7 @@ foreach ($r in $rows) { $prevInv = $invByKey[$key] if ($prevInv) { if ($r.Direct -eq $true -or ($null -eq $prevInv.Direct -and $null -ne $r.Direct)) { $prevInv.Direct = $r.Direct } + if (@($r.ViaRefs).Count) { $viaPending.Add(@($prevInv, $r.Sbom, $r.ViaRefs)) } if ("$($r.Scope)" -ne 'optional') { $prevInv.Scope = 'required' } $prevInv.Repos = [string[]]@(@($prevInv.Repos) + @($r.Repos) | Where-Object { $_ } | Select-Object -Unique) $prevInv.Backports = [string[]]@(@($prevInv.Backports) + @($r.Backports) | Where-Object { $_ } | Select-Object -Unique) @@ -1057,6 +1177,8 @@ foreach ($r in $rows) { CpeVendor = if ($r.CpeVendor) { "$($r.CpeVendor)".ToLower() } else { $null } CpeProduct = if ($r.CpeProduct) { "$($r.CpeProduct)".ToLower() } else { $null } Direct = $r.Direct + # A transitive component: the direct dependencies it comes in through (inventory labels, filled below). + Via = [string[]]@() # CycloneDX scope: required (default when absent) or optional; excluded components are skipped above. Scope = if ("$($r.Scope)" -eq 'optional') { 'optional' } else { 'required' } Sbom = $r.Sbom @@ -1068,6 +1190,7 @@ foreach ($r in $rows) { Backports = [string[]]@($r.Backports) }) $inv = $inventory[$inventory.Count - 1] + if (@($r.ViaRefs).Count) { $viaPending.Add(@($inv, $r.Sbom, $r.ViaRefs)) } $label = if ($inv.Vendor) { "$($inv.Vendor)/$($inv.Product)" } else { "$($inv.Product)" } if ($inv.Version) { $label += "@$($inv.Version)" } $labelByKey[$key] = $label @@ -1075,6 +1198,15 @@ foreach ($r in $rows) { if ($r.BomRef) { $labelByRef["$($r.Sbom)|$($r.BomRef)"] = $label; & $addLabel $labelsByAnyRef $r.BomRef $label } if ($r.Purl) { & $addLabel $labelsByPurl $r.Purl $label } } +# Via: the inventory labels of the direct dependencies a transitive component comes in through (name@version when the +# direct one is not in the inventory); none when the component is also a direct dependency somewhere. +foreach ($vp in $viaPending) { + $vinv = $vp[0] + if ($vinv.Direct -eq $true) { continue } + $labels = @(foreach ($vr in @($vp[2])) { $l = $labelByRef["$($vp[1])|$vr"]; if (-not $l) { $l = $refNames["$($vp[1])|$vr"] }; if ($l) { $l } }) + $vinv.Via = [string[]]@(@($vinv.Via) + $labels | Where-Object { $_ } | Select-Object -Unique) +} + # The services of the SBOMs on their components: role service (RoleSource services), login required when the service # says authenticated, the exposure of its endpoints (ExposureSource services) - the stricter of several services. A # service that names no inventory component (the application itself, an external API) is listed only. diff --git a/docs/schema/combined_vulnerabilities.schema.json b/docs/schema/combined_vulnerabilities.schema.json index 13118b5..fe897ad 100644 --- a/docs/schema/combined_vulnerabilities.schema.json +++ b/docs/schema/combined_vulnerabilities.schema.json @@ -673,6 +673,15 @@ "type": ["string", "null"], "description": "Why, e.g. 'isolated, AV:N: -25' or 'internal, AV:P: 0; physical access excluded, AV:P: -30'." }, + "DependencyScope": { + "type": ["string", "null"], + "enum": ["direct", "transitive", null], + "description": "Script build 2026-12-04a: direct when one matched component is a direct dependency of the SBOM's main component, transitive when every matched component with a known scope is transitive; absent when the inventory has no dependency graph." + }, + "Via": { + "type": ["string", "null"], + "description": "A transitive entry: the direct dependencies the affected component comes in through, as inventory labels separated by '; ' (e.g. 'express@4.17.1; lodash@4.17.20')." + }, "TriageScore": { "type": [ "number", diff --git a/gui/MetaScraper.Core/AutoReport.cs b/gui/MetaScraper.Core/AutoReport.cs index 954fc96..ce819b7 100644 --- a/gui/MetaScraper.Core/AutoReport.cs +++ b/gui/MetaScraper.Core/AutoReport.cs @@ -795,7 +795,7 @@ static void AttackPathSection(StringBuilder sb, Context ctx) sb.Append("
").Append(GraphSvg(g)).Append("
"); string Item(AttackPaths.Step s, string note = null) => $"
  • {H(s.Id)} {H(s.Component)}{(s.Row.Exploited ? " KEV" : s.Row.Poc ? " PoC" : "")}" - + (s.Uncertain ? " uncertain" : "") + (s.Stride.Length > 0 ? $"{H(AttackPaths.StrideNames(s.Stride))}" : "") + + (s.Uncertain ? " uncertain" : "") + (s.Row.IsTransitive ? $" {H(s.Row.DepShort)}" : "") + (s.Stride.Length > 0 ? $"{H(AttackPaths.StrideNames(s.Stride))}" : "") + (note != null ? $" {H(note)}" : "") + "
  • "; string List(IEnumerable xs, int n = 3, Func note = null) => ""; string Measure(params string[] keys) => string.Join(" ยท ", keys.Where(measures.Contains).Select(k => AttackPaths.KindOf(k) + ": " + AttackPaths.MeasureLabel(k))); @@ -1187,6 +1187,8 @@ static void Row(StringBuilder sb, Entry e) else if (string.IsNullOrEmpty(e.Fix) && r.VendorStatus == "affected") fixCell = $"no fix yet"; if (!string.IsNullOrEmpty(r.VendorWorkaround)) fixCell += $" workaround"; if (r.AnyEol) fixCell += $" EOL"; + // A transitive dependency: the direct one it comes in through - mostly the one to update. + if (r.IsTransitive) fixCell += (fixCell.Length > 0 ? "
    " : "") + $"{H(r.DepShort)}"; Td(sb, "Fix", fixCell, fixCell.Length == 0 ? "blank" : null); string chg = string.IsNullOrEmpty(r.ChangeStatus) ? "" : r.ChangeStatus.StartsWith("new", StringComparison.OrdinalIgnoreCase) ? "new" : "changed"; Td(sb, "Change", chg.Length > 0 ? $"{chg}" : "", chg.Length == 0 ? "blank" : null); diff --git a/gui/MetaScraper.Core/InventoryEditor.cs b/gui/MetaScraper.Core/InventoryEditor.cs index a6181a5..a68fe37 100644 --- a/gui/MetaScraper.Core/InventoryEditor.cs +++ b/gui/MetaScraper.Core/InventoryEditor.cs @@ -50,6 +50,8 @@ public sealed class Item : INotifyPropertyChanged public string AiSuggested { get => aiSuggested; set { aiSuggested = value ?? ""; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AiSuggested))); } } // Read-only context from the SBOM. public string Origin => Raw["Origin"]?.ToString() ?? ""; + // A transitive component: the direct dependencies it comes in through (SbomFilterExtractor, from the graph). + public string Via => Raw["Via"] is JsonArray a ? string.Join("; ", a.Select(v => v?.ToString()).Where(v => !string.IsNullOrEmpty(v))) : ""; public string Sbom => Raw["Sbom"] is JsonNode n ? n.ToString().Split('/', '\\').Last() : ""; // file name (Windows or Unix path) public string Label => LabelOf(Vendor?.Trim(), Product?.Trim(), CleanVersion(Version)); diff --git a/gui/MetaScraper.Core/InventoryScan.cs b/gui/MetaScraper.Core/InventoryScan.cs index a8252b2..c405947 100644 --- a/gui/MetaScraper.Core/InventoryScan.cs +++ b/gui/MetaScraper.Core/InventoryScan.cs @@ -71,6 +71,24 @@ public sealed class Result } // Components of sbom_inventory.json. + // Direct or transitive (asked 2026-12-04), as the script's Add-DependencyScope: direct when one matched component is a + // direct dependency, transitive when every known one is transitive, with the direct ones it comes in through (Via). + public static void ApplyDependencyScope(IEnumerable rows, IReadOnlyList items) + { + var byLabel = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var it in items ?? Array.Empty()) if (it.Direct is "yes" or "no") byLabel.TryAdd(it.Label, it); + if (byLabel.Count == 0) return; + foreach (var r in rows) + { + var known = (r.MatchedComponents ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(l => byLabel.TryGetValue(l, out var it) ? it : null).Where(x => x != null).ToList(); + if (known.Count == 0) continue; + if (known.Any(x => x.Direct == "yes")) { r.DependencyScope = "direct"; r.Via = ""; continue; } + r.DependencyScope = "transitive"; + r.Via = string.Join("; ", known.SelectMany(x => x.Via.Split("; ", StringSplitOptions.RemoveEmptyEntries)).Distinct(StringComparer.OrdinalIgnoreCase)); + } + } + public static List FromInventory(string inventoryPath) { var list = new List(); diff --git a/gui/MetaScraper.Core/Results.cs b/gui/MetaScraper.Core/Results.cs index 7c51ca7..556888f 100644 --- a/gui/MetaScraper.Core/Results.cs +++ b/gui/MetaScraper.Core/Results.cs @@ -62,6 +62,7 @@ public static VulnRow FromElement(JsonElement i) row.ComponentEol = V(i, "ComponentEol") is true; row.ComponentEolText = S(i, "ComponentEolText") ?? ""; row.VendorMatch = S(i, "VendorMatch") ?? ""; row.VendorMatchPct = V(i, "VendorMatchPct") is double vmp ? vmp : null; row.NetworkExposure = S(i, "NetworkExposure") ?? ""; row.ExposurePoints = V(i, "ExposurePoints") is double xp ? xp : 0; row.ExposureReason = S(i, "ExposureReason") ?? ""; + row.DependencyScope = S(i, "DependencyScope") ?? ""; row.Via = S(i, "Via") ?? ""; row.IsEolEntry = V(i, "EndOfLife") is true; row.EolStatus = S(i, "EolStatus") ?? ""; row.EolKind = S(i, "EolKind") ?? ""; row.EolFrom = S(i, "EolFrom") ?? ""; row.EolLatest = S(i, "EolLatest") ?? ""; row.EolPackages = V(i, "EolPackages") is double ep ? (int)ep : 0; if (row.IsEolEntry) row.SearchText += " end of life eol"; @@ -267,6 +268,7 @@ public static string DetailText(VulnRow r) + (r.PocSightings > 0 ? (r.Sighted ? "; " : "") + $"{r.PocSightings} PoC sighting(s) (information only, many come from bots listing GitHub repositories)" : "")); risk.Add(r.ImpactInfo); if (r.ExposureReason.Length > 0) risk.Add($"Network exposure: {r.ExposureReason} (triage risk {r.ExposurePoints.ToString("+0;-0;0", ci)})"); + if (r.DepText.Length > 0) risk.Add("Dependency: " + r.DepText); risk.Add($"Published: {pub}"); if (r.UpdateOnly) risk.Add($"Update: published {pub}, before the time window; updated {r.UpdatedText.Replace(" (update)", "")}"); if (!string.IsNullOrEmpty(r.ChangeStatus)) risk.Add("Change since last run: " + r.ChangeStatus); @@ -355,7 +357,7 @@ public static int Write(IEnumerable rows, string path, (string Project, var header = new[] { "Triage", "Change", "Severity", "Source", "ID", "CVE", "Published", "Updated", "PublishedUTC", "UpdatedUTC", "UpdateOnly", "Note", "CVSS", "ScoreStatus", "CVSSVersion", "CVSSVector", "CVSS4", "CVSS4Vector", "EPSS", "EPSSUnit", "EPSSSource", "EPSSPercentile", "KnownExploited", "PoC", "CWE", "Impact", "PreAuth", "Vendor", "Product", "Relevance", "Matched", "Applicability", "Components", "VersionStatus", "ApplicabilityReason", "SuppressedHits", "ShadowApplicability", "Versions", "VersionsSource", "GitRanges", "URL", "Description", - "AI", "AIComponent", "AIConfidence", "AIReason", "AIModel", "AIChecked", "Sources", "Conflicts", "MaxCVSS", "MaxCVSSSource", "CoherentApplicability", "VersionHint", "Exposure", "ExposureConditions", "NetworkExposure", "ExposurePoints", "ExposureReason", "Fix", "FixInfo", "Sighted", "SightingKind", "SightingDays", "SightingLast", "SightingSources", "PocSightings", "LateOsv", "VendorStatus", "VendorFix", "VendorAdvisory", "VendorWorkaround", "ComponentEol", "ComponentEolText", "EndOfLife", "EolStatus", "Origin" }; + "AI", "AIComponent", "AIConfidence", "AIReason", "AIModel", "AIChecked", "Sources", "Conflicts", "MaxCVSS", "MaxCVSSSource", "CoherentApplicability", "VersionHint", "Exposure", "ExposureConditions", "NetworkExposure", "ExposurePoints", "ExposureReason", "DependencyScope", "Via", "Fix", "FixInfo", "Sighted", "SightingKind", "SightingDays", "SightingLast", "SightingSources", "PocSightings", "LateOsv", "VendorStatus", "VendorFix", "VendorAdvisory", "VendorWorkaround", "ComponentEol", "ComponentEolText", "EndOfLife", "EolStatus", "Origin" }; var sb = new StringBuilder(); if (basis != null) header = header.Concat(new[] { "Project", "DataBasis" }).ToArray(); sb.AppendLine(string.Join(",", header.Select(Q))); @@ -401,7 +403,7 @@ static string[] Fields(VulnRow r) r.Ai != null ? r.Ai.Checked.ToString("yyyy-MM-dd HH:mm") : "", r.Sources, Safe(r.Conflicts), N(r.MaxScore), r.MaxScoreSource, N(r.CoherentApplicability), Safe(r.VersionHint), Core.Exposure.Label(r.Exposure), Safe(r.Exposure?.Reason), - r.NetworkExposure, r.NetworkExposure.Length == 0 ? "" : N(r.ExposurePoints), Safe(r.ExposureReason), + r.NetworkExposure, r.NetworkExposure.Length == 0 ? "" : N(r.ExposurePoints), Safe(r.ExposureReason), r.DependencyScope, Safe(r.Via), r.FixKind == "nofix" ? "no fix" : (r.FixText ?? "").Replace("\u2713 ", ""), Safe(r.FixTip), r.Sighted ? "True" : "False", r.SightingKind, r.SightingDays?.ToString(ci) ?? "", r.SightingLast, r.SightingSources, r.PocSightings?.ToString(ci) ?? "", r.LateOsv ? "True" : "False", r.VendorStatus, r.VendorFix, r.VendorAdvisory, Safe(r.VendorWorkaround), r.ComponentEol ? "True" : "False", Safe(r.ComponentEolText), diff --git a/gui/MetaScraper.Core/SbomCompare.cs b/gui/MetaScraper.Core/SbomCompare.cs index 564c0e8..1679f80 100644 --- a/gui/MetaScraper.Core/SbomCompare.cs +++ b/gui/MetaScraper.Core/SbomCompare.cs @@ -27,13 +27,14 @@ public sealed class Row public double? OldTriage { get; set; } public double? NewTriage { get; set; } public string Why { get; set; } = ""; + public string Dependency { get; set; } = ""; // direct / "transitive via express@4.17.1" / "" (no graph) // The grid. public string ChangeText => Change switch { "new" => "New", "changed" => "Changed", "resolved" => "Resolved", _ => "Unchanged" }; public string IdText => Id + (Exploited ? " KEV" : ""); public string ComponentText => (OldComponent.Length > 0 ? OldComponent : "-") + " โ†’ " + (NewComponent.Length > 0 ? NewComponent : Change == "resolved" ? "removed" : "-"); public string TriageText => T(OldTriage) + " โ†’ " + T(NewTriage); static string T(double? t) => t.HasValue ? t.Value.ToString("0.#", CultureInfo.InvariantCulture) : "-"; - public bool Matches(string q) => string.IsNullOrWhiteSpace(q) || new[] { Id, Cve, OldComponent, NewComponent, Why, Severity, Change } + public bool Matches(string q) => string.IsNullOrWhiteSpace(q) || new[] { Id, Cve, OldComponent, NewComponent, Why, Severity, Change, Dependency } .Any(s => (s ?? "").Contains(q.Trim(), StringComparison.OrdinalIgnoreCase)); } @@ -76,7 +77,7 @@ IEnumerable Many(JsonElement e, string name) => e.ValueKind == Json ? x.ValueKind == JsonValueKind.Array ? x.EnumerateArray() : x.ValueKind == JsonValueKind.Object ? new[] { x } : Enumerable.Empty() : Enumerable.Empty(); foreach (var x in Many(root, "Rows")) r.Rows.Add(new Row { Change = S(x, "Change"), Id = S(x, "Id"), Cve = S(x, "Cve"), Severity = S(x, "Severity"), Exploited = S(x, "Exploited") == "true", Url = S(x, "Url"), - OldComponent = S(x, "OldComponent"), NewComponent = S(x, "NewComponent"), OldTriage = D(x, "OldTriage"), NewTriage = D(x, "NewTriage"), Why = S(x, "Why") }); + OldComponent = S(x, "OldComponent"), NewComponent = S(x, "NewComponent"), OldTriage = D(x, "OldTriage"), NewTriage = D(x, "NewTriage"), Why = S(x, "Why"), Dependency = S(x, "Dependency") }); if (root.TryGetProperty("Components", out var c)) { foreach (var x in Many(c, "Added")) r.Added.Add(new ComponentChange(S(x, "Component"), S(x, "Old"), S(x, "New"))); diff --git a/gui/MetaScraper.Core/SearchQuery.cs b/gui/MetaScraper.Core/SearchQuery.cs index 6ebf4ab..11df9dd 100644 --- a/gui/MetaScraper.Core/SearchQuery.cs +++ b/gui/MetaScraper.Core/SearchQuery.cs @@ -31,6 +31,7 @@ public sealed class SearchQuery { ["id"] = r => r.Id, ["cve"] = r => r.Cve, ["cveid"] = r => string.IsNullOrEmpty(r.Cve) ? r.Id : r.Cve, ["source"] = r => r.Source, ["src"] = r => r.Source, ["vendor"] = r => r.Vendor, ["product"] = r => r.Product, ["exposure"] = r => r.NetworkExposure, + ["via"] = r => r.Via, ["dependency"] = r => r.DependencyScope, ["dep"] = r => r.DependencyScope, ["desc"] = r => r.Description, ["description"] = r => r.Description, ["matched"] = r => r.Matched, ["keyword"] = r => r.Matched, ["component"] = r => r.MatchedComponents, ["comp"] = r => r.MatchedComponents, @@ -86,6 +87,7 @@ public sealed class SearchQuery ["ai-open"] = r => AiStatus.Kind(r.Ai, r.AiNote) is "open" or "failed", ["ai-notneeded"] = r => AiStatus.Kind(r.Ai, r.AiNote) == "notneeded", ["named"] = r => !string.IsNullOrEmpty(r.RefNickname), ["discussed"] = r => (r.RefSignals ?? "").Contains("community", StringComparison.OrdinalIgnoreCase), ["backport"] = r => (r.ApplicabilityReason ?? "").Contains("backport", StringComparison.OrdinalIgnoreCase), + ["direct"] = r => r.IsDirect, ["transitive"] = r => r.IsTransitive, ["latest"] = r => r.InLatestRun, ["history"] = r => r.InHistory && !r.InLatestRun, ["advisory"] = r => r.IsAdvisory, ["gcve"] = r => r.IsAdvisory || r.HasAdvisories || (r.Id ?? "").StartsWith("GCVE-", StringComparison.OrdinalIgnoreCase), }; diff --git a/gui/MetaScraper.Core/VulnModel.cs b/gui/MetaScraper.Core/VulnModel.cs index 6226d19..1a36e08 100644 --- a/gui/MetaScraper.Core/VulnModel.cs +++ b/gui/MetaScraper.Core/VulnModel.cs @@ -112,6 +112,18 @@ public sealed record FpState(double? InventoryScore, string VersionStatus, strin public string NetLabel => NetworkExposure.Length == 0 ? "" : (NetworkExposure == Core.NetworkExposure.Default ? "physical" : NetworkExposure) + (ExposurePoints != 0 ? " " + ExposurePoints.ToString("+0;-0;0", CultureInfo.InvariantCulture) : ""); public double NetSort => NetworkExposure.Length == 0 ? -1000 : ExposurePoints; + // Direct or transitive dependency (script build 2026-12-04a, Add-DependencyScope): "direct" / "transitive" / "" + // (no dependency graph), and for a transitive one the direct dependencies it comes in through ("express@4.17.1"). + public string DependencyScope { get; set; } = ""; + public string Via { get; set; } = ""; + public bool IsDirect => DependencyScope == "direct"; + public bool IsTransitive => DependencyScope == "transitive"; + // Short: "direct" / "transitive via express@4.17.1" (Workbench, attack paths, reports). + public string DepShort => IsDirect ? "direct" : IsTransitive ? "transitive" + (Via.Length > 0 ? " via " + Via : "") : ""; + // Column "Dep.": direct / transitive; the tooltip names the way in. + public string DepLabel => DependencyScope; + public string DepText => IsDirect ? "direct dependency of the main component" + : IsTransitive ? "transitive dependency" + (Via.Length > 0 ? " - comes in through " + Via + "; an update of that one usually brings the fixed version" : "") : ""; public double SightingBonus => Sighted && !Exploited ? (SightingKind == "report" ? 5 : 10) : 0; public string SightingText => !Sighted ? "" : "Exploitation sighted (CIRCL Vulnerability-Lookup): " + SightingSources + (string.IsNullOrEmpty(SightingLast) ? "" : ", last " + SightingLast) + (SightingKind == "report" ? " - reports only, weaker" : ""); diff --git a/gui/MetaScraper.Core/Watchlist.cs b/gui/MetaScraper.Core/Watchlist.cs index 80f4acd..f8a50d0 100644 --- a/gui/MetaScraper.Core/Watchlist.cs +++ b/gui/MetaScraper.Core/Watchlist.cs @@ -36,6 +36,9 @@ void Set(ref T field, T value, [CallerMemberName] string name = null, params // Network exposure of the systems with its triage points ("isolated, AV:N: -25"), from the run (script 2026-11-25a). string networkExposure = ""; public string NetworkExposure { get => networkExposure; set => Set(ref networkExposure, value ?? ""); } + // Direct or transitive dependency from the run (script 2026-12-04a): "direct" / "transitive via express@4.17.1". + string dependency = ""; + public string Dependency { get => dependency; set => Set(ref dependency, value ?? ""); } public string Sources { get => sources; set => Set(ref sources, value ?? ""); } public string Conflicts { get => conflicts; set => Set(ref conflicts, value ?? ""); } public string SourcesDetail { get => sourcesDetail; set => Set(ref sourcesDetail, value ?? ""); } @@ -386,7 +389,7 @@ public string SevKey Description = r.Description, Url = !string.IsNullOrEmpty(r.CveUrl) ? r.CveUrl : r.Url, Added = DateTime.Now, Note = "", OwnSeverity = "", OwnVector = "", SourceVector = r.CvssVector ?? "", ScoreFrom = r.Source, Cvss4 = r.Cvss4Score, Cvss4Vector = r.Cvss4Vector ?? "", Changes = "", Published = r.Published, Updated = r.Updated, - Sources = r.Sources, Conflicts = r.Conflicts, SourcesDetail = ResultsLoader.SourcesBlock(r), VersionHint = r.VersionHint, NetworkExposure = r.ExposureReason, + Sources = r.Sources, Conflicts = r.Conflicts, SourcesDetail = ResultsLoader.SourcesBlock(r), VersionHint = r.VersionHint, NetworkExposure = r.ExposureReason, Dependency = r.DepShort, // The vulnerability's name from its references (e.g. sshhole) as buzz term; the reference signal for the buzz. BuzzTerms = r.RefNickname ?? "", RefSignals = r.RefSignals ?? "", }; @@ -488,6 +491,12 @@ public List UpdateFrom(VulnRow r, bool newAnalysis = false) if (r.Unmaintained && !(VersionHint ?? "").StartsWith("potentially unmaintained")) d.Add("version potentially unmaintained"); VersionHint = r.VersionHint; } + // The dependency: a change is noted (an entry of an older build only takes the value). + if (r.DepShort != Dependency) + { + if (Dependency.Length > 0) d.Add($"dependency: {Dependency} -> {(r.DepShort.Length > 0 ? r.DepShort : "none")}"); + Dependency = r.DepShort; + } if (r.ExposureReason != NetworkExposure) { d.Add($"network exposure: {(NetworkExposure.Length > 0 ? NetworkExposure : "none")} -> {(r.ExposureReason.Length > 0 ? r.ExposureReason : "none")}"); @@ -520,7 +529,7 @@ public static class WatchlistStore "Sources", "Conflicts", "SourcesDetail", "VersionHint", "AiItems", "Exposure", "ExposureConditions", "ExposureConfidence", "ExposureModel", "ExposureChecked", "Snoozed", "SnoozeReason", - "BasisProject", "BasisVersion", "BasisId", "BasisAt", "BasisTriage", "BasisApplicability", "BasisComponent", "BasisVersionStatus", "NowBasisVersion", "NowBasisId", "NetworkExposure", + "BasisProject", "BasisVersion", "BasisId", "BasisAt", "BasisTriage", "BasisApplicability", "BasisComponent", "BasisVersionStatus", "NowBasisVersion", "NowBasisId", "NetworkExposure", "Dependency", "VexState", "VexJustification", "VexResponse", "VexDetail", }; @@ -549,7 +558,7 @@ public static void Save(IEnumerable entries, string path) e.Exposure?.Verdict ?? "", e.Exposure?.Reason ?? "", e.Exposure != null ? e.Exposure.Confidence.ToString("R", Inv) : "", e.Exposure?.Model ?? "", e.Exposure?.Checked.ToString("o", Inv) ?? "", e.Snoozed?.ToString("o", Inv) ?? "", e.SnoozeReason, e.BasisProject, e.BasisVersion?.ToString(Inv) ?? "", e.BasisId, e.BasisAt?.ToString("o", Inv) ?? "", D(e.BasisTriage), D(e.BasisApplicability), e.BasisComponent, e.BasisVersionStatus, - e.NowBasisVersion?.ToString(Inv) ?? "", e.NowBasisId, e.NetworkExposure, + e.NowBasisVersion?.ToString(Inv) ?? "", e.NowBasisId, e.NetworkExposure, e.Dependency, e.VexState, e.VexJustification, e.VexResponse, e.VexDetail, }; sb.AppendLine(string.Join(",", f.Select(Q))); @@ -596,7 +605,7 @@ public static List Load(string path) Snoozed = T("Snoozed"), SnoozeReason = G("SnoozeReason"), BasisProject = G("BasisProject"), BasisVersion = I("BasisVersion"), BasisId = G("BasisId"), BasisAt = T("BasisAt"), BasisTriage = N("BasisTriage"), BasisApplicability = N("BasisApplicability"), BasisComponent = G("BasisComponent"), BasisVersionStatus = G("BasisVersionStatus"), - NowBasisVersion = I("NowBasisVersion"), NowBasisId = G("NowBasisId"), NetworkExposure = G("NetworkExposure"), + NowBasisVersion = I("NowBasisVersion"), NowBasisId = G("NowBasisId"), NetworkExposure = G("NetworkExposure"), Dependency = G("Dependency"), VexState = G("VexState"), VexJustification = G("VexJustification"), VexResponse = G("VexResponse"), VexDetail = G("VexDetail"), }; if (AiVerdict.Verdicts.Contains(G("AiVerdict"))) @@ -724,6 +733,7 @@ public static string DetailText(WatchEntry e) (string.IsNullOrEmpty(e.BuzzEvidence) ? "" : $"\n Latest: {e.BuzzEvidence}") + (string.IsNullOrEmpty(e.BuzzAuthorityEvidence) ? "" : $"\n Authority: {e.BuzzAuthorityEvidence}")); if (!string.IsNullOrEmpty(e.NetworkExposure)) risk.Add("Network exposure: " + e.NetworkExposure); + if (!string.IsNullOrEmpty(e.Dependency)) risk.Add("Dependency: " + e.Dependency); if (e.Published.HasValue || e.Updated.HasValue) risk.AddRange(ResultsLoader.Facts($"Published: {(e.Published.HasValue ? e.PublishedText : "n/a")} Updated: {(e.Updated.HasValue ? e.UpdatedText : "n/a")}")); ResultsLoader.Section(sb, "RISK", risk); diff --git a/gui/MetaScraper.Desktop/CompareWindow.cs b/gui/MetaScraper.Desktop/CompareWindow.cs index a92545d..9b3914b 100644 --- a/gui/MetaScraper.Desktop/CompareWindow.cs +++ b/gui/MetaScraper.Desktop/CompareWindow.cs @@ -122,6 +122,7 @@ Control Side(string label, ComboBox combo, TextBox path) Col("Vulnerability", nameof(SbomCompare.Row.IdText), 170, null, FontWeight.SemiBold); Col("Severity", nameof(SbomCompare.Row.Severity), 90); Col("Component old โ†’ new", nameof(SbomCompare.Row.ComponentText), 330); + Col("Dependency", nameof(SbomCompare.Row.Dependency), 170); Col("Triage", nameof(SbomCompare.Row.TriageText), 100); Col("Why", nameof(SbomCompare.Row.Why), 360); diff --git a/gui/MetaScraper.Desktop/Converters.cs b/gui/MetaScraper.Desktop/Converters.cs index c990fb7..b32ba01 100644 --- a/gui/MetaScraper.Desktop/Converters.cs +++ b/gui/MetaScraper.Desktop/Converters.cs @@ -120,6 +120,7 @@ public sealed class ColumnHelpConverter : IValueConverter ["Appl."] = "Applicability 0-100: how well the entry matches your products - keyword hit, SBOM component, version check (100 = affected, 0 = not affected).", ["Affected"] = "Is our version affected? version: the version check of the inventory component; vendor: the distribution's statement for the package (affected, or fixed in a newer build); EOL: the component gets no fixes (end of life, or extended support only - paid support is not assumed). \u26a0: version check, vendor or AI review disagree. The same rule as is:affected.", ["Net"] = "Network exposure of the systems (project setting, a component can differ) and its points on the triage risk by the attack vector of the CVE: e.g. isolated -25 (AV:N), internet +20 (AV:N pre-auth); physical: physical access excluded (AV:P). Empty: default, no points. Search exposure:internet, netpoints<0.", + ["Dep."] = "Dependency: direct = the main component uses the affected package itself; transitive = it comes in through another package (the tooltip names it - an update of that one usually brings the fixed version). Empty: the SBOM has no dependency graph. Search is:direct, is:transitive, via:express.", ["Report"] = "Would the entry go into the Auto Report now - with the period and the rules of the Auto Report menu (severity, triage, KEV / not rated always)? The tooltip says why (not). Search is:report.", ["Impact"] = "What the flaw allows (from CWE, CVSS vector, description): RCE, Bypass, PrivEsc, Data, DoS, XSS. 'pre-auth' = no account and no user interaction needed.", ["Vendor"] = "Vendor as named by the source.", diff --git a/gui/MetaScraper.Desktop/InventoryWindow.cs b/gui/MetaScraper.Desktop/InventoryWindow.cs index 71e5673..179cbf3 100644 --- a/gui/MetaScraper.Desktop/InventoryWindow.cs +++ b/gui/MetaScraper.Desktop/InventoryWindow.cs @@ -59,6 +59,8 @@ internal InventoryWindow(string path, Func ai = null, System.Collectio Col("Version", nameof(InventoryEditor.Item.Version), 110); Combo("Scope", nameof(InventoryEditor.Item.Scope), new[] { "required", "optional" }, 100); Combo("Direct", nameof(InventoryEditor.Item.Direct), new[] { "", "yes", "no" }, 80); + // A transitive component: the direct dependencies it comes in through (from the SBOM's graph, 2026-12-04). + Col("Via", nameof(InventoryEditor.Item.Via), 160, readOnly: true); Combo("Exposure", nameof(InventoryEditor.Item.Exposure), InventoryEditor.ExposureChoices, 110); // Role for the attack paths (2026-12-02): auto = the suggestion next to it (package type, well-known names). Combo("Role (exp.)", nameof(InventoryEditor.Item.Role), InventoryEditor.RoleChoices, 140); diff --git a/gui/MetaScraper.Desktop/MainWindow.AttackTab.cs b/gui/MetaScraper.Desktop/MainWindow.AttackTab.cs index 6e8ada6..3427168 100644 --- a/gui/MetaScraper.Desktop/MainWindow.AttackTab.cs +++ b/gui/MetaScraper.Desktop/MainWindow.AttackTab.cs @@ -150,6 +150,13 @@ Control FindingLine(AttackPaths.Step s, string note = null) ToolTip.SetTip(chip, $"Role: {s.Role.Text} - {ComponentRoles.Effect(s.Role.Role)}"); p.Children.Add(chip); } + // A transitive dependency: the direct one it comes in through (the one to update). + if (s.Row.IsTransitive) + { + var dep = Res(new TextBlock { Text = s.Row.DepShort, FontSize = 11, Margin = new Thickness(2, 1, 6, 0) }, TextBlock.ForegroundProperty, "Ms.DimFg"); + ToolTip.SetTip(dep, s.Row.DepText); + p.Children.Add(dep); + } if (s.Stride.Length > 0) { // The STRIDE categories written out; the tooltip says what sets each one. diff --git a/gui/MetaScraper.Desktop/MainWindow.Mode.cs b/gui/MetaScraper.Desktop/MainWindow.Mode.cs index 6614da6..e4912cb 100644 --- a/gui/MetaScraper.Desktop/MainWindow.Mode.cs +++ b/gui/MetaScraper.Desktop/MainWindow.Mode.cs @@ -288,6 +288,7 @@ internal void ScheduleScan() { using var db = new LocalVulnDb(dbPath, true); res = InventoryScan.Scan(InventoryScan.FromInventory(inv), db, line => Dispatcher.UIThread.Post(() => AddLog(line))); + InventoryScan.ApplyDependencyScope(res.Hits, InventoryEditor.Load(inv)); } catch (Exception ex) when (ex is Microsoft.Data.Sqlite.SqliteException or IOException or System.Text.Json.JsonException) { diff --git a/gui/MetaScraper.Desktop/MainWindow.axaml b/gui/MetaScraper.Desktop/MainWindow.axaml index a845880..d4f77ff 100644 --- a/gui/MetaScraper.Desktop/MainWindow.axaml +++ b/gui/MetaScraper.Desktop/MainWindow.axaml @@ -577,6 +577,11 @@ + + + + + )SmokeProgram.Check; + string dir = Path.Combine(outDir, "dependency"); + if (Directory.Exists(dir)) Directory.Delete(dir, true); + Directory.CreateDirectory(dir); + + // The run file. + using (var doc = System.Text.Json.JsonDocument.Parse("{\"ID\":\"CVE-2022-24999\",\"CVE\":\"CVE-2022-24999\",\"Source\":\"NVD\",\"BaseScore\":7.5,\"MatchedComponents\":\"qs@6.7.0\",\"DependencyScope\":\"transitive\",\"Via\":\"express@4.17.1; lodash@4.17.20\"}")) + { + var r = ResultsLoader.FromElement(doc.RootElement); + C($"run file: DependencyScope and Via read ({r.DepShort})", r.IsTransitive && !r.IsDirect && r.Via == "express@4.17.1; lodash@4.17.20" && r.DepLabel == "transitive" + && r.DepShort == "transitive via express@4.17.1; lodash@4.17.20" && r.DepText.Contains("comes in through express@4.17.1; lodash@4.17.20")); + } + var rows = new List + { + Row("CVE-2022-24999", "qs@6.7.0", "transitive", "express@4.17.1", "CWE-1321", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "Prototype pollution in qs lets a remote attacker hang the Node process."), + Row("CVE-2024-29041", "express@4.17.1", "direct", "", "CWE-601", "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N", "Open redirect in express."), + Row("CVE-2021-23337", "lodash@4.17.20", "direct", "", "CWE-94", "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "Command injection via the template function."), + Row("CVE-2023-26136", "tough-cookie@2.5.0", "transitive", "request@2.88.2", "CWE-1321", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N", "Prototype pollution in tough-cookie."), + Row("CVE-2026-2001", "nginx/nginx@1.22.1", "", "", "CWE-787", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "A heap overflow - no dependency graph for this component."), + }; + VulnTools.Recompute(rows, 4, 5, 9, 10, Array.Empty(), Array.Empty(), Array.Empty()); + string[] Find(string q) => rows.Where(SearchQuery.Parse(q, true).Match).Select(r => r.Cve).ToArray(); + C("search: is:direct, is:transitive, via:express, dep:transitive", Find("is:direct").SequenceEqual(new[] { "CVE-2024-29041", "CVE-2021-23337" }) + && Find("is:transitive").SequenceEqual(new[] { "CVE-2022-24999", "CVE-2023-26136" }) && Find("via:express").SequenceEqual(new[] { "CVE-2022-24999" }) + && Find("dep:transitive").Length == 2 && SearchQuery.Parse("is:transitive", true).Error == null); + C("detail text: the dependency with the way in; none without a graph", ResultsLoader.DetailText(rows[0]).Contains("Dependency: transitive dependency - comes in through express@4.17.1") + && ResultsLoader.DetailText(rows[1]).Contains("Dependency: direct dependency of the main component") && !ResultsLoader.DetailText(rows[4]).Contains("Dependency:")); + string csvFile = Path.Combine(dir, "results.csv"); + CsvExport.Write(rows, csvFile); + var csv = File.ReadAllLines(csvFile); + C("CSV export: DependencyScope and Via", csv[0].Contains("\"DependencyScope\",\"Via\"") && csv.Any(l => l.Contains("transitive") && l.Contains("express@4.17.1"))); + + // The Workbench: kept (CSV), in the viewer, a change named. + var we = WatchEntry.FromRow(rows[0]); + string wbFile = Path.Combine(dir, "workbench.csv"); + WatchlistStore.Save(new[] { we }, wbFile); + var wb = WatchlistStore.Load(wbFile).Single(); + C($"Workbench: the dependency kept and shown ({wb.Dependency})", we.Dependency == "transitive via express@4.17.1" && wb.Dependency == we.Dependency + && WatchlistStore.DetailText(wb).Contains("Dependency: transitive via express@4.17.1")); + var moved = Row("CVE-2022-24999", "qs@6.7.0", "direct", "", "CWE-1321", rows[0].CvssVector, rows[0].Description); + var changes = wb.UpdateFrom(moved); + C($"Workbench: a changed dependency named ({string.Join("; ", changes)})", changes.Contains("dependency: transitive via express@4.17.1 -> direct") && wb.Dependency == "direct"); + + // Auto Report: the way in under the fix. + string report = AutoReport.Html(AutoReport.Build(new[] { rows[0], rows[1] }), new AutoReport.Context()); + C("Auto Report: a transitive entry names the way in, a direct one nothing", report.Contains("transitive via express@4.17.1") && !report.Contains(">direct<")); + + // The SBOM comparison: the column Dependency. + string cmpDir = Path.Combine(dir, "compare"); Directory.CreateDirectory(cmpDir); + File.WriteAllText(Path.Combine(cmpDir, SbomCompare.ResultFile), "{ \"Summary\": { \"New\": 1 }, \"Old\": { \"Name\": \"1.0\" }, \"New\": { \"Name\": \"2.0\" }, \"Rows\": [ { \"Change\": \"new\", \"Id\": \"CVE-2022-24999\", \"NewComponent\": \"qs@6.7.0\", \"Dependency\": \"transitive via express@4.17.1\" } ] }"); + var res = SbomCompare.Load(cmpDir); + C("SBOM comparison: the dependency per row, found by the search box", res?.Rows.Single().Dependency == "transitive via express@4.17.1" && res.Rows.Single().Matches("via express")); + + // The inventory: column Via; the Heavy mode scan gets the scope from it. + string inv = Path.Combine(dir, "sbom_inventory.json"); + File.WriteAllText(inv, "[ { \"Product\": \"express\", \"Version\": \"4.17.1\", \"Direct\": true, \"Via\": [] }, { \"Product\": \"qs\", \"Version\": \"6.7.0\", \"Direct\": false, \"Via\": [\"express@4.17.1\"] }, { \"Product\": \"nginx\", \"Version\": \"1.22.1\" } ]"); + var items = InventoryEditor.Load(inv); + C("inventory: Via of a transitive component", items.Single(i => i.Product == "qs").Via == "express@4.17.1" && items.Single(i => i.Product == "express").Via == ""); + var iw = new InventoryWindow(inv); + var heads = iw.ColumnHeaders.ToList(); + C($"inventory window: the column Via after Direct ({string.Join(", ", heads.Take(8))})", heads.IndexOf("Via") == heads.IndexOf("Direct") + 1); + iw.Close(); + var scanned = new List { new() { Id = "CVE-A", MatchedComponents = "qs@6.7.0" }, new() { Id = "CVE-B", MatchedComponents = "qs@6.7.0; express@4.17.1" }, new() { Id = "CVE-C", MatchedComponents = "nginx@1.22.1" } }; + InventoryScan.ApplyDependencyScope(scanned, items); + C($"Heavy mode scan: the scope from the inventory ({string.Join(", ", scanned.Select(s => s.DepShort))})", scanned[0].DepShort == "transitive via express@4.17.1" + && scanned[1].DepShort == "direct" && scanned[2].DepShort == ""); + + // The GUI: column Dep. with its tooltip, the attack paths' long list. + var w = new MainWindow(null, Path.Combine(dir, "settings.json")); + w.Show(); Dispatcher.UIThread.RunJobs(); + try + { + var gridHeads = w.ResGrid.Columns.Select(c => c.Header as string ?? "").ToList(); + C("GUI: the column Dep. right after Net", gridHeads.IndexOf("Dep.") == gridHeads.IndexOf("Net") + 1); + w.ShowRows(rows, "dependency", null); Dispatcher.UIThread.RunJobs(); + w.TabMain.SelectedItem = w.FindControl("TabResults"); w.UpdateLayout(); Dispatcher.UIThread.RunJobs(); + w.ResGrid.SelectedItem = rows[0]; w.UpdateLayout(); Dispatcher.UIThread.RunJobs(); + var cell = w.ResGrid.GetVisualDescendants().OfType().FirstOrDefault(t => t.Text == "transitive" && ToolTip.GetTip(t) is string); + C($"GUI: the cell 'transitive' with the way in as tooltip ({ToolTip.GetTip(cell!)})", (ToolTip.GetTip(cell!) as string ?? "").Contains("comes in through express@4.17.1")); + SmokeProgram.Snap(w, Path.Combine(outDir, "dependency-results.png")); + w.TabMain.SelectedItem = w.TabAttack; w.UpdateLayout(); Dispatcher.UIThread.RunJobs(); + var sol = w.AttackSolutions?.FirstOrDefault(); + if (sol != null) { w.ShowAttackDetails("Long list", sol.Steps, new List<(string, List)> { ("all", sol.Steps) }); w.UpdateLayout(); Dispatcher.UIThread.RunJobs(); } + var via = w.AttackHost.GetVisualDescendants().OfType().FirstOrDefault(t => t.Text == "transitive via express@4.17.1"); + C("attack paths: a transitive finding names the way in, with a tooltip", via != null && (ToolTip.GetTip(via) as string ?? "").Contains("comes in through")); + SmokeProgram.Snap(w, Path.Combine(outDir, "dependency-attack.png")); + } + finally { w.Close(); Dispatcher.UIThread.RunJobs(); } + } +} diff --git a/gui/MetaScraper.Smoke/NetworkExposureChecks.cs b/gui/MetaScraper.Smoke/NetworkExposureChecks.cs index 7fb21e3..e57f106 100644 --- a/gui/MetaScraper.Smoke/NetworkExposureChecks.cs +++ b/gui/MetaScraper.Smoke/NetworkExposureChecks.cs @@ -73,7 +73,7 @@ public static void Run(string outDir) C("back to the project: the field is gone", !File.ReadAllText(inv).Contains("NetworkExposure")); var iw = new InventoryWindow(inv); var heads = iw.ColumnHeaders.ToList(); - C($"the inventory window has the column Exposure after Direct ({string.Join(", ", heads.Take(9))})", heads.IndexOf("Exposure") == heads.IndexOf("Direct") + 1 + C($"the inventory window has the column Exposure after Direct and Via ({string.Join(", ", heads.Take(9))})", heads.IndexOf("Exposure") == heads.IndexOf("Direct") + 2 && InventoryEditor.ExposureChoices.SequenceEqual(new[] { "project", "internet", "internal", "isolated" })); iw.Close(); diff --git a/gui/MetaScraper.Smoke/Program.cs b/gui/MetaScraper.Smoke/Program.cs index 3348228..d053504 100644 --- a/gui/MetaScraper.Smoke/Program.cs +++ b/gui/MetaScraper.Smoke/Program.cs @@ -81,6 +81,7 @@ public static int Main(string[] rawArgs) Section("runlog", "Run log: select, copy, context menu", () => RunLogCopyChecks.Run(outDir)); Section("zen", "Colour schemes: Zen, Synthwave", () => ColorSchemeChecks.Run(outDir, data)); Section("zen", "Colour schemes: a fresh start in Synthwave, then Zen", () => SchemeFreshStartChecks.Run(outDir)); + Section("dependency", "Direct and transitive dependencies: column Dep., search, details, CSV, Workbench, attack paths, report, comparison, inventory, scan", () => DependencyScopeChecks.Run(outDir)); Section("buzz", "Buzz prototype", () => BuzzChecks.Run(outDir, data)); if (mock != null) Section("config", "Script build check, settings migration", () => SettingsMigrationChecks.Run(outDir, mock)); Section("results", "Results tab layout, chips, thresholds", () => ResultsLayoutChecks.Run(outDir, data)); diff --git a/gui/MetaScraper.Smoke/ReportRulesChecks.cs b/gui/MetaScraper.Smoke/ReportRulesChecks.cs index eab18ba..4ab0eda 100644 --- a/gui/MetaScraper.Smoke/ReportRulesChecks.cs +++ b/gui/MetaScraper.Smoke/ReportRulesChecks.cs @@ -89,7 +89,7 @@ public static void Run(string outDir) w.ReportMinSeverity.SelectedIndex = 2; Dispatcher.UIThread.RunJobs(); // Medium C("GUI: from Medium - all three in", r3.ReportIn && Count("is:report") == 3); var heads = w.ResGrid.Columns.Select(c => c.Header as string ?? "").ToList(); - C("GUI: the column Report right after Net", heads.IndexOf("Report") == heads.IndexOf("Net") + 1); + C("GUI: the column Report right after Net and Dep.", heads.IndexOf("Report") == heads.IndexOf("Net") + 2 && heads.IndexOf("Dep.") == heads.IndexOf("Net") + 1); C("GUI: 'List why CVEs are not in it' off by default", w.ReportListLeftOut.IsChecked != true); w.ReportListLeftOut.IsChecked = true; Dispatcher.UIThread.RunJobs(); w.SaveSettings(); diff --git a/gui/MetaScraper.Smoke/ResultsLayoutChecks.cs b/gui/MetaScraper.Smoke/ResultsLayoutChecks.cs index 8bb7495..6204d37 100644 --- a/gui/MetaScraper.Smoke/ResultsLayoutChecks.cs +++ b/gui/MetaScraper.Smoke/ResultsLayoutChecks.cs @@ -47,7 +47,7 @@ public static void Run(string outDir, string dataDir) C("first three columns frozen", grid.FrozenColumnCount == 3 && cols[0] == "Triage" && cols[1] == "Severity" && cols[2] == "CVE"); // Column order as agreed (icon columns by their sort field); the AI review next to the applicability it judges. string[] names = grid.Columns.Select(c => c.Header as string ?? c.SortMemberPath).ToArray(); - string[] expected = { "Triage", "Severity", "CVE", "WorkbenchState", "Exploited", "Poc", "CVSS", "EPSS %", "Appl.", "Affected", "Net", "Report", "AiSort", "ExposureSort", "Impact", "Fix", "Vendor", "Product", "Versions", + string[] expected = { "Triage", "Severity", "CVE", "WorkbenchState", "Exploited", "Poc", "CVSS", "EPSS %", "Appl.", "Affected", "Net", "Dep.", "Report", "AiSort", "ExposureSort", "Impact", "Fix", "Vendor", "Product", "Versions", "Published", "Updated", "Description", "Vector", "ID", "Component", "Sources", "Changed", "Matched" }; C("column order: " + string.Join(", ", names), names.SequenceEqual(expected)); // Mouse-over help of the column headers. diff --git a/metascraper.ps1 b/metascraper.ps1 index 1b799c6..9a069b5 100644 --- a/metascraper.ps1 +++ b/metascraper.ps1 @@ -654,7 +654,7 @@ function Write-Log { } # Writes a visible/logged separator before the effective configuration. # Build marker: shows in the log which state of the script ran (update it with changes that matter for support). -$script:ScriptBuild = '2026-12-03b (false positives by component: an entry counts for nothing only when every component it matches is covered, KeywordOnly for a keyword hit; 2026-12-03a: false positives set by hand for the project: project VEX - ProjectVexFile, State false_positive, a component without version covers every version of it, FalsePositive in the run file; 2026-12-02a: impact classes after the NVD mapping view CWE-1003 - all its clear entries classified: memory errors CWE-129, 131, 193, 672, 681, 704, 908; denial of service CWE-662, 667, 920; data CWE-203, 311, 922; XML entity expansion CWE-776 is denial of service, not data; HTTP request smuggling CWE-444 and default credentials CWE-1392 / 1393 bypass access control; format string CWE-134 is memory corruption; 2026-12-01b: generic version comparison: trailing zero segments count nothing - 1.0.0 = 1.0, a range up to 1.0 includes 1.0.0; shared version cases with the GUI in tests/version-cases.json; 2026-12-01a: the SBOM file of each matched component in the run file - ComponentSboms - so the GUI groups attack paths by solution without matching labels; 2026-11-30a: versions of language packages and apk by the rules of their ecosystem - PEP 440, semver, Maven qualifiers, apk suffixes - instead of the generic comparison; package identity beats text: a language package gets no hit from the words of a description when the record names other packages of its ecosystem - log4j-api on the Log4Shell record of log4j-core; package keys of SBOM and records compared in one form, PyPI by PEP 503, npm scope; 2026-11-28a: the short name of a namespaced package - Go module, scoped npm package, Composer, Swift, GitHub - alone in a CVE description is no listed hit: golang.org/x/term on "long term key"; 2026-11-25b: version check by name: a product match under another vendor - nothing in common - is no hit, the version is not compared; a partly matching vendor makes an uncertain hit for the AI review, VendorMatch / VendorMatchPct in the run file; 2026-11-25a: network exposure of the project and of single components: points on the triage risk by the attack vector of the CVE, physical access excluded; 2026-11-24b: extended support only counts as end of life in the triage: entry 50, CVEs + 10 - paid support is not assumed; 2026-11-24a: a distribution package written without its release part: version check unknown, vendor status "fixed (build unknown)" instead of a false all-clear; 2026-11-21c: -ReplayFile: re-evaluation of a run from its source records - the store of the GUI - instead of a snapshot; the input of the normalizers in the observations (KEV catalog + KEVin, Red Hat), the records of attached GCVE advisories, the settings of the download in run_stats.json, -NoSnapshotCopy: a re-evaluation without a copy of the run snapshot, the raw record of every source in its observation of combined_vulnerabilities.json; HTML report: long version lists folded behind + N more; end-of-life components as entries of their own without CVE: severity End of life, triage 50 / 30 in extended support, cobweb marker in the report; end of life of the inventory components and their distribution releases from endoflife.date: warnings in every run, eol_components.json, + 10 triage risk; vendor status of distribution packages - the same rule for every distribution: Red Hat CSAF VEX for RHEL and its rebuilds CentOS Stream, Rocky, AlmaLinux, Oracle Linux, SUSE CSAF VEX for SLES and openSUSE, Ubuntu CVE API, Debian Security Tracker, Alpine secdb, Amazon Linux CVE API - not affected, fixed with version and advisory, no fix planned, workaround; end of life of every release from endoflife.date, impact classes: CWE-494 code without integrity check = RCE, CWE-62 hard link = privilege escalation, code execution named in the description counts next to the CWE classes, sightings.json in the run folder for the GUI history, sightings of exploitation from CIRCL Vulnerability-Lookup: honeypots, KEV catalogs, reports, feeds: Atom and JSON Feed of new and changed relevant entries, GitHub re-query: reason per HTTP status, re-evaluation from a run snapshot without downloading again, up to 40 coordinates per source for the version table, distribution OSV records without a fix count as open, version coverage: potentially unmaintained versions, explicit not affected statements, merge fixes, pair keywords vendor|product, shadow value coherent coordinates, one object per CVE with an observation per source and disagreements - results format 2, no NoTypeInformation warning on PowerShell 7, proxy login with user and password, faster local phases, CIRCL cache two hours overlap, EUVD 80 per page, references as buzz signal, Red Hat description with colons fixed, CIRCL cache, CIRCL stops on a failing server, version matching: backports, distribution packages, rpm / deb versions, KEV from the official CISA catalog, inventory / VEX / OSV on Windows PowerShell 5.1 fixed, CIRCL 100 per page, GCVE advisories, phase timing, weakness: CWE and impact classes, CIRCL read by publication date when IncludeUpdates is off, rate limits: request pacing per source, Retry-After, no page halving on HTTP 429, continue to the end of the time window, safe page sizes, NVD 120-day ranges, operational statistics per source, log levels, UTF-8 output for the GUI, CIRCL page size 25, lenient JSON, CIRCL page size retry and oversized records, CVSS vectors, masked secrets)' +$script:ScriptBuild = '2026-12-04a (direct / transitive per entry: DependencyScope and Via of the matched components; 2026-12-03b: false positives by component: an entry counts for nothing only when every component it matches is covered, KeywordOnly for a keyword hit; 2026-12-03a: false positives set by hand for the project: project VEX - ProjectVexFile, State false_positive, a component without version covers every version of it, FalsePositive in the run file; 2026-12-02a: impact classes after the NVD mapping view CWE-1003 - all its clear entries classified: memory errors CWE-129, 131, 193, 672, 681, 704, 908; denial of service CWE-662, 667, 920; data CWE-203, 311, 922; XML entity expansion CWE-776 is denial of service, not data; HTTP request smuggling CWE-444 and default credentials CWE-1392 / 1393 bypass access control; format string CWE-134 is memory corruption; 2026-12-01b: generic version comparison: trailing zero segments count nothing - 1.0.0 = 1.0, a range up to 1.0 includes 1.0.0; shared version cases with the GUI in tests/version-cases.json; 2026-12-01a: the SBOM file of each matched component in the run file - ComponentSboms - so the GUI groups attack paths by solution without matching labels; 2026-11-30a: versions of language packages and apk by the rules of their ecosystem - PEP 440, semver, Maven qualifiers, apk suffixes - instead of the generic comparison; package identity beats text: a language package gets no hit from the words of a description when the record names other packages of its ecosystem - log4j-api on the Log4Shell record of log4j-core; package keys of SBOM and records compared in one form, PyPI by PEP 503, npm scope; 2026-11-28a: the short name of a namespaced package - Go module, scoped npm package, Composer, Swift, GitHub - alone in a CVE description is no listed hit: golang.org/x/term on "long term key"; 2026-11-25b: version check by name: a product match under another vendor - nothing in common - is no hit, the version is not compared; a partly matching vendor makes an uncertain hit for the AI review, VendorMatch / VendorMatchPct in the run file; 2026-11-25a: network exposure of the project and of single components: points on the triage risk by the attack vector of the CVE, physical access excluded; 2026-11-24b: extended support only counts as end of life in the triage: entry 50, CVEs + 10 - paid support is not assumed; 2026-11-24a: a distribution package written without its release part: version check unknown, vendor status "fixed (build unknown)" instead of a false all-clear; 2026-11-21c: -ReplayFile: re-evaluation of a run from its source records - the store of the GUI - instead of a snapshot; the input of the normalizers in the observations (KEV catalog + KEVin, Red Hat), the records of attached GCVE advisories, the settings of the download in run_stats.json, -NoSnapshotCopy: a re-evaluation without a copy of the run snapshot, the raw record of every source in its observation of combined_vulnerabilities.json; HTML report: long version lists folded behind + N more; end-of-life components as entries of their own without CVE: severity End of life, triage 50 / 30 in extended support, cobweb marker in the report; end of life of the inventory components and their distribution releases from endoflife.date: warnings in every run, eol_components.json, + 10 triage risk; vendor status of distribution packages - the same rule for every distribution: Red Hat CSAF VEX for RHEL and its rebuilds CentOS Stream, Rocky, AlmaLinux, Oracle Linux, SUSE CSAF VEX for SLES and openSUSE, Ubuntu CVE API, Debian Security Tracker, Alpine secdb, Amazon Linux CVE API - not affected, fixed with version and advisory, no fix planned, workaround; end of life of every release from endoflife.date, impact classes: CWE-494 code without integrity check = RCE, CWE-62 hard link = privilege escalation, code execution named in the description counts next to the CWE classes, sightings.json in the run folder for the GUI history, sightings of exploitation from CIRCL Vulnerability-Lookup: honeypots, KEV catalogs, reports, feeds: Atom and JSON Feed of new and changed relevant entries, GitHub re-query: reason per HTTP status, re-evaluation from a run snapshot without downloading again, up to 40 coordinates per source for the version table, distribution OSV records without a fix count as open, version coverage: potentially unmaintained versions, explicit not affected statements, merge fixes, pair keywords vendor|product, shadow value coherent coordinates, one object per CVE with an observation per source and disagreements - results format 2, no NoTypeInformation warning on PowerShell 7, proxy login with user and password, faster local phases, CIRCL cache two hours overlap, EUVD 80 per page, references as buzz signal, Red Hat description with colons fixed, CIRCL cache, CIRCL stops on a failing server, version matching: backports, distribution packages, rpm / deb versions, KEV from the official CISA catalog, inventory / VEX / OSV on Windows PowerShell 5.1 fixed, CIRCL 100 per page, GCVE advisories, phase timing, weakness: CWE and impact classes, CIRCL read by publication date when IncludeUpdates is off, rate limits: request pacing per source, Retry-After, no page halving on HTTP 429, continue to the end of the time window, safe page sizes, NVD 120-day ranges, operational statistics per source, log levels, UTF-8 output for the GUI, CIRCL page size 25, lenient JSON, CIRCL page size retry and oversized records, CVSS vectors, masked secrets)' Write-Host "[SCRIPT] metascraper.ps1 build $script:ScriptBuild - PowerShell $($PSVersionTable.PSVersion)" Write-Log "Log level: $LogLevel$(if ($logFile) { " (log file $logFile)" })" Write-Log "======================== APPLIED CONFIGURATION ========================" @@ -2096,7 +2096,7 @@ function Import-Inventory([string]$path, [string]$projectVex) { $namespaced = $ptype -in 'golang', 'composer', 'swift', 'github', 'gitlab', 'bitbucket' -or ($ptype -eq 'npm' -and "$($it.Purl)" -match '^pkg:npm/(%40|@)') $pkey = if ($it.PurlKey) { Format-PackageKey "$($it.PurlKey)" } else { $null } $c = [pscustomobject]@{ Index = $comps.Count; Label = $label; PackageKey = $pkey; Version = "$($it.Version)"; Generic = [bool]$it.Generic; VendorBroad = [bool]$it.VendorBroad; VendorKeys = $vendorKeys; ProductKeys = $productKeys; Namespaced = $namespaced - Direct = $it.Direct; Scope = "$($it.Scope)"; Origin = $origin; PurlType = $ptype; Distro = "$($it.Distro)"; Backports = $bp + Direct = $it.Direct; Via = [string[]]@($it.Via | Where-Object { $_ }); Scope = "$($it.Scope)"; Origin = $origin; PurlType = $ptype; Distro = "$($it.Distro)"; Backports = $bp NetworkExposure = (ConvertTo-ExposureClass "$($it.NetworkExposure)" -Override); Sbom = ("$($it.Sbom)" -split '[\\/]')[-1] } $comps.Add($c) $add = { param($table, $key) if ($key) { if (-not $table.ContainsKey($key)) { $table[$key] = [System.Collections.Generic.List[object]]::new() }; $table[$key].Add($c) } } @@ -4253,6 +4253,28 @@ function Add-NetworkExposure { return $counts } +# Direct or transitive (asked 2026-12-04): from the matched components of the inventory (SbomFilterExtractor, from the +# dependency graph). DependencyScope direct when one matched component is a direct dependency, transitive when every +# known one is transitive (nothing when the inventory has no graph); Via the direct dependencies a transitive one comes +# in through ("express@4.17.1; lodash@4.17.20") - the fix is mostly an update of those. End-of-life entries included. +function Add-DependencyScope { + param ([object[]]$Data, $Inventory = $null) + $byLabel = @{} + foreach ($c in @($Inventory.Components)) { if ($c -and $null -ne $c.Direct) { $byLabel["$($c.Label)"] = $c } } + if ($byLabel.Count -eq 0) { return $null } + $counts = @{ direct = 0; transitive = 0 } + foreach ($item in $Data) { + if ($null -eq $item) { continue } + $known = @(@("$($item.MatchedComponents)" -split ';\s*' | Where-Object { $_ }) | Where-Object { $byLabel.ContainsKey($_) } | ForEach-Object { $byLabel[$_] }) + if ($known.Count -eq 0) { continue } + if (@($known | Where-Object { $_.Direct -eq $true }).Count) { Set-NoteProperty $item 'DependencyScope' 'direct'; $counts.direct++; continue } + Set-NoteProperty $item 'DependencyScope' 'transitive' + Set-NoteProperty $item 'Via' ((@($known | ForEach-Object { $_.Via }) | Where-Object { $_ } | Select-Object -Unique) -join '; ') + $counts.transitive++ + } + return $counts +} + function Add-FilterMatches { param ( # Normalized vulnerability objects; updated in place. @@ -6549,6 +6571,11 @@ function Invoke-LocalPhases { $ex = Add-NetworkExposure -Data @($combinedData) -Inventory $(if ($useInventory) { $inventory } else { $null }) -Exposure $NetworkExposure -PhysicalExcluded $PhysicalAccessExcluded -Points $exPoints -PhysicalPoints $PhysicalAccessPoints if ($ex) { Write-Host "[EXPOSURE] project $(ConvertTo-ExposureClass $NetworkExposure)$(if ($PhysicalAccessExcluded) { ', physical access excluded' }): $($ex.internet) internet, $($ex.internal) internal, $($ex.isolated) isolated, $($ex.default) default; $($ex.points) entries with points (internet: $ExposurePointsInternet; internal: $ExposurePointsInternal; isolated: $ExposurePointsIsolated$(if ($PhysicalAccessExcluded) { "; physical: $PhysicalAccessPoints" }))" } } + # Direct or transitive dependency (the matched components of the inventory). + if ($useInventory -and @($combinedData).Count -gt 0) { + $ds = Add-DependencyScope -Data @($combinedData) -Inventory $inventory + if ($ds) { Write-Host "[DEPENDENCY] $($ds.direct) entries in direct dependencies, $($ds.transitive) only in transitive ones" } + } # Keyword matching, applicability and triage score, stored in the normalized objects before they are written. Start-Phase 'keywords-triage' @($combinedData).Count if (@($combinedData).Count -gt 0) { diff --git a/tests/dependency-graph.ps1 b/tests/dependency-graph.ps1 new file mode 100644 index 0000000..bcb9f79 --- /dev/null +++ b/tests/dependency-graph.ps1 @@ -0,0 +1,105 @@ +# Direct and transitive dependencies (asked 2026-12-04): SbomFilterExtractor.ps1 marks each inventory component Direct +# true / false from the dependency graph and names, for a transitive one, the direct dependencies it comes in through +# (Via). The graph comes from a CycloneDX SBOM or from a lockfile that has one (package-lock v2/v3, pnpm-lock, +# packages.lock.json, Gemfile.lock, Cargo.lock, uv.lock); lockfiles without one (yarn.lock, poetry.lock ...) leave +# Direct empty. +# Run by the GUI smoke test (area "origin"); on its own: pwsh -NoProfile -File tests/dependency-graph.ps1 +$ErrorActionPreference = 'Stop' +$tool = Join-Path (Split-Path -Parent $PSScriptRoot) 'SbomFilterExtractor.ps1' +$pwsh = (Get-Process -Id $PID).Path +$script:fail = 0; $script:count = 0 +function Check([string]$name, [bool]$ok, $got = $null) { $script:count++; if (-not $ok) { $script:fail++; Write-Host " FAIL $name$(if ($null -ne $got) { " - got: $got" })" } } + +$d = Join-Path ([IO.Path]::GetTempPath()) ("depgraph-test-" + [guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory $d | Out-Null +# One file per folder: the tool on it, the inventory back. +function Inv([string]$file, [string]$text) { + $dir = Join-Path $d ([guid]::NewGuid().ToString('N')); New-Item -ItemType Directory $dir | Out-Null + [IO.File]::WriteAllText((Join-Path $dir $file), $text) + $null = & $pwsh -NoProfile -File $tool -SbomPath (Join-Path $dir $file) -OutDir (Join-Path $dir 'out') 2>&1 + @(Get-Content (Join-Path $dir 'out/sbom_inventory.json') -Raw | ConvertFrom-Json) +} +function Of($inv, [string]$product) { $inv | Where-Object { $_.Product -eq $product } | Select-Object -First 1 } +function D($c) { if ($null -eq $c) { 'missing' } elseif ($null -eq $c.Direct) { 'unknown' } elseif ($c.Direct) { 'direct' } else { 'transitive via ' + (@($c.Via) -join ', ') } } +try { + # CycloneDX: app -> express -> body-parser -> qs; app -> lodash; lodash -> qs too (two ways in). + $cdx = @' +{ "bomFormat": "CycloneDX", "specVersion": "1.6", + "metadata": { "component": { "type": "application", "name": "app", "bom-ref": "app" } }, + "components": [ + { "type": "library", "name": "express", "version": "4.17.1", "purl": "pkg:npm/express@4.17.1", "bom-ref": "express" }, + { "type": "library", "name": "body-parser", "version": "1.19.0", "purl": "pkg:npm/body-parser@1.19.0", "bom-ref": "bp" }, + { "type": "library", "name": "qs", "version": "6.7.0", "purl": "pkg:npm/qs@6.7.0", "bom-ref": "qs" }, + { "type": "library", "name": "lodash", "version": "4.17.20", "purl": "pkg:npm/lodash@4.17.20", "bom-ref": "lodash" } ], + "dependencies": [ { "ref": "app", "dependsOn": ["express", "lodash"] }, { "ref": "express", "dependsOn": ["bp"] }, + { "ref": "bp", "dependsOn": ["qs"] }, { "ref": "lodash", "dependsOn": ["qs"] } ] } +'@ + $inv = Inv 'bom.cdx.json' $cdx + $script:cdxInventory = Get-ChildItem $d -Recurse -Filter sbom_inventory.json | Select-Object -First 1 -ExpandProperty FullName + Check 'CycloneDX: express direct' ((D (Of $inv 'express')) -eq 'direct') (D (Of $inv 'express')) + Check 'CycloneDX: body-parser transitive via express' ((D (Of $inv 'body-parser')) -eq 'transitive via express@4.17.1') (D (Of $inv 'body-parser')) + Check 'CycloneDX: qs transitive, two ways in (express, lodash)' ((D (Of $inv 'qs')) -eq 'transitive via express@4.17.1, lodash@4.17.20') (D (Of $inv 'qs')) + + # package-lock v3: the root's dependencies; nested node_modules resolved like npm. + $npm = '{"name":"app","lockfileVersion":3,"packages":{"":{"name":"app","dependencies":{"express":"^4"}},' + + '"node_modules/express":{"version":"4.17.1","dependencies":{"qs":"6.7.0"}},"node_modules/express/node_modules/qs":{"version":"6.7.0"},' + + '"node_modules/qs":{"version":"6.11.0"}}}' + $inv = Inv 'package-lock.json' $npm + $qs = @($inv | Where-Object { $_.Product -eq 'qs' }) + Check 'package-lock: express direct' ((D (Of $inv 'express')) -eq 'direct') (D (Of $inv 'express')) + Check 'package-lock: nested qs 6.7.0 via express, hoisted qs 6.11.0 unused' ((D ($qs | Where-Object Version -eq '6.7.0')) -eq 'transitive via express@4.17.1' -and (D ($qs | Where-Object Version -eq '6.11.0')) -eq 'transitive via ') (($qs | ForEach-Object { "$($_.Version): $(D $_)" }) -join '; ') + + # pnpm-lock v9: importers "." and snapshots. + $pnpm = "lockfileVersion: '9.0'`n`nimporters:`n`n .:`n dependencies:`n express:`n specifier: ^4.17.1`n version: 4.17.1`n`npackages:`n`n express@4.17.1:`n resolution: {integrity: x}`n`n qs@6.7.0:`n resolution: {integrity: y}`n`nsnapshots:`n`n express@4.17.1:`n dependencies:`n qs: 6.7.0`n`n qs@6.7.0: {}`n" + $inv = Inv 'pnpm-lock.yaml' $pnpm + Check 'pnpm-lock: express direct, qs via express' ((D (Of $inv 'express')) -eq 'direct' -and (D (Of $inv 'qs')) -eq 'transitive via express@4.17.1') "$(D (Of $inv 'express')) / $(D (Of $inv 'qs'))" + + # .NET packages.lock.json: type Direct / Transitive and the dependencies of each package. + $nuget = '{"version":1,"dependencies":{"net8.0":{"Serilog.AspNetCore":{"type":"Direct","requested":"[8.0.0, )","resolved":"8.0.0","dependencies":{"Serilog":"3.1.1"}},"Serilog":{"type":"Transitive","resolved":"3.1.1"}}}}' + $inv = Inv 'packages.lock.json' $nuget + Check 'packages.lock.json: Serilog via Serilog.AspNetCore' ((D (Of $inv 'serilog.aspnetcore')) -eq 'direct' -and (D (Of $inv 'serilog')) -eq 'transitive via serilog.aspnetcore@8.0.0') "$(D (Of $inv 'serilog.aspnetcore')) / $(D (Of $inv 'serilog'))" + + # Gemfile.lock: DEPENDENCIES and the dependency lines under a spec. + $gem = "GEM`n remote: https://rubygems.org/`n specs:`n rails (7.0.4)`n rack (>= 2.2)`n rack (2.2.6.2)`n`nPLATFORMS`n ruby`n`nDEPENDENCIES`n rails (~> 7.0)`n" + $inv = Inv 'Gemfile.lock' $gem + Check 'Gemfile.lock: rails direct, rack via rails' ((D (Of $inv 'rails')) -eq 'direct' -and (D (Of $inv 'rack')) -eq 'transitive via rails@7.0.4') "$(D (Of $inv 'rails')) / $(D (Of $inv 'rack'))" + + # Cargo.lock: the crate without source is the project. + $cargo = "version = 3`n`n[[package]]`nname = ""myapp""`nversion = ""0.1.0""`ndependencies = [`n ""tokio"",`n]`n`n[[package]]`nname = ""tokio""`nversion = ""1.25.0""`nsource = ""registry+https://github.com/rust-lang/crates.io-index""`ndependencies = [`n ""mio 0.8.6"",`n]`n`n[[package]]`nname = ""mio""`nversion = ""0.8.6""`nsource = ""registry+https://github.com/rust-lang/crates.io-index""`n" + $inv = Inv 'Cargo.lock' $cargo + Check 'Cargo.lock: tokio direct, mio via tokio' ((D (Of $inv 'tokio')) -eq 'direct' -and (D (Of $inv 'mio')) -eq 'transitive via tokio@1.25.0') "$(D (Of $inv 'tokio')) / $(D (Of $inv 'mio'))" + + # uv.lock: the virtual project and its dependencies. + $uv = "version = 1`n`n[[package]]`nname = ""myapp""`nversion = ""0.1.0""`nsource = { virtual = ""."" }`ndependencies = [`n { name = ""requests"" },`n]`n`n[[package]]`nname = ""requests""`nversion = ""2.31.0""`nsource = { registry = ""https://pypi.org/simple"" }`ndependencies = [`n { name = ""urllib3"" },`n]`n`n[package.metadata]`nrequires-dist = [{ name = ""other"" }]`n`n[[package]]`nname = ""urllib3""`nversion = ""2.0.7""`nsource = { registry = ""https://pypi.org/simple"" }`n" + $inv = Inv 'uv.lock' $uv + Check 'uv.lock: requests direct, urllib3 via requests' ((D (Of $inv 'requests')) -eq 'direct' -and (D (Of $inv 'urllib3')) -eq 'transitive via requests@2.31.0') "$(D (Of $inv 'requests')) / $(D (Of $inv 'urllib3'))" + + # A lockfile without a graph: Direct stays unknown (no deduction in metascraper.ps1). + $inv = Inv 'yarn.lock' "# yarn lockfile v1`n`nlodash@^4.17.20:`n version ""4.17.21""`n" + Check 'yarn.lock: no graph, Direct unknown' ((D (Of $inv 'lodash')) -eq 'unknown') (D (Of $inv 'lodash')) + + # metascraper.ps1: each entry gets DependencyScope and Via from its matched components (build 2026-12-04a). + $ms = Join-Path (Split-Path -Parent $PSScriptRoot) 'metascraper.ps1' + $tok = $null; $err = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($ms, [ref]$tok, [ref]$err) + $res = & { + foreach ($f in $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $false)) { Invoke-Expression $f.Extent.Text } + function Write-Log { param($m) } + $minv = Import-Inventory $script:cdxInventory $null + $labels = @{}; foreach ($c in $minv.Components) { $labels[($c.Label -split '@')[0] -replace '^.*/', ''] = $c.Label } + $e1 = [pscustomobject]@{ ID = 'CVE-1'; MatchedComponents = $labels['express'] } + $e2 = [pscustomobject]@{ ID = 'CVE-2'; MatchedComponents = $labels['qs'] } + $e3 = [pscustomobject]@{ ID = 'CVE-3'; MatchedComponents = "$($labels['qs']); $($labels['lodash'])" } + $e4 = [pscustomobject]@{ ID = 'CVE-4'; MatchedComponents = 'other/thing@1.0' } + $counts = Add-DependencyScope -Data @($e1, $e2, $e3, $e4) -Inventory $minv + @{ e = @($e1, $e2, $e3, $e4); counts = $counts } + } + $e = $res.e + Check 'script: an entry in a direct dependency is direct' ($e[0].DependencyScope -eq 'direct' -and -not $e[0].PSObject.Properties['Via']) ($e[0] | ConvertTo-Json -Compress) + Check 'script: an entry only in a transitive one is transitive, Via the direct ones' ($e[1].DependencyScope -eq 'transitive' -and $e[1].Via -eq 'express@4.17.1; lodash@4.17.20') ($e[1] | ConvertTo-Json -Compress) + Check 'script: also in a direct one - direct wins' ($e[2].DependencyScope -eq 'direct') ($e[2] | ConvertTo-Json -Compress) + Check 'script: a component not in the inventory - nothing set' (-not $e[3].PSObject.Properties['DependencyScope'] -and $res.counts.direct -eq 2 -and $res.counts.transitive -eq 1) ($e[3] | ConvertTo-Json -Compress) +} finally { Remove-Item -Recurse -Force -LiteralPath $d -ErrorAction SilentlyContinue } + +Write-Host "dependency-graph: $($script:count - $script:fail) / $($script:count) ok" +exit $(if ($script:fail -eq 0) { 0 } else { 1 })