devHọc Dev
EN
Bài học

Tuần 2 - Ngày 9: Supply Chain Attacks, SBOM và Dependency Scanning

Tuần 2 – Ngày 9

Bài này gộp 2 chủ đề: Supply Chain Attacks, SBOM & Dependency Scanning.

Mục tiêu học tập

  • Nắm các sự cố supply chain nổi tiếng: event-stream, ua-parser-js, node-ipc, xz utils
  • Hiểu các risk pattern: typosquatting, dependency confusion, malicious update
  • Biết vì sao lockfile (package-lock.json, yarn.lock, poetry.lock, go.sum) quan trọng
  • Biết signed commit (GPG, Sigstore), npm provenance, signing nói chung
  • Hiểu lý do vendor-a-copy, mirror registry nội bộ (Nexus, Artifactory)
  • Nắm khung SLSA (Supply-chain Levels for Software Artifacts) levels 1-4
  • Hiểu SBOM (Software Bill of Materials) là gì, vì sao đang trở thành yêu cầu compliance
  • So sánh hai chuẩn SBOM: SPDX và CycloneDX
  • Biết các công cụ sinh SBOM: syft, cdxgen, npm sbom, Trivy
  • Nắm pipeline dependency scanning: npm/pip-audit, Snyk, Dependabot, Renovate
  • Biết container image scanning: Trivy, Grype, Anchore
  • Hiểu CVE database, CVSS score, và khác biệt giữa severity và exploitability
  • Tích hợp scanning vào CI: fail build trên high-severity CVE, allowlist khi cần

Phần 1: Supply Chain Attacks

1. Supply chain attack là gì?

┌───────────┐│Yourapp│└─────┬─────┘│importsdepends┌─────────────┴──────────────┐▼▼┌─────────┐┌─────────┐│libA││libB││v1.2.0││v3.0.1│└────┬────┘└────┬────┘││┌─────────────┴─────┐┌────────────┴───┐▼▼▼▼┌───────┐┌───────┐┌───────┐┌───────┐│libC││libD││libE││libF│└───┬───┘└───┬───┘└───┬───┘└───┬───┘││││...transitivedependencies...│▼┌───────────┐│libZ││malicious│←chỉcần1deptrongchainbịcompromise└───────────┘→mãđộcchạytrongappcủabạn

Định nghĩa: tấn công nhắm vào một thành phần (dependency, build tool, CI runner, registry, maintainer account) trong chuỗi cung ứng phần mềm, không nhắm trực tiếp vào target. Một dependency compromise = mọi user của library đó bị ảnh hưởng.

Vì sao supply chain ngày càng nguy hiểm

  • App hiện đại có hàng ngàn transitive dependency (node_modules thường > 1000)
  • Maintainer của lib quan trọng thường là 1 người vô danh (xkcd 2347)
  • Update tự động (Dependabot, Renovate) merge các bản patch không ai review
  • Một npm install có thể chạy postinstall script tuỳ ý

2. Các sự cố nổi tiếng

event-stream (2018)

2011-2018: event-stream là package phổ biến trong npm (~2 triệu download/tuần)
2018-09:   Maintainer ban đầu chán, nhận offer từ user "right9ctrl" để hand over
2018-09:   right9ctrl publish version mới có dependency mới: flatmap-stream
2018-10:   flatmap-stream được publish (cùng người), chứa code obfuscated
2018-11:   Mã độc activate nếu app có dependency "copay" (Bitcoin wallet)
           → đánh cắp private key của ví Bitcoin
2018-11:   Phát hiện và rút package

Bài học: maintainer handover không có vetting + npm cho phép publish bất cứ version nào → một transitive dep có thể thay đổi hành vi gốc.

ua-parser-js (2021)

2021-10-22: Maintainer account npm bị takeover (password leak)
2021-10-22: Attacker publish 3 phiên bản malicious: 0.7.29, 0.8.0, 1.0.0
            preinstall script:
              - Windows: download crypto miner + password stealer
              - Linux: chỉ crypto miner
2021-10-23: User report, package được unpublished sau ~4 giờ
            Nhưng hàng triệu CI/install đã chạy postinstall script

Bài học: account takeover là vector chính → 2FA bắt buộc cho maintainer, và --ignore-scripts là tuyến phòng thủ.

node-ipc protestware (2022)

2022-03:  Maintainer RIAEvangelist (Brandon Nozaki Miller) cập nhật node-ipc
          Thêm code: nếu IP geolocation = Nga hoặc Belarus
            → overwrite mọi file trong project với emoji "❤️"
          Mục đích "protest war in Ukraine"
2022-03:  Hàng nghìn dev bị ảnh hưởng, không liên quan đến cuộc chiến
2022-03:  GitHub assign CVE-2022-23812 — mã độc, không phải "protest"

Bài học: ngay cả maintainer "có ý tốt" cũng có thể thành vector tấn công. Lockfile + audit là phòng thủ.

xz utils backdoor (2024) — gần như thành công

2021:     "Jia Tan" bắt đầu đóng góp cho xz utils (lib nén phổ biến)
2022-23:  Build trust qua hàng trăm PR hợp pháp
2024-02:  Maintainer chính bị áp lực để cho "Jia Tan" co-maintain
2024-02:  Jia Tan publish version 5.6.0 với backdoor:
          - Backdoor được inject qua build script (m4/build-to-host.m4)
          - Khi liblzma.so được load bởi sshd, hook RSA_public_decrypt
          - Cho phép attacker authenticate với SSH bằng chữ ký riêng
2024-03-29: Andres Freund (Microsoft) phát hiện do ssh login chậm 500ms hơn bình thường
2024-03-30: CVE-2024-3094 (CVSS 10.0)
            xz 5.6.0/5.6.1 bị thu hồi khỏi mọi distro

Backdoor đã có trong Fedora Rawhide, Debian Sid, Kali → suýt vào stable
Ước tính nếu vào stable: ~50% Linux server có thể bị backdoor SSH

Bài học đáng sợ:

  • Social engineering dài hạn (3 năm)
  • Backdoor được inject ở build time, không thấy trong source code Git
  • Phát hiện hoàn toàn nhờ luck (Andres ngẫu nhiên benchmark)
  • Even SLSA Level 3+ build có thể không bắt được nếu CI itself compromised

3. Risk patterns

3a. Typosquatting

Package thật:   express
Typo package:   experess, expres, expressjs, express-js

Package thật:   urllib3 (Python)
Typo package:   urlib3, url-lib3, urllib4

Package thật:   discord.js
Typo package:   discord-js, discordjs, dscord.js

Attacker publish package với tên gần giống package phổ biến, hi vọng dev gõ nhầm. Khi npm install chạy, postinstall script của typo package chạy → mã độc.

3b. Dependency confusion

2021: Alex Birsan demonstrate cách attack hơn 35 công ty lớn (Apple, Microsoft, ...)

Setup:
  Công ty có internal npm package: @mycompany/internal-utils (private registry)
  npm config có cả public registry và internal registry

Attack:
  Attacker publish package "@mycompany/internal-utils" lên npmjs.com public
  Với version số CAO hơn (vd: 99.0.0)

Khi build trong company:
  npm/yarn check cả 2 registry → thấy version 99.0.0 trên public cao hơn
  → install version public (malicious) thay vì internal

Phòng thủ:

  • Scope (@mycompany/) phải reserve trên npmjs.com public dù không publish
  • Config .npmrc chỉ định strict registry cho mỗi scope:
    @mycompany:registry=https://nexus.mycompany.com/
    
  • Dùng --scope mirror trong Artifactory/Nexus

3c. Malicious update / maintainer takeover

Vectors:
1. Account password reuse → leak từ data breach khác → attacker login
2. Phishing email "update your npm 2FA"
3. Maintainer hand over package cho stranger (event-stream)
4. Long-con social engineering (xz utils)
5. CI token leak → attacker publish version mới

Phòng thủ phía user:

  • Lockfile + không tự động update minor/patch trong production deploy
  • Pin exact version ("react": "18.2.0", không phải "^18.2.0")
  • Review changelog/release notes trước khi bump
  • Dùng npm audit signatures để verify npm provenance

4. Lockfile — không thể thiếu

Vì sao lockfile quan trọng

package.json (declared):
  "lodash": "^4.17.0"          ← caret: cho phép 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"
  }

Không có lockfile:

  • Hôm nay npm install → lodash 4.17.21
  • Mai maintainer publish 4.17.22 → npm install lấy 4.17.22 (khác build)
  • Reproducibility = 0, "works on my machine" trở lại

Có lockfile + integrity:

  • Mọi npm ci đều ra cùng version y hệt
  • Nếu tarball bị tamper (mã độc inject) → hash mismatch → install fail

Pin transitively

Lockfile pin mọi dep kể cả transitive:

package.json: chỉ khai báo top-level deps
package-lock.json: ghi mọi sub-dep với version + integrity hash
                   → hàng nghìn entries

Khi sub-dep release version mới với mã độc:
  npm install (without lockfile) → có thể lấy version mới
  npm ci (with lockfile)        → vẫn dùng version cũ đã pin

Lockfile theo từng ecosystem

ToolLockfileLệnh strict install
npmpackage-lock.jsonnpm ci
yarn classicyarn.lockyarn install --frozen-lockfile
yarn berryyarn.lockyarn install --immutable
pnpmpnpm-lock.yamlpnpm install --frozen-lockfile
Python pip-toolsrequirements.txt (pinned)pip install -r requirements.txt
Python Poetrypoetry.lockpoetry install --no-update
Python uvuv.lockuv sync --frozen
Gogo.sum (kèm go.mod)go build (đã verify hash mặc định)
CargoCargo.lockcargo build --locked
BundlerGemfile.lockbundle install --frozen
Composercomposer.lockcomposer install

Trong CI

# GitHub Actions — đúng cách
- name: Install deps (strict)
  run: npm ci   # ← KHÔNG dùng "npm install"
                # npm ci: fail nếu lockfile out of sync, không update lockfile

5. Signed commits và artifact signing

Vì sao sign?

Default git:
  Commit có field "author" và "committer" — nhưng đây là CHỈ STRING tự khai
  Tôi có thể tạo commit với author "Linus Torvalds <torvalds@kernel.org>"
  → mạo danh hoàn toàn

Signed commit:
  Commit kèm chữ ký số (GPG hoặc SSH key)
  Verify bằng public key → đảm bảo người sở hữu private key đã sign commit này

GPG signing

# Tạo GPG key
gpg --full-generate-key
# Chọn: RSA 4096 hoặc Ed25519, expiration 1-2 năm

# List key
gpg --list-secret-keys --keyid-format=long
# /home/user/.gnupg/secring.gpg
# sec  ed25519/3AA5C34371567BD2 2024-01-15

# Export public key, upload lên GitHub
gpg --armor --export 3AA5C34371567BD2

# Config git dùng key này
git config --global user.signingkey 3AA5C34371567BD2
git config --global commit.gpgsign true
git config --global tag.gpgsign true

# Commit sẽ tự sign từ giờ
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

Đơn giản hơn GPG, dùng SSH key sẵn có.

Sigstore — keyless signing

Vấn đề GPG/SSH key: key management cho hàng triệu maintainer là nightmare. Sigstore giải quyết bằng ephemeral key + OIDC:

Flow ký:
1. Maintainer login OIDC (Google/GitHub) → get JWT
2. cosign tạo ephemeral key pair (sống ~10 phút)
3. Fulcio (cert authority của Sigstore) cấp short-lived cert có embed JWT identity
4. Maintainer sign artifact bằng ephemeral key
5. Signature + cert + JWT → upload lên Rekor (transparency log, immutable)
6. Vứt private key

Verify:
- Đọc signature
- Verify cert chain về Fulcio root
- Kiểm tra Rekor log có entry tương ứng (timestamp đáng tin)
- Đọc identity từ cert: vd "ci@release.example.com from github.com/org/repo"
# Cài 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 (từ 2023): khi publish package từ GitHub Actions, npm CLI gọi Sigstore để sign và liên kết package với:

  • Workflow YAML đã build nó
  • Commit SHA
  • GitHub repo
# Trong CI:
npm publish --provenance --access public

# User verify:
npm audit signatures
# → "X packages have verified registry signatures"
# → "Y packages have verified attestations"

User có thể kiểm tra tarball thực sự được build từ source code claim, không phải laptop bí ẩn của attacker.

6. Vendor a copy / mirror registry

Vendoring

Thay vì depend vào registry public:
  Copy source code của dep vào repo của mình (thư mục vendor/)
  Build dùng code trong vendor/ thay vì download

Pros:
- Reproducible 100% — không depend registry uptime
- Audit được toàn bộ code đang chạy
- An toàn khỏi npm unpublish, registry compromise

Cons:
- Repo lớn lên nhiều (Go vendor có thể GB)
- Update dep = update vendor folder
- Diff PR thường khó review

Go có built-in support: go mod vendor. Một số project Node dùng patch-package cho vendoring có chọn lọc.

Mirror registry nội bộ

┌──────────────────────────────────────────────────────┐│InternalMirror(Nexus/Artifactory/Verdaccio)││││┌────────────────────────────────────────────────┐│││Proxycachecủanpmjs.com,PyPI,...││││-Cachemọipackageđãdownload││││-Allowlist:chỉchophéppackageđãvet││││-Scanvirus/malware││││-BlockversioncóCVE│││└────────────────────────────────────────────────┘│└──────────────────────────────────────────────────────┘▲│npminstall┌──────┴──────┐│Dev/CI│└─────────────┘
# .npmrc
registry=https://nexus.mycompany.com/repository/npm-proxy/
//nexus.mycompany.com/:_authToken=${NEXUS_TOKEN}

Pros:

  • Centralized control: 1 nơi đến vet/scan
  • Cache: tránh hit rate limit của npmjs
  • Audit: log mọi package download trong công ty
  • Khi npmjs down → nội bộ vẫn build được

7. SLSA framework

SLSA (Supply-chain Levels for Software Artifacts) — framework do Google + OpenSSF tạo ra, định 4 level tăng dần.

┌──────────────────────────────────────────────────────────────┐│SLSALevel1:Documentation││-Buildprocesscódocument││-Provenanceđượcsinhra(text)││-Mụcđích:traceability│├──────────────────────────────────────────────────────────────┤│SLSALevel2:Hostedbuildplatform││-Buildchạytrênplatformhosted(GitHubActions,GCB...)││-Provenanceđượcsinhtựđộngvàsigned││-Sourcecodecóversioncontrol│├──────────────────────────────────────────────────────────────┤│SLSALevel3:Hardenedbuilds││-Sourcevàbuildplatformmeetspecificstandards││-Provenancekhôngthểbịforgebởibuilduser││-Buildisolation(mỗibuildtrongenvsạch,ephemeral)│├──────────────────────────────────────────────────────────────┤│SLSALevel4:(deprecatedtrongSLSAv1.0,dồnvàoL3)││Originally:two-personreview,reproduciblebuild│└──────────────────────────────────────────────────────────────┘

Provenance là gì?

Một attestation (JSON) describe artifact được build như thế nào:

{
  "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 đã dùng */]
  }
}

Người dùng verify provenance để biết:

  • Artifact này được build từ commit nào
  • Workflow nào trigger build
  • Runner nào chạy build
  • Dependencies nào được dùng

Đạt SLSA L3 với GitHub Actions

# .github/workflows/release.yml
permissions:
  contents: write
  id-token: write   # cho 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 }}"

Workflow chuẩn này:

  • Build artifact trong VM ephemeral
  • Generate provenance signed bởi Sigstore (keyless)
  • Provenance bao gồm: commit SHA, workflow ref, runner, materials
  • User verify được "artifact này đến từ chính repo+workflow này"

Phần 2: SBOM & Dependency Scanning

1. SBOM là gì?

SBOM = "Software Bill of Materials"

Tương tự như:
- BOM (Bill of Materials) trong sản xuất ô-tô: danh sách linh kiện
- Nutrition label trên thực phẩm: liệt kê thành phần

SBOM cho phần mềm: liệt kê MỌI component (lib, framework, tool) trong
một artifact (binary, container image, source release), kèm:
- Tên component
- Version
- License
- Supplier
- Hash (cryptographic checksum)
- Quan hệ (cái nào depends on cái nào)

Vì sao SBOM trở thành bắt buộc

2020: SolarWinds attack — backdoor trong Orion software ảnh hưởng 18,000 tổ chức
2021: Log4Shell (CVE-2021-44228) — log4j 2.x có RCE, mọi app Java dùng log4j bị
      Câu hỏi đau: "tôi có dùng log4j không? phiên bản nào? ở đâu?"
      Nếu không có SBOM → phải scan thủ công hàng trăm app trong vài giờ

2021-05: Executive Order 14028 (US) — yêu cầu SBOM cho mọi software bán cho US gov
2023-Q4: EU Cyber Resilience Act (CRA) — yêu cầu SBOM cho hardware/software bán EU
2024:    SBOM bắt đầu trở thành mandatory với critical infra

Use case cụ thể

  1. Incident response: CVE mới công bố → query SBOM database → biết ngay app nào bị ảnh hưởng
  2. License compliance: đảm bảo không vô tình ship code GPL trong sản phẩm proprietary
  3. Supply chain audit: customer hỏi "bạn có dùng dep X không?" → trả lời chính xác
  4. Vulnerability management: continuous scan SBOM với CVE database

2. SPDX vs CycloneDX

SPDX (Software Package Data Exchange)

  • ISO/IEC 5962:2021 — chuẩn quốc tế
  • Maintained bởi Linux Foundation từ 2010
  • Định dạng: tag-value, JSON, YAML, RDF, spreadsheet
  • Mạnh về license metadata (SPDX License List là chuẩn 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

  • Bắt đầu từ OWASP, light-weight design for security use cases
  • Định dạng: JSON, XML, Protocol Buffers
  • Tích hợp tốt 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"]
    }
  ]
}

So sánh

Tiêu chíSPDXCycloneDX
Chuẩn hoáISO/IEC 5962:2021ECMA-424 (đang process)
MaintainerLinux FoundationOWASP
Focus chínhLicense complianceSecurity / vulnerability
FormatJSON, YAML, tag-value, RDFJSON, XML
PURL supportCó (từ 2.3)Có (native)
VEX integrationCóNative
Best forLegal/compliance teamDevSecOps pipeline

Trong thực tế: dùng cả hai khi cần. Hầu hết tool (syft, Trivy, cdxgen) có thể export cả hai format.

Package URL (PURL)

PURL chuẩn hoá cách định danh package giữa các ecosystem:

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

Format chung: pkg:<type>/<namespace>/<name>@<version>?<qualifiers>#<subpath>

3. Tạo SBOM với syft

syft là CLI phổ biến nhất, support ~30 ecosystem.

# Cài
brew install syft

# Scan directory (source code)
syft .

# Scan container image
syft alpine:3.19
syft docker.io/myorg/myapp:v1

# Scan và xuất 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

Output mẫu:

NAME              VERSION       TYPE
async             3.2.4         npm
express           4.18.2        npm
lodash            4.17.21       npm
...

Tạo SBOM với 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 cho container image

# Build image
docker build -t myapp:v1 .

# Sinh SBOM cho image (gồm cả OS package layer)
syft myapp:v1 -o spdx-json > myapp-sbom.json

# Attach SBOM vào image như attestation (cosign + Sigstore)
cosign attest --predicate myapp-sbom.json \
  --type spdxjson \
  myapp:v1

4. Dependency scanning — phát hiện CVE

CVE và CVSS basics

CVE-2021-44228(Log4Shell)│├──CVEID:CVE-<year>-<sequence>├──Môtả:ApacheLog4j2<2.15.0—JNDIlookupRCE├──CVSSv3.1score:10.0(CRITICAL)│├──AttackVector(AV):Network│├──AttackComplexity(AC):Low│├──PrivilegesRequired(PR):None│├──UserInteraction(UI):None│├──Scope:Changed│├──Confidentiality/Integrity/Availabilityimpact:High/High/High└──References:CISA,Apacheadvisory,exploitDB

Severity scale (CVSS v3.1)

ScoreSeverity
0.1 - 3.9Low
4.0 - 6.9Medium
7.0 - 8.9High
9.0 - 10.0Critical

Severity vs Exploitability — khác biệt quan trọng

CVE severity = "Worst case impact NẾU bị exploit"
Exploitability = "Khả năng thực sự exploit trong app của bạn"

Ví dụ: CVE critical trong dep, nhưng:
- App bạn không call function bị vulnerable → exploit không reach được
- App bạn không expose tới untrusted input → attacker không trigger được
- Dep chỉ chạy ở dev env (devDependency) → production không ảnh hưởng

→ Severity 10.0 không tự động = "patch ngay"
   Cần đánh giá exploitability cụ thể trong context

Tool theo 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

# Chi tiết
npm audit --json

# Chỉ fail trên 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 — chỉ flag vuln EXPLOITABLE

go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

# Khác biệt: govulncheck phân tích call graph
# Chỉ báo CVE nếu code thực sự GỌI function bị vulnerable
# → giảm false positive đáng kể

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 và Renovate

Dependabot

GitHub native, miễn phí cho mọi 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"]   # tạm hold major

  - package-ecosystem: docker
    directory: /
    schedule:
      interval: weekly

  - package-ecosystem: github-actions
    directory: /
    schedule:
      interval: monthly

Dependabot auto tạo PR khi:

  • Có security advisory (urgent, dùng dependabot/security-updates)
  • Có version mới (scheduled)

Renovate (Mend) — mạnh hơn

// 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"]
  }
}

Renovate ưu việt hơn Dependabot:

  • Group nhiều update vào 1 PR (giảm noise)
  • Auto-merge thông minh hơn
  • Schedule chi tiết hơn
  • Support nhiều ecosystem hơn (Terraform, Helm, Kustomize)

6. Container image scanning

Trivy — Aqua Security (open source, miễn phí)

brewinstalltrivy#Scanimagetrivyimagealpine:3.19trivyimagemyorg/myapp:v1#Output:#alpine:3.19(alpine3.19.0)#Total:3(UNKNOWN:0,LOW:0,MEDIUM:1,HIGH:2,CRITICAL:0)##┌─────────────┬───────────┬──────────┬─────────┬────────┐#│Library│VulnID│Severity│Version│Fixed│#├─────────────┼───────────┼──────────┼─────────┼────────┤#│libcrypto3│CVE-2024..│HIGH│3.1.4│3.1.5│#└─────────────┴───────────┴──────────┴─────────┴────────┘#Scanfilesystemtrivyfs.#ScanIaC(Terraform,K8s,Dockerfile)trivyconfig.#Scansecretstrivyfs--scannerssecret.#GenerateSBOMtrivyimage--formatspdx-jsonmyapp:v1>sbom.jsontrivyimage--formatcyclonedxmyapp:v1>sbom.cdx.json#ScanSBOMfile(offline)trivysbomsbom.cdx.json

Grype + syft (Anchore stack)

brew install grype

# Scan image
grype alpine:3.19
grype myapp:v1

# Scan từ SBOM (offline, fast)
syft myapp:v1 -o json > sbom.json
grype sbom:sbom.json

So sánh Trivy vs Grype

TrivyGrype
VendorAqua SecurityAnchore
LicenseApache 2.0Apache 2.0
Scan typesImage, filesystem, IaC, secret, SBOMImage, filesystem, SBOM
DB sourcesNVD, GHSA, OSV, distro advisoriesNVD, GHSA, distro advisories
SpeedNhanh, single binaryNhanh khi dùng với pre-built SBOM
IaC scanCó (Terraform, K8s, Dockerfile)Không (dùng anchore-engine riêng)

Khuyến nghị thực tế: Trivy cho one-stop scanning. syft + grype khi cần separation between SBOM generation và scanning (ví dụ: scan offline trong air-gapped env).

7. Tích hợp vào CI

GitHub Actions — fail build trên 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 build nếu có HIGH/CRITICAL
          ignore-unfixed: true     # skip CVE chưa có fix

      - 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 khi cần (.trivyignore)

# .trivyignore — ignore CVE chưa có fix hoặc không exploitable
# Mỗi CVE phải có comment lý do và ngày review lại

# CVE-2024-1234: chỉ ảnh hưởng function chúng ta không gọi (path X.Y.Z)
# Review lại: 2026-12-31
CVE-2024-1234

# CVE-2024-5678: dep chỉ dùng trong dev/test
CVE-2024-5678

Quy tắc allowlist:

  • Mọi entry phải có expiry date — không allowlist vĩnh viễn
  • Comment phải explain vì sao không fix, không chỉ "ignore"
  • Review allowlist hàng quý

Branch protection — block merge khi có critical CVE

GitHub repo Settings → Branches → Branch protection rules:
- Require status checks before merge:
  ✓ Security Scan / deps
  ✓ Security Scan / container

8. VEX — giảm noise

Vấn đề: scan tool báo 50 CVE — bao nhiêu thực sự ảnh hưởng?
        Triage thủ công tốn rất nhiều giờ engineer.

VEX (Vulnerability Exploitability eXchange): document machine-readable
nói "CVE X có trong dep Y nhưng KHÔNG affected vì lý do 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` chưa được dùng trong app. Verified bởi static analysis tool X, last reviewed 2025-06-15."
      }
    }
  ]
}

state có thể là:

  • resolved — đã patch
  • exploitable — confirm ảnh hưởng
  • not_affected — không ảnh hưởng (kèm justification)
  • false_positive — sai từ scan tool
  • in_triage — đang review

VEX cho phép automation: CI thấy CVE → check VEX → nếu có entry not_affected thì skip alert. Giảm false-positive fatigue.


Câu hỏi ôn tập

  1. event-stream và ua-parser-js bị compromise bằng cơ chế khác nhau như thế nào, và bài học cho dev là gì?

    Xem đáp án

    event-stream (2018): maintainer chuyển giao package cho người lạ ("right9ctrl"). Người này publish version mới với một transitive dep (flatmap-stream) chứa mã độc nhắm vào users của copay Bitcoin wallet. Vector: ownership transfer không vetting.

    ua-parser-js (2021): account npm của maintainer bị takeover (password leak). Attacker publish 3 phiên bản malicious với preinstall script tải crypto miner và password stealer. Vector: account compromise + thiếu 2FA.

    Bài học: (1) lockfile + audit transitive dep, (2) --ignore-scripts cho deps lạ, (3) đừng tự động update minor/patch trong production, (4) review changelog trước khi bump major, (5) khuyến khích maintainer bật 2FA (npm yêu cầu 2FA cho top package từ 2022).

  2. Vì sao lockfile (package-lock.json, poetry.lock, ...) lại quan trọng đặc biệt cho security, không chỉ reproducibility?

    Xem đáp án

    Lockfile pin exact version + integrity hash của mọi dep (cả top-level và transitive). Hệ quả security:

    (1) Pin version: nếu sub-dep release version mới chứa mã độc (như event-stream), build với lockfile cũ vẫn dùng version đã pin → không bị "auto-poisoned".

    (2) Integrity verification: lockfile lưu hash của tarball. Nếu registry/CDN trả về tarball khác (do compromise hoặc MITM), npm ci/pnpm install --frozen fail với hash mismatch.

    (3) Reproducibility for audit: SBOM + lockfile = biết chính xác mã nào chạy trong production tại mỗi commit, cần thiết để incident response khi CVE mới được công bố.

    Bắt buộc: dùng npm ci (không phải npm install) trong CI.

  3. Dependency confusion attack hoạt động thế nào, và làm sao phòng chống?

    Xem đáp án

    Cách hoạt động: công ty có internal package @mycompany/utils trong private registry. npm config có cả public + private registry. Attacker publish package cùng tên @mycompany/utils lên public npmjs.com với version cao hơn (vd 99.0.0). Khi npm install, npm resolve version cao nhất → lấy version public (malicious). Alex Birsan demo cách này crack 35+ công ty lớn (2021).

    Phòng chống: (1) Reserve scope @mycompany/* trên npmjs.com public dù không publish gì, (2) cấu hình .npmrc strict per-scope registry:

    @mycompany:registry=https://nexus.mycompany.com/
    

    (3) dùng mirror nội bộ làm registry duy nhất (Nexus, Artifactory) — proxy public packages, không cho phép resolve trực tiếp ra public.

  4. xz utils backdoor (2024) khác các sự cố trước ở điểm nào, và tại sao đáng sợ hơn?

    Xem đáp án

    Khác biệt: (1) Social engineering dài hạn (~3 năm) — "Jia Tan" đóng góp PR hợp pháp để xây dựng trust, sau đó được trao co-maintainer status. (2) Backdoor không nằm trong source code git mà inject ở build time qua m4 macro — nhìn source không thấy. (3) Target rất sâu: liblzma được linked bởi sshd (qua systemd notify), backdoor cho phép RSA-based SSH auth bypass.

    Đáng sợ vì: (a) detected gần như hoàn toàn nhờ luck (Andres Freund benchmark sshd, thấy chậm 500ms hơn bình thường). (b) Đã có trong rolling distro (Fedora Rawhide, Debian Sid) — suýt vào stable, ảnh hưởng hàng chục triệu server. (c) SLSA L3+ build có thể không bắt được, vì build platform compromised không phải vấn đề — source code itself contained backdoor logic.

    Bài học: cần (1) reproducible builds, (2) review build script không chỉ source code, (3) "burnout maintainer" là target chính — cần hỗ trợ tài chính/người cho maintainer của crit-deps (OpenSSF Alpha-Omega program).

  5. Sigstore/cosign khác GPG signing như thế nào, và vì sao nó dễ áp dụng hơn ở quy mô lớn?

    Xem đáp án

    GPG: maintainer giữ long-term private key (1-2 năm). Phân phối public key lên keyservers/GitHub. Verifier cần biết trước key fingerprint nào tin cậy. Vấn đề: key management khó (lost key, leak, rotation), discovery của public key chậm, mỗi project tự maintain web-of-trust.

    Sigstore (keyless): không có long-term private key. Mỗi lần sign: (1) login OIDC (Google/GitHub) → JWT, (2) Fulcio cấp ephemeral cert (sống ~10 phút) embed identity từ JWT, (3) sign bằng ephemeral key, (4) signature + cert + log entry → Rekor (transparency log immutable). Vứt private key sau khi sign.

    Lợi ích quy mô: (1) Không có long-term key để bị steal/leak, (2) identity = OIDC subject (vd "release@npm.example.com via github.com/org/repo workflow X") dễ verify hơn key fingerprint, (3) Rekor log immutable cho phép verify "package này đã được sign tại thời điểm X", chống backdating, (4) npm provenance, GitHub container signing đã dùng Sigstore mặc định — adoption rất nhanh.

  6. Vì sao SBOM trở thành yêu cầu compliance sau sự cố Log4Shell?

    Xem đáp án

    Khi Log4Shell (CVE-2021-44228) công bố tháng 12/2021, mọi tổ chức phải trả lời câu hỏi đơn giản: "Chúng ta có dùng log4j không? Phiên bản nào? Trong những app nào?" Không có SBOM, đội bảo mật phải scan thủ công hàng trăm app, mất nhiều ngày — trong khi attacker đã exploit hàng giờ sau khi PoC public.

    Hệ quả: US Executive Order 14028 (5/2021) yêu cầu SBOM cho mọi software bán cho US gov. EU Cyber Resilience Act (2024) tương tự. SBOM trở thành công cụ chuẩn để incident response, vulnerability management, license compliance, và supply chain audit. Với SBOM, query "ai dùng log4j 2.x" trở thành SQL one-liner thay vì hàng nghìn giờ effort.

  7. SPDX và CycloneDX khác nhau như thế nào, và khi nào nên dùng cái nào?

    Xem đáp án

    SPDX: chuẩn ISO/IEC 5962:2021, maintained bởi Linux Foundation từ 2010. Focus mạnh vào license compliance — SPDX License List là chuẩn license identifier toàn ngành. Định dạng đa dạng (JSON, YAML, RDF, tag-value).

    CycloneDX: bắt đầu từ OWASP, light-weight, focus mạnh vào security use case. Native support cho VEX (Vulnerability Exploitability eXchange). Định dạng JSON/XML.

    Khi nào dùng:

    • SPDX cho legal/compliance team (license audit, US gov submissions yêu cầu SPDX cụ thể)
    • CycloneDX cho DevSecOps pipeline (tích hợp scanning, VEX, dễ generate)
    • Thực tế: nhiều tool (syft, Trivy) export cả hai, vendor cả hai khi cần.
  8. Severity của CVE và exploitability trong app cụ thể khác nhau như thế nào? Cho ví dụ.

    Xem đáp án

    Severity (CVSS score): đo "worst case impact NẾU CVE bị exploit thành công". Tính trên kịch bản tổng quát, không biết context cụ thể của app.

    Exploitability trong app: thực tế CVE có reach được trong app của bạn không, dựa vào: (1) Code vulnerable có được CALL không (call graph analysis)? (2) Untrusted input có chạm tới function đó không? (3) Dep dùng ở runtime hay chỉ dev (devDependency)?

    Ví dụ: CVE-2024-XYZ trong thư viện image processing với CVSS 9.8 (Critical) — buffer overflow khi parse exotic image format. Nếu app của bạn chỉ dùng thư viện đó để resize JPG (function khác hoàn toàn) và không bao giờ gọi function vulnerable → exploitability = 0 trong thực tế, dù severity = 9.8.

    Đó là lý do tools như govulncheck (Go) phân tích call graph để chỉ flag CVE actually reachable, giảm false positive. VEX standard giúp document/communicate điều này.

  9. Vì sao Renovate hoặc Dependabot tự động merge minor/patch update vẫn cần caution?

    Xem đáp án

    Auto-merge minor/patch dựa trên giả định SemVer chuẩn: minor/patch chỉ thêm tính năng/sửa lỗi, không breaking. Vấn đề:

    (1) Maintainer không tuân thủ SemVer: nhiều lib break trong patch (đặc biệt npm ecosystem). Auto-merge có thể đẩy bug breaking lên prod.

    (2) Supply chain attack: event-stream và ua-parser-js bị compromise qua patch update. Nếu auto-merge mọi patch, mã độc vào production trong vài giờ.

    (3) Behavioral change: lib có thể đổi log format, metrics, default behavior trong "patch" — không breaking API nhưng break monitoring/operations.

    Best practice: (a) auto-merge chỉ devDependencies + types, (b) require human review cho runtime deps, (c) chạy full test suite + smoke test trước merge, (d) deploy auto-merge xuống staging trước, soak time vài giờ trước khi roll prod, (e) ưu tiên security alerts (faster lane) nhưng vẫn require status check.

  10. Container image scanning với Trivy phát hiện vuln ở những layer nào, và pattern "ignore-unfixed" có ý nghĩa gì?

Xem đáp án

Trivy scan nhiều layer trong image:

  • OS package layer: Alpine apk, Debian/Ubuntu dpkg, RHEL rpm — check distro advisories
  • Application dep layer: node_modules, Python packages, Go modules trong image — check NVD/GHSA
  • Secrets: hardcoded API key, private key trong layers
  • Misconfiguration: Dockerfile bad practices (USER root, COPY .env, etc.)

--ignore-unfixed: skip CVE chưa có version fix nào available. Lý do: nhiều CVE trong distro package (Alpine, Debian) công bố trước khi distro maintainer release patch. Báo những CVE này là "noise actionable" — bạn không thể fix bằng cách update vì update chưa tồn tại. Ignore cho đến khi có fix → giảm alert fatigue và tập trung vào CVE có thể action.

Cẩn thận: vẫn cần background scan định kỳ để biết khi nào fix có sẵn để upgrade.

Bài tập thực hành

Phần 1: Supply Chain Attacks

# 1. Tạo SBOM-like lockfile audit
cd your-project
npm ci
npm ls --all > deps-tree.txt
wc -l deps-tree.txt   # số lượng dep thực tế (thường > 1000)

# 2. Tìm dep transitive với version flagged
npm audit
npm audit --audit-level=high
npm audit signatures   # check npm provenance

# 3. Block scripts trong install
npm install --ignore-scripts
# Hoặc set permanently:
npm config set ignore-scripts true

# 4. Setup GPG signing cho git
gpg --full-generate-key   # chọn ed25519 hoặc 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 lên GitHub

# Commit test
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 container image với cosign
brew install cosign
docker build -t myorg/myapp:v1 .
docker push myorg/myapp:v1

# Keyless sign (cần OIDC từ GitHub Actions hoặc 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 với .npmrc
cat > .npmrc <<EOF
@mycompany:registry=https://nexus.mycompany.com/
//nexus.mycompany.com/:_authToken=\${NEXUS_TOKEN}
EOF

Phần 2: SBOM & Dependency Scanning

# 1. Tạo SBOM cho project hiện tại
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 với npm audit và pip-audit
npm audit --audit-level=high
# Nếu Python:
pip install pip-audit
pip-audit -r requirements.txt

# 3. Scan SBOM với grype (offline)
grype sbom:sbom.cdx.json

# 4. Build image và scan với 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 Dockerfile và IaC
trivy config Dockerfile
trivy config .   # scan toàn bộ Terraform/K8s nếu có

# 6. Setup 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 Trivy scan trong CI (.github/workflows/security.yml)
# Xem ví dụ trong phần 7 của bài

Tài liệu tham khảo


Bài tiếp theo →