This lesson combines 2 topics: Supply Chain Attacks, SBOM & Dependency Scanning.
Learning Objectives
- Know the well-known supply chain incidents: event-stream, ua-parser-js, node-ipc, xz utils
- Understand the risk patterns: typosquatting, dependency confusion, malicious update
- Know why lockfiles (
package-lock.json,yarn.lock,poetry.lock,go.sum) matter - Know signed commits (GPG, Sigstore), npm provenance, and signing in general
- Understand the reasons for vendoring a copy and running an internal mirror registry (Nexus, Artifactory)
- Know the SLSA framework (Supply-chain Levels for Software Artifacts) levels 1-4
- Understand what an SBOM (Software Bill of Materials) is and why it is becoming a compliance requirement
- Compare the two SBOM standards: SPDX and CycloneDX
- Know the SBOM generation tools: syft, cdxgen,
npm sbom, Trivy - Know the dependency scanning pipeline: npm/pip-audit, Snyk, Dependabot, Renovate
- Know container image scanning: Trivy, Grype, Anchore
- Understand the CVE database, the CVSS score, and the difference between severity and exploitability
- Integrate scanning into CI: fail the build on high-severity CVEs, allowlist when needed
Part 1: Supply Chain Attacks
1. What is a supply chain attack?
Definition: an attack that targets one component (dependency, build tool, CI runner, registry, maintainer account) in the software supply chain instead of attacking the target directly. One compromised dependency = every user of that library is affected.
Why supply chain attacks are becoming more dangerous
- Modern apps have thousands of transitive dependencies (node_modules is often > 1000)
- The maintainer of a critical lib is often one anonymous person (xkcd 2347)
- Automatic updates (Dependabot, Renovate) merge patch releases that nobody reviews
- A single npm install can run an arbitrary
postinstallscript
2. Well-known incidents
event-stream (2018)
2011-2018: event-stream was a popular npm package (~2 million downloads/week)
2018-09: The original maintainer lost interest and accepted an offer from user "right9ctrl" to hand it over
2018-09: right9ctrl published a new version with a new dependency: flatmap-stream
2018-10: flatmap-stream was published (by the same person), containing obfuscated code
2018-11: The malicious code activated if the app depended on "copay" (Bitcoin wallet)
→ stole the private keys of Bitcoin wallets
2018-11: Discovered and the package was pulled
Lesson: a maintainer handover with no vetting + npm allowing any version to be published → a transitive dep can change the original behavior.
ua-parser-js (2021)
2021-10-22: The maintainer's npm account was taken over (password leak)
2021-10-22: The attacker published 3 malicious versions: 0.7.29, 0.8.0, 1.0.0
preinstall script:
- Windows: download crypto miner + password stealer
- Linux: crypto miner only
2021-10-23: Users reported it, the package was unpublished after ~4 hours
But millions of CI runs/installs had already executed the postinstall script
Lesson: account takeover is the main vector → mandatory 2FA for maintainers, and --ignore-scripts is a line of defense.
node-ipc protestware (2022)
2022-03: Maintainer RIAEvangelist (Brandon Nozaki Miller) updated node-ipc
Added code: if IP geolocation = Russia or Belarus
→ overwrite every file in the project with the emoji "❤️"
Purpose: "protest war in Ukraine"
2022-03: Thousands of devs were affected, with no connection to the war
2022-03: GitHub assigned CVE-2022-23812 — malicious code, not "protest"
Lesson: even a "well-intentioned" maintainer can become an attack vector. Lockfile + audit is the defense.
xz utils backdoor (2024) — it almost succeeded
2021: "Jia Tan" started contributing to xz utils (a popular compression lib)
2022-23: Built trust through hundreds of legitimate PRs
2024-02: The main maintainer was pressured into letting "Jia Tan" co-maintain
2024-02: Jia Tan published version 5.6.0 with a backdoor:
- The backdoor was injected through a build script (m4/build-to-host.m4)
- When liblzma.so is loaded by sshd, it hooks RSA_public_decrypt
- Lets the attacker authenticate to SSH with their own signature
2024-03-29: Andres Freund (Microsoft) discovered it because ssh logins were 500ms slower than normal
2024-03-30: CVE-2024-3094 (CVSS 10.0)
xz 5.6.0/5.6.1 pulled from every distro
The backdoor was already in Fedora Rawhide, Debian Sid, Kali → nearly reached stable
Estimate if it had reached stable: ~50% of Linux servers could have had a backdoored SSH
Scary lessons:
- Long-term social engineering (3 years)
- The backdoor was injected at build time, not visible in the Git source code
- Discovered purely by luck (Andres happened to be benchmarking)
- Even a SLSA Level 3+ build may not catch it if the CI itself is compromised
3. Risk patterns
3a. Typosquatting
Real package: express
Typo package: experess, expres, expressjs, express-js
Real package: urllib3 (Python)
Typo package: urlib3, url-lib3, urllib4
Real package: discord.js
Typo package: discord-js, discordjs, dscord.js
The attacker publishes a package with a name close to a popular package, hoping a dev mistypes it. When npm install runs, the typo package's postinstall script runs → malicious code.
3b. Dependency confusion
2021: Alex Birsan demonstrated how to attack more than 35 large companies (Apple, Microsoft, ...)
Setup:
The company has an internal npm package: @mycompany/internal-utils (private registry)
The npm config has both the public registry and the internal registry
Attack:
The attacker publishes a package "@mycompany/internal-utils" to the public npmjs.com
With a HIGHER version number (e.g. 99.0.0)
When building inside the company:
npm/yarn checks both registries → sees version 99.0.0 on public is higher
→ installs the public (malicious) version instead of the internal one
Defense:
- The scope (
@mycompany/) must be reserved on the public npmjs.com even if you never publish there - Configure
.npmrcwith a strict registry for each scope:@mycompany:registry=https://nexus.mycompany.com/ - Use a
--scopemirror in Artifactory/Nexus
3c. Malicious update / maintainer takeover
Vectors:
1. Account password reuse → leaked from another data breach → attacker logs in
2. Phishing email "update your npm 2FA"
3. Maintainer hands the package over to a stranger (event-stream)
4. Long-con social engineering (xz utils)
5. CI token leak → attacker publishes a new version
Defense on the user side:
- Lockfile + no automatic minor/patch updates in production deploys
- Pin exact versions (
"react": "18.2.0", not"^18.2.0") - Review the changelog/release notes before bumping
- Use
npm audit signaturesto verify npm provenance
4. Lockfile — indispensable
Why lockfiles matter
package.json (declared):
"lodash": "^4.17.0" ← caret: allows 4.x.x
package-lock.json (resolved):
"lodash": {
"version": "4.17.21",
"integrity": "sha512-v2kDEe57lecTul...",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"
}
Without a lockfile:
- Today
npm install→ lodash 4.17.21 - Tomorrow the maintainer publishes 4.17.22 →
npm installpulls 4.17.22 (a different build) - Reproducibility = 0, "works on my machine" is back
With a lockfile + integrity:
- Every
npm ciproduces exactly the same versions - If the tarball is tampered with (malicious code injected) → hash mismatch → install fails
Pin transitively
The lockfile pins every dep, including transitive ones:
package.json: declares only top-level deps
package-lock.json: records every sub-dep with version + integrity hash
→ thousands of entries
When a sub-dep releases a new version with malicious code:
npm install (without lockfile) → may pull the new version
npm ci (with lockfile) → still uses the old pinned version
Lockfiles per ecosystem
| Tool | Lockfile | Strict install command |
|---|---|---|
| npm | package-lock.json | npm ci |
| yarn classic | yarn.lock | yarn install --frozen-lockfile |
| yarn berry | yarn.lock | yarn install --immutable |
| pnpm | pnpm-lock.yaml | pnpm install --frozen-lockfile |
| Python pip-tools | requirements.txt (pinned) | pip install -r requirements.txt |
| Python Poetry | poetry.lock | poetry install --no-update |
| Python uv | uv.lock | uv sync --frozen |
| Go | go.sum (with go.mod) | go build (verifies hashes by default) |
| Cargo | Cargo.lock | cargo build --locked |
| Bundler | Gemfile.lock | bundle install --frozen |
| Composer | composer.lock | composer install |
In CI
# GitHub Actions — the right way
- name: Install deps (strict)
run: npm ci # ← DO NOT use "npm install"
# npm ci: fails if the lockfile is out of sync, never updates the lockfile
5. Signed commits and artifact signing
Why sign?
Default git:
A commit has "author" and "committer" fields — but these are JUST SELF-DECLARED STRINGS
I can create a commit with author "Linus Torvalds <torvalds@kernel.org>"
→ complete impersonation
Signed commit:
The commit carries a digital signature (GPG or SSH key)
Verify with the public key → guarantees the private key owner signed this commit
GPG signing
# Create a GPG key
gpg --full-generate-key
# Choose: RSA 4096 or Ed25519, expiration 1-2 years
# List keys
gpg --list-secret-keys --keyid-format=long
# /home/user/.gnupg/secring.gpg
# sec ed25519/3AA5C34371567BD2 2024-01-15
# Export the public key, upload it to GitHub
gpg --armor --export 3AA5C34371567BD2
# Configure git to use this key
git config --global user.signingkey 3AA5C34371567BD2
git config --global commit.gpgsign true
git config --global tag.gpgsign true
# Commits are signed automatically from now on
git commit -m "feat: ..."
# Verify
git log --show-signature
SSH signing (Git 2.34+)
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
Simpler than GPG, reuses the SSH key you already have.
Sigstore — keyless signing
The problem with GPG/SSH keys: key management for millions of maintainers is a nightmare. Sigstore solves it with ephemeral key + OIDC:
Signing flow:
1. Maintainer logs in via OIDC (Google/GitHub) → gets a JWT
2. cosign creates an ephemeral key pair (lives ~10 minutes)
3. Fulcio (Sigstore's cert authority) issues a short-lived cert embedding the JWT identity
4. Maintainer signs the artifact with the ephemeral key
5. Signature + cert + JWT → uploaded to Rekor (transparency log, immutable)
6. Throw away the private key
Verify:
- Read the signature
- Verify the cert chain up to the Fulcio root
- Check that the Rekor log has a matching entry (trusted timestamp)
- Read the identity from the cert: e.g. "ci@release.example.com from github.com/org/repo"
# Install cosign
brew install cosign
# Sign container image
cosign sign --yes <registry>/<image>@sha256:<digest>
# Verify
cosign verify <image> \
--certificate-identity-regexp ".+@release.example.com" \
--certificate-oidc-issuer https://token.actions.githubusercontent.com
npm provenance
npm provenance (since 2023): when you publish a package from GitHub Actions, the npm CLI calls Sigstore to sign it and link the package to:
- The workflow YAML that built it
- The commit SHA
- The GitHub repo
# In CI:
npm publish --provenance --access public
# User verifies:
npm audit signatures
# → "X packages have verified registry signatures"
# → "Y packages have verified attestations"
Users can check that the tarball was really built from the claimed source code, not from an attacker's mysterious laptop.
6. Vendor a copy / mirror registry
Vendoring
Instead of depending on the public registry:
Copy the dep's source code into your own repo (vendor/ directory)
Build using the code in vendor/ instead of downloading
Pros:
- 100% reproducible — no dependency on registry uptime
- You can audit all the code that runs
- Safe from npm unpublish and registry compromise
Cons:
- The repo grows a lot (Go vendor can reach GB)
- Updating a dep = updating the vendor folder
- PR diffs are often hard to review
Go has built-in support: go mod vendor. Some Node projects use patch-package for selective vendoring.
Internal mirror registry
# .npmrc
registry=https://nexus.mycompany.com/repository/npm-proxy/
//nexus.mycompany.com/:_authToken=${NEXUS_TOKEN}
Pros:
- Centralized control: one place to vet/scan
- Cache: avoids hitting npmjs rate limits
- Audit: logs every package downloaded in the company
- When npmjs is down → internal builds still work
7. SLSA framework
SLSA (Supply-chain Levels for Software Artifacts) — a framework created by Google + OpenSSF, defining 4 increasing levels.
What is provenance?
An attestation (JSON) that describes how the artifact was built:
{
"subject": [{
"name": "my-app",
"digest": { "sha256": "abc123..." }
}],
"predicate": {
"buildType": "https://github.com/actions/...",
"builder": { "id": "https://github.com/actions/runner" },
"invocation": {
"configSource": {
"uri": "git+https://github.com/org/repo@refs/tags/v1.0",
"digest": { "sha1": "deadbeef..." },
"entryPoint": ".github/workflows/release.yml"
}
},
"materials": [/* deps used */]
}
}
Users verify provenance to know:
- Which commit this artifact was built from
- Which workflow triggered the build
- Which runner ran the build
- Which dependencies were used
Reaching SLSA L3 with GitHub Actions
# .github/workflows/release.yml
permissions:
contents: write
id-token: write # for OIDC
packages: write
jobs:
build:
uses: slsa-framework/slsa-github-generator/.github/workflows/builder_generic_slsa3.yml@v2.0.0
with:
base64-subjects: "${{ needs.compute-hash.outputs.hash }}"
This standard workflow:
- Builds the artifact in an ephemeral VM
- Generates provenance signed by Sigstore (keyless)
- The provenance includes: commit SHA, workflow ref, runner, materials
- Users can verify "this artifact came from exactly this repo+workflow"
Part 2: SBOM & Dependency Scanning
1. What is an SBOM?
SBOM = "Software Bill of Materials"
Similar to:
- The BOM (Bill of Materials) in car manufacturing: a list of parts
- The nutrition label on food: lists the ingredients
An SBOM for software: lists EVERY component (lib, framework, tool) in
an artifact (binary, container image, source release), along with:
- Component name
- Version
- License
- Supplier
- Hash (cryptographic checksum)
- Relationships (which depends on which)
Why SBOMs are becoming mandatory
2020: SolarWinds attack — a backdoor in the Orion software affected 18,000 organizations
2021: Log4Shell (CVE-2021-44228) — log4j 2.x had an RCE, every Java app using log4j was hit
The painful question: "do we use log4j? which version? where?"
Without an SBOM → manually scan hundreds of apps within a few hours
2021-05: Executive Order 14028 (US) — requires an SBOM for all software sold to the US gov
2023-Q4: EU Cyber Resilience Act (CRA) — requires an SBOM for hardware/software sold in the EU
2024: SBOMs start becoming mandatory for critical infra
Concrete use cases
- Incident response: a new CVE is announced → query the SBOM database → instantly know which apps are affected
- License compliance: make sure you don't accidentally ship GPL code in a proprietary product
- Supply chain audit: a customer asks "do you use dep X?" → answer precisely
- Vulnerability management: continuously scan SBOMs against the CVE database
2. SPDX vs CycloneDX
SPDX (Software Package Data Exchange)
- ISO/IEC 5962:2021 — an international standard
- Maintained by the Linux Foundation since 2010
- Formats: tag-value, JSON, YAML, RDF, spreadsheet
- Strong on license metadata (the SPDX License List is the standard license identifier)
{
"spdxVersion": "SPDX-2.3",
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "my-app-1.0.0",
"documentNamespace": "https://example.com/sbom/my-app-1.0.0",
"creationInfo": {
"created": "2025-06-15T10:00:00Z",
"creators": ["Tool: syft-v1.0.0"]
},
"packages": [
{
"SPDXID": "SPDXRef-Package-lodash",
"name": "lodash",
"versionInfo": "4.17.21",
"downloadLocation": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"filesAnalyzed": false,
"checksums": [{ "algorithm": "SHA256", "checksumValue": "abc123..." }],
"licenseConcluded": "MIT",
"supplier": "Organization: lodash maintainers"
}
],
"relationships": [
{
"spdxElementId": "SPDXRef-Package-my-app",
"relationshipType": "DEPENDS_ON",
"relatedSpdxElement": "SPDXRef-Package-lodash"
}
]
}
CycloneDX
- Started at OWASP, a lightweight design for security use cases
- Formats: JSON, XML, Protocol Buffers
- Integrates well with VEX (Vulnerability Exploitability eXchange)
{
"bomFormat": "CycloneDX",
"specVersion": "1.5",
"serialNumber": "urn:uuid:3e671687-...",
"version": 1,
"components": [
{
"type": "library",
"bom-ref": "pkg:npm/lodash@4.17.21",
"name": "lodash",
"version": "4.17.21",
"purl": "pkg:npm/lodash@4.17.21",
"licenses": [{ "license": { "id": "MIT" } }],
"hashes": [{ "alg": "SHA-256", "content": "abc123..." }]
}
],
"dependencies": [
{
"ref": "pkg:npm/my-app@1.0.0",
"dependsOn": ["pkg:npm/lodash@4.17.21"]
}
]
}
Comparison
| Criterion | SPDX | CycloneDX |
|---|---|---|
| Standardization | ISO/IEC 5962:2021 | ECMA-424 (in process) |
| Maintainer | Linux Foundation | OWASP |
| Main focus | License compliance | Security / vulnerability |
| Format | JSON, YAML, tag-value, RDF | JSON, XML |
| PURL support | Yes (since 2.3) | Yes (native) |
| VEX integration | Yes | Native |
| Best for | Legal/compliance team | DevSecOps pipeline |
In practice: use both when needed. Most tools (syft, Trivy, cdxgen) can export both formats.
Package URL (PURL)
PURL standardizes how packages are identified across ecosystems:
pkg:npm/lodash@4.17.21
pkg:pypi/django@4.2.7
pkg:maven/org.apache.logging.log4j/log4j-core@2.17.0
pkg:golang/github.com/gin-gonic/gin@v1.9.1
pkg:docker/library/postgres@15.4
pkg:cargo/serde@1.0.193
General format: pkg:<type>/<namespace>/<name>@<version>?<qualifiers>#<subpath>
3. Generating an SBOM with syft
syft is the most popular CLI, supporting ~30 ecosystems.
# Install
brew install syft
# Scan directory (source code)
syft .
# Scan container image
syft alpine:3.19
syft docker.io/myorg/myapp:v1
# Scan and export the SBOM
syft . -o spdx-json > sbom.spdx.json
syft . -o cyclonedx-json > sbom.cdx.json
syft . -o table # human-readable
# Scan binary
syft /usr/bin/curl
Sample output:
NAME VERSION TYPE
async 3.2.4 npm
express 4.18.2 npm
lodash 4.17.21 npm
...
Generating an SBOM with npm built-in (npm 10+)
npm sbom --sbom-format spdx > sbom.spdx.json
npm sbom --sbom-format cyclonedx > sbom.cdx.json
cdxgen — multi-language
npm install -g @cyclonedx/cdxgen
cdxgen -o bom.json -t nodejs .
cdxgen -o bom.json -t python .
cdxgen -o bom.json -t java .
SBOM for a container image
# Build image
docker build -t myapp:v1 .
# Generate an SBOM for the image (including the OS package layer)
syft myapp:v1 -o spdx-json > myapp-sbom.json
# Attach the SBOM to the image as an attestation (cosign + Sigstore)
cosign attest --predicate myapp-sbom.json \
--type spdxjson \
myapp:v1
4. Dependency scanning — detecting CVEs
CVE and CVSS basics
Severity scale (CVSS v3.1)
| Score | Severity |
|---|---|
| 0.1 - 3.9 | Low |
| 4.0 - 6.9 | Medium |
| 7.0 - 8.9 | High |
| 9.0 - 10.0 | Critical |
Severity vs Exploitability — an important difference
CVE severity = "Worst case impact IF exploited"
Exploitability = "The real likelihood of exploitation in your app"
Example: a critical CVE in a dep, but:
- Your app does not call the vulnerable function → the exploit cannot reach it
- Your app does not expose it to untrusted input → the attacker cannot trigger it
- The dep only runs in the dev env (devDependency) → production is not affected
→ Severity 10.0 does not automatically = "patch now"
You need to assess the actual exploitability in context
Tools per ecosystem
Node: npm audit, pnpm audit, yarn audit
Python: pip-audit, safety
Ruby: bundle audit
Go: govulncheck (Google official)
Java: OWASP Dependency-Check, Snyk
Rust: cargo audit
Multi: Snyk, GitHub Dependabot, Renovate, Mend (WhiteSource)
npm audit
npm audit
# Output:
# found 5 vulnerabilities (2 moderate, 2 high, 1 critical)
# To address all issues, run:
# npm audit fix
# To address all issues (including breaking changes), run:
# npm audit fix --force
# Details
npm audit --json
# Only fail on high+
npm audit --audit-level=high
pip-audit
pip install pip-audit
pip-audit
pip-audit -r requirements.txt
# Output:
# Found 2 known vulnerabilities in 1 package
# Name Version ID Fix Versions
# urllib3 1.26.5 GHSA-mh33-7rrq-662w 1.26.18
govulncheck — flags only EXPLOITABLE vulns
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
# The difference: govulncheck analyzes the call graph
# It only reports a CVE if your code actually CALLS the vulnerable function
# → significantly fewer false positives
Snyk (commercial)
npm install -g snyk
snyk auth
snyk test # scan deps
snyk container test myapp:v1 # scan container
snyk iac test # scan Terraform/K8s
snyk code test # SAST
5. GitHub Dependabot and Renovate
Dependabot
GitHub native, free for every repo:
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 10
groups:
minor-and-patch:
update-types: ["minor", "patch"]
ignore:
- dependency-name: "react"
versions: [">=19.0.0"] # temporarily hold the major
- package-ecosystem: docker
directory: /
schedule:
interval: weekly
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
Dependabot automatically opens PRs when:
- There is a security advisory (urgent, uses
dependabot/security-updates) - There is a new version (scheduled)
Renovate (Mend) — more powerful
// renovate.json
{
"extends": ["config:base"],
"schedule": ["after 9pm every weekday", "before 5am every weekday"],
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch"],
"automerge": true,
"automergeType": "branch"
},
{
"matchDepTypes": ["devDependencies"],
"automerge": true
},
{
"matchPackagePatterns": ["^@types/"],
"automerge": true,
"groupName": "@types packages"
}
],
"vulnerabilityAlerts": {
"labels": ["security"],
"schedule": ["at any time"]
}
}
Where Renovate beats Dependabot:
- Groups many updates into 1 PR (less noise)
- Smarter auto-merge
- More detailed scheduling
- Supports more ecosystems (Terraform, Helm, Kustomize)
6. Container image scanning
Trivy — Aqua Security (open source, free)
Grype + syft (Anchore stack)
brew install grype
# Scan image
grype alpine:3.19
grype myapp:v1
# Scan from an SBOM (offline, fast)
syft myapp:v1 -o json > sbom.json
grype sbom:sbom.json
Trivy vs Grype comparison
| Trivy | Grype | |
|---|---|---|
| Vendor | Aqua Security | Anchore |
| License | Apache 2.0 | Apache 2.0 |
| Scan types | Image, filesystem, IaC, secret, SBOM | Image, filesystem, SBOM |
| DB sources | NVD, GHSA, OSV, distro advisories | NVD, GHSA, distro advisories |
| Speed | Fast, single binary | Fast when used with a pre-built SBOM |
| IaC scan | Yes (Terraform, K8s, Dockerfile) | No (use the separate anchore-engine) |
Practical recommendation: Trivy for one-stop scanning. syft + grype when you need separation between SBOM generation and scanning (for example: offline scanning in an air-gapped env).
7. Integrating into CI
GitHub Actions — fail the build on HIGH+
# .github/workflows/security.yml
name: Security Scan
on:
push:
branches: [main]
pull_request:
schedule:
- cron: "0 6 * * *" # daily 6am UTC
jobs:
deps:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: npm audit
run: npm audit --audit-level=high
continue-on-error: false
- name: pip-audit
if: hashFiles('requirements.txt') != ''
run: |
pip install pip-audit
pip-audit -r requirements.txt
container:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Trivy scan
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
format: sarif
output: trivy-results.sarif
severity: HIGH,CRITICAL
exit-code: "1" # fail the build if there is a HIGH/CRITICAL
ignore-unfixed: true # skip CVEs with no fix yet
- name: Upload SARIF to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: trivy-results.sarif
sbom:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Generate SBOM
uses: anchore/sbom-action@v0
with:
format: spdx-json
output-file: sbom.spdx.json
- uses: actions/upload-artifact@v4
with:
name: sbom
path: sbom.spdx.json
Allowlist when needed (.trivyignore)
# .trivyignore — ignore CVEs with no fix yet or that are not exploitable
# Every CVE must have a comment with the reason and a re-review date
# CVE-2024-1234: only affects a function we do not call (path X.Y.Z)
# Re-review: 2026-12-31
CVE-2024-1234
# CVE-2024-5678: the dep is only used in dev/test
CVE-2024-5678
Allowlist rules:
- Every entry must have an expiry date — no permanent allowlisting
- The comment must explain why it is not fixed, not just "ignore"
- Review the allowlist every quarter
Branch protection — block merges when there is a critical CVE
GitHub repo Settings → Branches → Branch protection rules:
- Require status checks before merge:
✓ Security Scan / deps
✓ Security Scan / container
8. VEX — reducing noise
The problem: the scan tool reports 50 CVEs — how many actually matter?
Manual triage costs a lot of engineer hours.
VEX (Vulnerability Exploitability eXchange): a machine-readable document
saying "CVE X is present in dep Y but is NOT affected because of reason Z"
CycloneDX VEX example
{
"vulnerabilities": [
{
"id": "CVE-2024-1234",
"source": { "name": "NVD" },
"affects": [{ "ref": "pkg:npm/express@4.18.2" }],
"analysis": {
"state": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
"detail": "Vulnerable function `express.unsafeRender` is not used in the app. Verified by static analysis tool X, last reviewed 2025-06-15."
}
}
]
}
state can be:
resolved— already patchedexploitable— confirmed affectednot_affected— not affected (with a justification)false_positive— the scan tool was wrongin_triage— under review
VEX enables automation: CI sees a CVE → checks VEX → if there is a not_affected entry, skip the alert. Less false-positive fatigue.
Review Questions
-
How were event-stream and ua-parser-js compromised through different mechanisms, and what is the lesson for devs?
Show answer
event-stream (2018): the maintainer handed over the package to a stranger ("right9ctrl"). This person published a new version with a transitive dep (flatmap-stream) containing malicious code that targeted users of the copay Bitcoin wallet. Vector: ownership transfer with no vetting.
ua-parser-js (2021): the maintainer's npm account was taken over (password leak). The attacker published 3 malicious versions with a preinstall script that downloaded a crypto miner and a password stealer. Vector: account compromise + missing 2FA.
Lessons: (1) lockfile + audit transitive deps, (2)
--ignore-scriptsfor unfamiliar deps, (3) do not auto-update minor/patch in production, (4) review the changelog before bumping a major, (5) encourage maintainers to enable 2FA (npm has required 2FA for top packages since 2022). -
Why does a lockfile (
package-lock.json,poetry.lock, ...) matter especially for security, not just reproducibility?Show answer
A lockfile pins the exact version + integrity hash of every dep (both top-level and transitive). The security consequences:
(1) Version pinning: if a sub-dep releases a new version containing malicious code (like event-stream), a build with the old lockfile still uses the pinned version → no "auto-poisoning".
(2) Integrity verification: the lockfile stores the tarball hash. If the registry/CDN returns a different tarball (due to compromise or MITM),
npm ci/pnpm install --frozenfails with a hash mismatch.(3) Reproducibility for audit: SBOM + lockfile = you know exactly which code runs in production at each commit, which is essential for incident response when a new CVE is announced.
Mandatory: use
npm ci(notnpm install) in CI. -
How does a dependency confusion attack work, and how do you defend against it?
Show answer
How it works: a company has an internal package
@mycompany/utilsin a private registry. The npm config has both the public and private registries. The attacker publishes a package with the same name@mycompany/utilsto the public npmjs.com with a higher version (e.g.99.0.0). Onnpm install, npm resolves the highest version → pulls the public (malicious) version. Alex Birsan demonstrated this approach against 35+ large companies (2021).Defense: (1) Reserve the
@mycompany/*scope on the public npmjs.com even if you publish nothing, (2) configure.npmrcwith a strict per-scope registry:@mycompany:registry=https://nexus.mycompany.com/(3) use an internal mirror as the only registry (Nexus, Artifactory) — it proxies public packages and does not allow resolving directly against public.
-
How does the xz utils backdoor (2024) differ from earlier incidents, and why is it scarier?
Show answer
Differences: (1) Long-term social engineering (~3 years) — "Jia Tan" contributed legitimate PRs to build trust, then was given co-maintainer status. (2) The backdoor was not in the git source code but injected at build time via an m4 macro — you could not see it by looking at the source. (3) A very deep target: liblzma is linked by sshd (via systemd notify), and the backdoor allowed an RSA-based SSH auth bypass.
Scary because: (a) it was detected almost entirely by luck (Andres Freund was benchmarking sshd and noticed it was 500ms slower than normal). (b) It was already in rolling distros (Fedora Rawhide, Debian Sid) — it nearly reached stable and would have affected tens of millions of servers. (c) A SLSA L3+ build may not catch it, because a compromised build platform was not the problem — the source code itself contained the backdoor logic.
Lessons: you need (1) reproducible builds, (2) review of build scripts, not just source code, (3) the "burned-out maintainer" is the main target — maintainers of critical deps need financial/people support (OpenSSF Alpha-Omega program).
-
How does Sigstore/cosign differ from GPG signing, and why is it easier to adopt at scale?
Show answer
GPG: the maintainer holds a long-term private key (1-2 years) and distributes the public key via keyservers/GitHub. The verifier needs to know in advance which key fingerprint to trust. Problems: key management is hard (lost key, leak, rotation), public key discovery is slow, and every project maintains its own web-of-trust.
Sigstore (keyless): there is no long-term private key. Each signing: (1) log in via OIDC (Google/GitHub) → JWT, (2) Fulcio issues an ephemeral cert (lives ~10 minutes) embedding the identity from the JWT, (3) sign with the ephemeral key, (4) signature + cert + log entry → Rekor (immutable transparency log). Throw away the private key after signing.
Benefits at scale: (1) No long-term key to be stolen/leaked, (2) identity = OIDC subject (e.g. "release@npm.example.com via github.com/org/repo workflow X") is easier to verify than a key fingerprint, (3) the immutable Rekor log lets you verify "this package was signed at time X", preventing backdating, (4) npm provenance and GitHub container signing already use Sigstore by default — adoption is very fast.
-
Why did SBOMs become a compliance requirement after the Log4Shell incident?
Show answer
When Log4Shell (CVE-2021-44228) was announced in December 2021, every organization had to answer a simple question: "Do we use log4j? Which version? In which apps?" Without an SBOM, security teams had to manually scan hundreds of apps, taking days — while attackers were exploiting it within hours of the PoC going public.
The result: US Executive Order 14028 (May 2021) requires an SBOM for all software sold to the US gov. The EU Cyber Resilience Act (2024) is similar. SBOMs became the standard tool for incident response, vulnerability management, license compliance, and supply chain audit. With an SBOM, the query "who uses log4j 2.x" becomes a SQL one-liner instead of thousands of hours of effort.
-
How do SPDX and CycloneDX differ, and when should you use which?
Show answer
SPDX: the ISO/IEC 5962:2021 standard, maintained by the Linux Foundation since 2010. Strong focus on license compliance — the SPDX License List is the industry-wide standard license identifier. Many formats (JSON, YAML, RDF, tag-value).
CycloneDX: started at OWASP, lightweight, strong focus on security use cases. Native support for VEX (Vulnerability Exploitability eXchange). JSON/XML formats.
When to use:
- SPDX for legal/compliance teams (license audits, US gov submissions that specifically require SPDX)
- CycloneDX for DevSecOps pipelines (scanning integration, VEX, easy to generate)
- In practice: many tools (syft, Trivy) export both; vendor both when needed.
-
How do a CVE's severity and its exploitability in a specific app differ? Give an example.
Show answer
Severity (CVSS score): measures the "worst case impact IF the CVE is successfully exploited". It is computed for a general scenario, without knowing the specific context of the app.
Exploitability in the app: whether the CVE can actually be reached in your app, based on: (1) Is the vulnerable code CALLED (call graph analysis)? (2) Does untrusted input reach that function? (3) Is the dep used at runtime or only in dev (devDependency)?
Example: CVE-2024-XYZ in an image processing library with CVSS 9.8 (Critical) — a buffer overflow when parsing an exotic image format. If your app only uses that library to resize JPGs (a completely different function) and never calls the vulnerable function → exploitability = 0 in practice, even though severity = 9.8.
That is why tools like
govulncheck(Go) analyze the call graph to flag only CVEs that are actually reachable, reducing false positives. The VEX standard helps document/communicate this. -
Why does letting Renovate or Dependabot auto-merge minor/patch updates still require caution?
Show answer
Auto-merging minor/patch relies on the assumption of proper SemVer: minor/patch only adds features/fixes bugs, nothing breaking. The problems:
(1) Maintainers do not follow SemVer: many libs break things in a patch (especially in the npm ecosystem). Auto-merge can push a breaking bug to prod.
(2) Supply chain attacks: event-stream and ua-parser-js were compromised via patch updates. If you auto-merge every patch, malicious code reaches production within hours.
(3) Behavioral change: a lib may change its log format, metrics, or default behavior in a "patch" — not breaking the API but breaking monitoring/operations.
Best practice: (a) auto-merge only devDependencies + types, (b) require human review for runtime deps, (c) run the full test suite + smoke tests before merging, (d) deploy auto-merges to staging first, with a soak time of a few hours before rolling to prod, (e) prioritize security alerts (faster lane) but still require status checks.
-
Which layers does container image scanning with Trivy find vulns in, and what does the "ignore-unfixed" pattern mean?
Show answer
Trivy scans several layers in the image:
- OS package layer: Alpine
apk, Debian/Ubuntudpkg, RHELrpm— checks distro advisories - Application dep layer:
node_modules, Python packages, Go modules in the image — checks NVD/GHSA - Secrets: hardcoded API keys, private keys in layers
- Misconfiguration: Dockerfile bad practices (USER root, COPY .env, etc.)
--ignore-unfixed: skips CVEs that have no fixed version available. Reason: many CVEs in distro packages (Alpine, Debian) are announced before the distro maintainers release a patch. Reporting these CVEs is "non-actionable noise" — you cannot fix them by updating because the update does not exist yet. Ignore them until a fix exists → less alert fatigue and focus on CVEs you can act on.
Be careful: you still need a periodic background scan to know when a fix becomes available so you can upgrade.
Hands-on Exercises
Part 1: Supply Chain Attacks
# 1. Create an SBOM-like lockfile audit
cd your-project
npm ci
npm ls --all > deps-tree.txt
wc -l deps-tree.txt # actual number of deps (often > 1000)
# 2. Find transitive deps with flagged versions
npm audit
npm audit --audit-level=high
npm audit signatures # check npm provenance
# 3. Block scripts during install
npm install --ignore-scripts
# Or set it permanently:
npm config set ignore-scripts true
# 4. Set up GPG signing for git
gpg --full-generate-key # choose ed25519 or RSA 4096
KEY_ID=$(gpg --list-secret-keys --keyid-format=long | grep sec | awk '{print $2}' | cut -d/ -f2)
git config --global user.signingkey $KEY_ID
git config --global commit.gpgsign true
gpg --armor --export $KEY_ID # upload to GitHub
# Test commit
git commit --allow-empty -m "test: signed commit"
git log --show-signature -1
# 5. SSH-based signing (alternative, simpler)
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
# 6. Sign a container image with cosign
brew install cosign
docker build -t myorg/myapp:v1 .
docker push myorg/myapp:v1
# Keyless sign (needs OIDC from GitHub Actions or a local browser)
cosign sign myorg/myapp:v1
# Verify
cosign verify myorg/myapp:v1 \
--certificate-identity dev@example.com \
--certificate-oidc-issuer https://github.com/login/oauth
# 7. Block dependency confusion with .npmrc
cat > .npmrc <<EOF
@mycompany:registry=https://nexus.mycompany.com/
//nexus.mycompany.com/:_authToken=\${NEXUS_TOKEN}
EOF
Part 2: SBOM & Dependency Scanning
# 1. Generate an SBOM for the current project
brew install syft trivy grype
cd ~/your-node-project
syft . -o spdx-json > sbom.spdx.json
syft . -o cyclonedx-json > sbom.cdx.json
syft . -o table # human-readable preview
# 2. Scan with npm audit and pip-audit
npm audit --audit-level=high
# If Python:
pip install pip-audit
pip-audit -r requirements.txt
# 3. Scan the SBOM with grype (offline)
grype sbom:sbom.cdx.json
# 4. Build an image and scan it with Trivy
cat > Dockerfile <<EOF
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
CMD ["npm", "start"]
EOF
docker build -t my-app:test .
trivy image my-app:test
trivy image --severity HIGH,CRITICAL --ignore-unfixed my-app:test
trivy image --format spdx-json my-app:test > image-sbom.json
# 5. Scan the Dockerfile and IaC
trivy config Dockerfile
trivy config . # scan all Terraform/K8s if present
# 6. Set up the Dependabot config
mkdir -p .github
cat > .github/dependabot.yml <<EOF
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 10
- package-ecosystem: docker
directory: /
schedule:
interval: weekly
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
EOF
git add .github/dependabot.yml
git commit -m "chore: enable Dependabot"
# 7. Trigger a Trivy scan in CI (.github/workflows/security.yml)
# See the example in section 7 of the lesson
References
- SLSA framework
- Sigstore
- npm provenance docs
- Alex Birsan — Dependency Confusion
- OpenSSF Best Practices
- xz utils backdoor (CVE-2024-3094) writeup
- SPDX specification
- CycloneDX specification
- PURL spec
- Trivy documentation
- syft / grype
- GitHub Dependabot
- Renovate
- NVD — National Vulnerability Database
- OSV — Open Source Vulnerabilities