--- name: supply-chain-malware-analysis description: > Analyze software supply chain compromises including malicious packages, trojanized updates, and compromised build systems. Use when investigating suspected supply chain attacks involving package managers (PyPI, npm, RubyGems, Maven, NuGet), build system compromises, dependency confusion, or typosquatting. Supports diff analysis against known-good versions, install script inspection, and blast radius assessment. Works offline with local tools or online with package registry APIs. --- # Supply Chain Malware Analysis Systematically analyze suspected supply chain compromises to identify injected malicious code, assess the scope of compromise, and determine attack methodology. ## Prerequisites - **Linux**: `diff`, `strings`, `find`, `grep`, `jq`, `python3` - **Windows**: PowerShell 5.1+, Python 3.8+, WSL recommended - **Python packages**: `requests`, `packaging`, `toml`, `pyyaml` - **Optional**: `bandit` (Python security linter), `npm audit`, `pip-audit` - **API keys** (optional, for online enrichment): PyPI, npm registry, VirusTotal ## Step-by-Step Instructions ### Step 1: Identify the Compromised Package or Component Determine which software component has been compromised and gather initial intelligence. **Gather basic information:** ```bash # If you have the package archive file suspicious_package.* sha256sum suspicious_package.* # For Python packages (wheel/sdist) unzip -l suspicious_package.whl tar tzf suspicious_package.tar.gz # For npm packages tar tzf suspicious_package.tgz # For Ruby gems gem specification suspicious.gem ``` **Check package metadata:** ```bash # PyPI package info curl -s "https://pypi.org/pypi/PACKAGE_NAME/json" | jq '.info | {name, version, author, author_email, home_page}' # npm package info curl -s "https://registry.npmjs.org/PACKAGE_NAME" | jq '{name, description, "dist-tags", maintainers}' # Check for typosquatting - compare with legitimate package name python3 scripts/package_analyzer.py --check-typosquat SUSPICIOUS_NAME LEGITIMATE_NAME ``` **Using the package analyzer script:** ```bash python3 scripts/package_analyzer.py --package ./suspicious_package/ --type pypi python3 scripts/package_analyzer.py --package ./suspicious_package/ --type npm python3 scripts/package_analyzer.py --package ./suspicious_package/ --type gem ``` ### Step 2: Compare Against the Legitimate Version (Diff Analysis) Obtain a known-good version and perform detailed comparison. **Download the legitimate version:** ```bash # PyPI pip download PACKAGE_NAME==KNOWN_GOOD_VERSION --no-deps -d ./clean/ # npm npm pack PACKAGE_NAME@KNOWN_GOOD_VERSION # Ruby gem fetch PACKAGE_NAME -v KNOWN_GOOD_VERSION ``` **Run the diff analyzer:** ```bash python3 scripts/diff_analyzer.py --clean ./clean_package/ --suspect ./suspicious_package/ --output diff_report.json ``` **Manual diff for targeted files:** ```bash # Recursive diff, ignoring binary files diff -rq ./clean_package/ ./suspicious_package/ # Detailed diff of specific files diff -u ./clean_package/setup.py ./suspicious_package/setup.py diff -u ./clean_package/package.json ./suspicious_package/package.json ``` Look for: - New files not present in the legitimate version - Modified build/install scripts - Changes to dependency declarations - Obfuscated or encoded code blocks - New network-related imports ### Step 3: Identify Injected Code Examine the differences to isolate the malicious payload. **Search for common injection patterns:** ```bash # Base64-encoded payloads grep -rn "base64" ./suspicious_package/ grep -rn "b64decode\|atob\|Base64.decode" ./suspicious_package/ # Dynamic code execution grep -rn "eval\|exec\|compile\|__import__" ./suspicious_package/ grep -rn "Function(\|eval(\|new Function" ./suspicious_package/ # Network calls grep -rn "requests\.\|urllib\|http\.client\|socket\." ./suspicious_package/ grep -rn "fetch(\|XMLHttpRequest\|axios\|http\.get" ./suspicious_package/ # Environment/credential harvesting grep -rn "os\.environ\|process\.env\|ENV\[" ./suspicious_package/ grep -rn "\.aws/credentials\|\.ssh/\|\.npmrc\|\.pypirc" ./suspicious_package/ # Obfuscation indicators grep -rn "\\\\x[0-9a-f]\{2\}" ./suspicious_package/ grep -rn "chr(\|String\.fromCharCode" ./suspicious_package/ ``` **Using the package analyzer for deep inspection:** ```bash python3 scripts/package_analyzer.py --package ./suspicious_package/ --type pypi --deep-scan ``` ### Step 4: Analyze Build System Modifications Check for compromises in build configuration and install hooks. **Python packages:** ```bash # Check setup.py for malicious install commands cat ./suspicious_package/setup.py # Look for: cmdclass overrides, custom install commands, subprocess calls # Check setup.cfg and pyproject.toml cat ./suspicious_package/setup.cfg cat ./suspicious_package/pyproject.toml # Check for __init__.py modifications that run at import time find ./suspicious_package/ -name "__init__.py" -exec grep -l "exec\|eval\|subprocess\|os\.system" {} \; ``` **npm packages:** ```bash # Check package.json install scripts cat ./suspicious_package/package.json | jq '.scripts' # Look for: preinstall, install, postinstall scripts # Check for hidden scripts in nested dependencies find ./suspicious_package/ -name "package.json" -exec jq -r '.scripts // empty' {} \; ``` **Ruby gems:** ```bash # Check gemspec for extensions cat ./suspicious_package/*.gemspec # Look for: extensions, post_install_message, executables # Check extconf.rb cat ./suspicious_package/ext/*/extconf.rb ``` ### Step 5: Check Dependency Trees for Anomalies Analyze dependencies for injection points and dependency confusion risks. ```bash # Python - check for new or changed dependencies diff <(cat ./clean_package/setup.py | grep -A50 "install_requires") \ <(cat ./suspicious_package/setup.py | grep -A50 "install_requires") # npm - compare dependency trees diff <(cat ./clean_package/package.json | jq '.dependencies') \ <(cat ./suspicious_package/package.json | jq '.dependencies') # Check for internal/private package name conflicts (dependency confusion) python3 scripts/package_analyzer.py --check-dependency-confusion ./suspicious_package/ ``` **Look for:** - New dependencies not in the original package - Version pinning changes (removing upper bounds) - Dependencies with very similar names to legitimate packages - Dependencies from unusual registries ### Step 6: Identify Typosquatting Indicators Check if the package name exploits typos of popular packages. ```bash python3 scripts/package_analyzer.py --check-typosquat PACKAGE_NAME --database popular_packages # Manual checks # - Character substitution (e.g., reqeusts vs requests) # - Hyphen/underscore confusion (e.g., python-dateutil vs python_dateutil) # - Scope confusion (e.g., @types/lodash vs types-lodash) # - Version suffix (e.g., requests2, requests-latest) ``` ### Step 7: Analyze Installation Scripts Deeply examine what runs during package installation. ```bash # Extract and analyze install-time behavior python3 scripts/package_analyzer.py --package ./suspicious_package/ --analyze-install-scripts # Trace install behavior in sandbox (Linux) strace -f -e trace=network,file pip install --no-deps ./suspicious_package/ 2>&1 | tee install_trace.log # Monitor network during install tcpdump -i any -w install_capture.pcap & pip install --no-deps ./suspicious_package/ kill %1 ``` **Windows (PowerShell):** ```powershell # Monitor process creation during install $job = Start-Job { Get-WinEvent -FilterHashtable @{LogName='Security';Id=4688} -MaxEvents 1000 } pip install --no-deps .\suspicious_package\ $events = Receive-Job $job $events | Select-Object TimeCreated, @{N='Process';E={$_.Properties[5].Value}} ``` ### Step 8: Detect Data Exfiltration in Build Processes Identify mechanisms used to steal data during build/install. **Common exfiltration patterns to search for:** ```bash # DNS exfiltration grep -rn "dns\|nslookup\|dig\|socket\.gethostbyname\|resolve" ./suspicious_package/ # HTTP exfiltration grep -rn "requests\.post\|urllib.*POST\|http\.request.*POST\|fetch.*method.*POST" ./suspicious_package/ # Webhook/paste services grep -rn "webhook\|discord\|telegram\|pastebin\|transfer\.sh\|pipedream\|requestbin" ./suspicious_package/ # File collection before exfiltration grep -rn "glob\|walk\|listdir.*ssh\|listdir.*aws\|listdir.*config" ./suspicious_package/ ``` ### Step 9: Assess Blast Radius Determine the impact scope of the supply chain compromise. ```bash # Check download statistics (PyPI) curl -s "https://pypistats.org/api/packages/PACKAGE_NAME/recent" | jq # Check npm download statistics curl -s "https://api.npmjs.org/downloads/point/last-month/PACKAGE_NAME" | jq # Identify reverse dependencies # PyPI - packages that depend on the compromised package pip download PACKAGE_NAME --no-deps -d /tmp/check && \ grep -r "PACKAGE_NAME" /path/to/requirements/files/ # npm npm info PACKAGE_NAME dependents ``` **Document blast radius:** - Number of downloads during compromise window - Number of dependent packages - Types of affected systems (CI/CD, developer machines, production) - Data potentially exfiltrated (credentials, tokens, source code) - Recommended remediation actions ### Step 10: Generate Analysis Report Compile findings into an actionable report. ```bash python3 scripts/diff_analyzer.py --clean ./clean/ --suspect ./suspicious/ \ --output report.json --format detailed ``` **Report should include:** 1. Package identification (name, version, ecosystem) 2. Compromise timeline (when malicious version published) 3. Technical analysis of injected code 4. Data exfiltration targets and methods 5. Blast radius assessment 6. IOCs (domains, IPs, hashes, file paths) 7. Remediation steps for affected users ## Offline vs Online Mode - **Offline**: All diff analysis, code inspection, and install script analysis work without network access. Use local copies of packages. - **Online**: Package registry APIs provide metadata, download statistics, maintainer history, and version timelines. VirusTotal API enables hash lookups.