SAST Analyzer Skill
Overview
Comprehensive Static Application Security Testing (SAST) skill integrating industry-leading tools to detect vulnerabilities including SQL injection, XSS, SSRF, command injection, path traversal, and authentication bypass.
Capabilities
1. Vulnerability Detection
- SQL Injection: Detect unsafe query construction
- Cross-Site Scripting (XSS): Find unescaped user input
- SSRF (Server-Side Request Forgery): Identify unsafe URL handling
- Command Injection: Detect unsafe shell command execution
- Path Traversal: Find unsafe file path operations
- Authentication Bypass: Identify weak authentication logic
- Insecure Deserialization: Detect unsafe object deserialization
- Sensitive Data Exposure: Find hardcoded secrets, passwords
2. Code Quality & Security Standards
- OWASP Top 10 compliance
- CWE (Common Weakness Enumeration) mapping
- Security best practices validation
- Code smell detection
3. Multi-Language Support
- Python, Java, JavaScript/TypeScript
- Go, Ruby, PHP, C/C++
- Framework-specific rules (Django, Spring, React, etc.)
Tools Integration
Semgrep (Primary Tool)
Industry-leading SAST with AI-assisted analysis:
# Install Semgrep
pip install semgrep
# Run SAST scan with OWASP rules
semgrep --config=auto --sarif > results.sarif .
# Custom rules
semgrep --config=custom-rules/ src/
SonarQube
Enterprise-grade code quality + security:
# Run SonarQube scanner
sonar-scanner \
-Dsonar.projectKey=myproject \
-Dsonar.sources=. \
-Dsonar.host.url=http://localhost:9000 \
-Dsonar.login=<token>
Language-Specific Tools
Python: Bandit
pip install bandit
bandit -r ./src -f json -o bandit-report.json
JavaScript: ESLint Security
npm install --save-dev eslint-plugin-security
eslint --plugin security src/
Java: SpotBugs
mvn spotbugs:check
Common Vulnerabilities & Detection
1. SQL Injection
Vulnerable Code (Python):
# ❌ VULNERABLE: String concatenation
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
# ❌ VULNERABLE: String formatting
query = "SELECT * FROM users WHERE id = %s" % user_id
cursor.execute(query)
Secure Code:
# ✅ SECURE: Parameterized query
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_id,))
# ✅ SECURE: ORM
user = User.objects.get(id=user_id)
Semgrep Rule:
rules:
- id: sql-injection
patterns:
- pattern: execute($SQL)
- pattern-inside: $SQL = f"..."
message: SQL injection vulnerability
severity: ERROR
languages: [python]
2. Cross-Site Scripting (XSS)
Vulnerable Code (JavaScript):
// ❌ VULNERABLE: innerHTML with user input
document.getElementById('output').innerHTML = userInput;
// ❌ VULNERABLE: eval() with user data
eval(userInput);
Secure Code:
// ✅ SECURE: textContent (auto-escapes)
document.getElementById('output').textContent = userInput;
// ✅ SECURE: DOMPurify sanitization
document.getElementById('output').innerHTML = DOMPurify.sanitize(userInput);
3. Command Injection
Vulnerable Code (Python):
# ❌ VULNERABLE: shell=True with user input
import subprocess
subprocess.run(f"ping -c 1 {user_host}", shell=True)
Secure Code:
# ✅ SECURE: List of arguments, shell=False
import subprocess
subprocess.run(["ping", "-c", "1", user_host], shell=False)
4. Path Traversal
Vulnerable Code (Java):
// ❌ VULNERABLE: Direct file access
String filename = request.getParameter("file");
File file = new File("/uploads/" + filename);
Secure Code:
// ✅ SECURE: Validate and normalize path
String filename = request.getParameter("file");
Path basePath = Paths.get("/uploads/").toRealPath();
Path filePath = basePath.resolve(filename).normalize();
if (!filePath.startsWith(basePath)) {
throw new SecurityException("Invalid path");
}
5. Insecure Authentication
Vulnerable Code:
# ❌ VULNERABLE: Weak password validation
if user.password == input_password:
login_success()
# ❌ VULNERABLE: Hardcoded credentials
password = "admin123"
Secure Code:
# ✅ SECURE: bcrypt hashing
import bcrypt
if bcrypt.checkpw(input_password.encode(), user.password_hash):
login_success()
# ✅ SECURE: Environment variables
password = os.environ.get('DB_PASSWORD')
Integration Scripts
sast_scan.sh
Automated SAST scanning:
#!/bin/bash
# Comprehensive SAST scan
PROJECT_DIR=${1:-.}
REPORT_DIR="security-reports"
mkdir -p $REPORT_DIR
echo "=== Running SAST Analysis ==="
# 1. Semgrep scan
echo "Running Semgrep..."
semgrep --config=auto --json --output=$REPORT_DIR/semgrep.json $PROJECT_DIR
# 2. Bandit (Python)
if [ -d "$PROJECT_DIR/python" ] || [ -f "$PROJECT_DIR/setup.py" ]; then
echo "Running Bandit (Python)..."
bandit -r $PROJECT_DIR -f json -o $REPORT_DIR/bandit.json
fi
# 3. ESLint Security (JavaScript)
if [ -f "$PROJECT_DIR/package.json" ]; then
echo "Running ESLint Security..."
npm run lint:security || true
fi
# 4. SpotBugs (Java)
if [ -f "$PROJECT_DIR/pom.xml" ]; then
echo "Running SpotBugs (Java)..."
mvn spotbugs:check
fi
echo "=== SAST Analysis Complete ==="
echo "Reports saved to: $REPORT_DIR/"
vulnerability_summarizer.py
Parse and summarize findings:
#!/usr/bin/env python3
import json
from collections import defaultdict
def summarize_semgrep_results(json_file):
"""Summarize Semgrep findings by severity"""
with open(json_file) as f:
data = json.load(f)
findings = defaultdict(list)
for result in data.get('results', []):
severity = result.get('extra', {}).get('severity', 'INFO')
findings[severity].append({
'rule': result['check_id'],
'message': result['extra']['message'],
'file': result['path'],
'line': result['start']['line']
})
print("=== SAST Vulnerability Summary ===\n")
for severity in ['ERROR', 'WARNING', 'INFO']:
if severity in findings:
print(f"\n{severity}: {len(findings[severity])} findings")
for finding in findings[severity][:5]: # Show first 5
print(f" • [{finding['rule']}] {finding['file']}:{finding['line']}")
print(f" {finding['message']}")
# Severity score
score = len(findings['ERROR']) * 10 + len(findings['WARNING']) * 5 + len(findings['INFO'])
print(f"\n=== Security Score: {max(0, 100 - score)}/100 ===")
summarize_semgrep_results('security-reports/semgrep.json')
custom_rules.yaml
Custom Semgrep rules:
rules:
- id: hardcoded-secret
patterns:
- pattern: $VAR = "..."
- metavariable-regex:
metavariable: $VAR
regex: (password|secret|api_key|token)
message: Hardcoded secret detected
severity: ERROR
languages: [python, javascript, java]
- id: unsafe-file-open
patterns:
- pattern: open($PATH, ...)
- pattern-not: open($PATH, 'r')
message: Unsafe file operation - validate path
severity: WARNING
languages: [python]
- id: missing-csrf-protection
patterns:
- pattern: @app.route(...)
- pattern-not: @csrf.exempt
- pattern-not-inside: methods=['GET', 'HEAD', 'OPTIONS']
message: Missing CSRF protection on POST endpoint
severity: ERROR
languages: [python]
CI/CD Integration
GitHub Actions
name: SAST Security Scan
on: [push, pull_request]
jobs:
semgrep:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Semgrep
uses: returntocorp/semgrep-action@v1
with:
config: >-
p/security-audit
p/owasp-top-ten
GitLab CI
sast:
stage: test
image: returntocorp/semgrep
script:
- semgrep --config=auto --json > semgrep-report.json .
artifacts:
reports:
sast: semgrep-report.json
Best Practices
- Run SAST Early: Integrate in CI/CD pipeline
- Custom Rules: Define organization-specific patterns
- False Positive Management: Tune rules, suppress known issues
- Combine Tools: Use multiple tools for better coverage
- Developer Training: Educate team on secure coding
- Regular Scans: Daily scans on main branch
- Fix Critical First: Prioritize ERROR > WARNING > INFO
- Track Metrics: Monitor new vulnerabilities over time
OWASP Top 10 Coverage
- A01 Broken Access Control ✓
- A02 Cryptographic Failures ✓
- A03 Injection ✓ (SQL, Command, XSS)
- A04 Insecure Design ✓
- A05 Security Misconfiguration ✓
- A06 Vulnerable Components (See: dependency-checker skill)
- A07 Authentication Failures ✓
- A08 Software & Data Integrity ✓
- A09 Security Logging Failures ✓
- A10 SSRF ✓
Requirements
# Semgrep
pip install semgrep
# Python tools
pip install bandit safety
# JavaScript tools
npm install -g eslint eslint-plugin-security
# Java tools
# SpotBugs (Maven/Gradle plugin)
Metrics to Track
- Critical vulnerabilities: 0 tolerance
- High severity: Fix within 7 days
- Medium severity: Fix within 30 days
- False positive rate: < 20%
- Scan coverage: 100% of codebase
- Time to fix: Average days to remediate