# Sast Analyzer

> Static Application Security Testing with Semgrep, SonarQube, and AI-assisted vulnerability detection

- Skill: `lodetomasi/sast-analyzer` (Agent Skill)
- Install (CLI): `npx skillmds@latest add lodetomasi/sast-analyzer`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lodetomasi/sast-analyzer/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: lodetomasi (https://skillmd.com/u/lodetomasi)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/lodetomasi/sast-analyzer

---


# 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:

```bash
# 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:

```bash
# Run SonarQube scanner
sonar-scanner \
  -Dsonar.projectKey=myproject \
  -Dsonar.sources=. \
  -Dsonar.host.url=http://localhost:9000 \
  -Dsonar.login=<token>
```

### Language-Specific Tools

**Python: Bandit**
```bash
pip install bandit
bandit -r ./src -f json -o bandit-report.json
```

**JavaScript: ESLint Security**
```bash
npm install --save-dev eslint-plugin-security
eslint --plugin security src/
```

**Java: SpotBugs**
```bash
mvn spotbugs:check
```

## Common Vulnerabilities & Detection

### 1. SQL Injection

**Vulnerable Code (Python)**:
```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**:
```python
# ✅ 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**:
```yaml
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)**:
```javascript
// ❌ VULNERABLE: innerHTML with user input
document.getElementById('output').innerHTML = userInput;

// ❌ VULNERABLE: eval() with user data
eval(userInput);
```

**Secure Code**:
```javascript
// ✅ 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)**:
```python
# ❌ VULNERABLE: shell=True with user input
import subprocess
subprocess.run(f"ping -c 1 {user_host}", shell=True)
```

**Secure Code**:
```python
# ✅ SECURE: List of arguments, shell=False
import subprocess
subprocess.run(["ping", "-c", "1", user_host], shell=False)
```

### 4. Path Traversal

**Vulnerable Code (Java)**:
```java
// ❌ VULNERABLE: Direct file access
String filename = request.getParameter("file");
File file = new File("/uploads/" + filename);
```

**Secure Code**:
```java
// ✅ 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**:
```python
# ❌ VULNERABLE: Weak password validation
if user.password == input_password:
    login_success()

# ❌ VULNERABLE: Hardcoded credentials
password = "admin123"
```

**Secure Code**:
```python
# ✅ 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:
```bash
#!/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:
```python
#!/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:
```yaml
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
```yaml
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
```yaml
sast:
  stage: test
  image: returntocorp/semgrep
  script:
    - semgrep --config=auto --json > semgrep-report.json .
  artifacts:
    reports:
      sast: semgrep-report.json
```

## Best Practices

1. **Run SAST Early**: Integrate in CI/CD pipeline
2. **Custom Rules**: Define organization-specific patterns
3. **False Positive Management**: Tune rules, suppress known issues
4. **Combine Tools**: Use multiple tools for better coverage
5. **Developer Training**: Educate team on secure coding
6. **Regular Scans**: Daily scans on main branch
7. **Fix Critical First**: Prioritize ERROR > WARNING > INFO
8. **Track Metrics**: Monitor new vulnerabilities over time

## OWASP Top 10 Coverage

1. **A01 Broken Access Control** ✓
2. **A02 Cryptographic Failures** ✓
3. **A03 Injection** ✓ (SQL, Command, XSS)
4. **A04 Insecure Design** ✓
5. **A05 Security Misconfiguration** ✓
6. **A06 Vulnerable Components** (See: dependency-checker skill)
7. **A07 Authentication Failures** ✓
8. **A08 Software & Data Integrity** ✓
9. **A09 Security Logging Failures** ✓
10. **A10 SSRF** ✓

## Requirements

```bash
# 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

