Automated security vulnerability scanning that integrates with development workflow to detect and prevent security issues before deployment
Recommended settings for this hook
Automated accessibility testing and compliance checking for web applications following WCAG guidelines
Automatically formats code files after Claude writes or edits them using Prettier, Black, or other formatters
Automated database migration management with rollback capabilities, validation, and multi-environment support
The Security Scanner Hook provides comprehensive automated security analysis with real-time vulnerability detection and remediation suggestions.
## Core Security Features
### Vulnerability Scanning
- **Static Code Analysis** - Detect security flaws in source code
- **Dependency Scanning** - Check for vulnerable dependencies
- **Container Scanning** - Analyze Docker images for security issues
- **Infrastructure Scanning** - Validate cloud and infrastructure configurations
- **Secrets Detection** - Find hardcoded secrets and credentials
### Compliance Checking
- **OWASP Top 10** - Validate against common web vulnerabilities
- **CIS Benchmarks** - Check against security configuration standards
- **PCI DSS** - Payment card industry compliance validation
- **SOC 2** - Service organization control requirements
- **GDPR** - Data privacy and protection compliance
### Security Tools Integration
- **SAST Tools**: SonarQube, CodeQL, Semgrep, Bandit
- **DAST Tools**: OWASP ZAP, Burp Suite, Nikto
- **SCA Tools**: Snyk, WhiteSource, Black Duck
- **Container Security**: Trivy, Clair, Aqua Security
- **Cloud Security**: Prowler, Scout Suite, CloudSploit
## Configuration
### Basic Setup
```json
{
"securityScanner": {
"enabled": true,
"scanLevel": "medium",
"blockOnCritical": true,
"blockOnHigh": false,
"autoFix": false
},
"triggers": {
"onCommit": true,
"onPullRequest": true,
"onDeploy": true,
"scheduled": "daily"
},
"scanTypes": {
"static": true,
"dependencies": true,
"secrets": true,
"containers": true,
"infrastructure": false
}
}
```
### Advanced Configuration
```json
{
"securityScanner": {
"tools": {
"semgrep": {
"enabled": true,
"configPath": ".semgrep.yml",
"rules": ["auto", "security", "owasp-top-10"]
},
"snyk": {
"enabled": true,
"severity": ["high", "critical"],
"ignoreFile": ".snyk"
},
"trivy": {
"enabled": true,
"scanners": ["vuln", "secret", "config"]
}
},
"reporting": {
"format": ["json", "sarif", "html"],
"outputDir": "security-reports",
"uploadToDefectDojo": true
},
"compliance": {
"frameworks": ["owasp-top-10", "cis", "pci-dss"],
"severity": "medium",
"generateReport": true
}
}
}
```
## Security Scan Types
### Static Application Security Testing (SAST)
```javascript
// Example security issues detected
// SQL Injection vulnerability
function getUserData(userId) {
// ❌ Vulnerable code
const query = `SELECT * FROM users WHERE id = ${userId}`;
return database.query(query);
// ✅ Secure alternative
const query = 'SELECT * FROM users WHERE id = ?';
return database.query(query, [userId]);
}
// XSS vulnerability
function renderUserContent(content) {
// ❌ Vulnerable code
document.innerHTML = content;
// ✅ Secure alternative
document.textContent = content;
// or use a sanitization library
document.innerHTML = DOMPurify.sanitize(content);
}
// Insecure cryptography
function hashPassword(password) {
// ❌ Vulnerable code
return crypto.createHash('md5').update(password).digest('hex');
// ✅ Secure alternative
const salt = crypto.randomBytes(16);
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512');
}
```
### Dependency Vulnerability Scanning
```json
// Example vulnerability report
{
"vulnerabilities": [
{
"package": "lodash",
"version": "4.17.15",
"severity": "high",
"cve": "CVE-2020-8203",
"title": "Prototype Pollution",
"description": "lodash is vulnerable to prototype pollution",
"patchedVersions": [">=4.17.19"],
"recommendation": "Upgrade to lodash@4.17.19 or later"
},
{
"package": "express",
"version": "4.16.0",
"severity": "medium",
"cve": "CVE-2022-24999",
"title": "qs Prototype Pollution",
"description": "Express.js is vulnerable via qs dependency",
"patchedVersions": [">=4.17.3"],
"recommendation": "Upgrade to express@4.17.3 or later"
}
]
}
```
### Secrets Detection
```bash
# Example secrets detected in code
# ❌ Hardcoded API keys
const API_KEY = "sk-1234567890abcdef";
const DATABASE_URL = "mongodb://admin:password123@localhost:27017/db";
# ❌ AWS credentials
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
# ❌ JWT secrets
JWT_SECRET="my-super-secret-key-123"
# ✅ Secure alternatives
const API_KEY = process.env.API_KEY;
const DATABASE_URL = process.env.DATABASE_URL;
const JWT_SECRET = process.env.JWT_SECRET;
```
### Container Security Scanning
```dockerfile
# Dockerfile security issues detected
# ❌ Security issues
FROM ubuntu:latest
RUN apt-get update
USER root
EXPOSE 22
COPY --chown=root:root app.js /app/
# ✅ Secure version
FROM ubuntu:22.04
RUN apt-get update && apt-get upgrade -y && apt-get clean
RUN useradd -m appuser
USER appuser
EXPOSE 3000
COPY --chown=appuser:appuser app.js /app/
HEALTHCHECK --interval=30s --timeout=3s CMD curl -f http://localhost:3000/health
```
## Security Scanning Workflow
### Pre-commit Scanning
```bash
#!/bin/bash
# .git/hooks/pre-commit
echo "🔒 Running security scans..."
# Secrets detection
echo "Scanning for secrets..."
truffleHog --regex --entropy=False .
if [ $? -ne 0 ]; then
echo "❌ Secrets detected! Please remove before committing."
exit 1
fi
# Static analysis
echo "Running static security analysis..."
semgrep --config=auto --error
if [ $? -ne 0 ]; then
echo "❌ Security vulnerabilities detected!"
exit 1
fi
# Dependency check
echo "Checking dependencies..."
npm audit --audit-level=high
if [ $? -ne 0 ]; then
echo "❌ High-severity vulnerabilities in dependencies!"
echo "Run 'npm audit fix' to resolve."
exit 1
fi
echo "✅ Security scans passed!"
```
### CI/CD Pipeline Integration
```yaml
# GitHub Actions example
name: Security Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Semgrep
uses: returntocorp/semgrep-action@v1
with:
config: auto
- name: Run Snyk
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --severity-threshold=high
- name: Run Trivy
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload results to GitHub Security
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: 'trivy-results.sarif'
```
## Automated Remediation
### Dependency Updates
```javascript
// Automated dependency update script
const { exec } = require('child_process');
const semver = require('semver');
class SecurityAutoFixer {
async fixVulnerabilities() {
const auditResult = await this.runAudit();
const fixableVulns = this.getFixableVulnerabilities(auditResult);
for (const vuln of fixableVulns) {
if (vuln.severity === 'critical' || vuln.severity === 'high') {
await this.applyFix(vuln);
}
}
}
async applyFix(vulnerability) {
const { package, currentVersion, patchedVersion } = vulnerability;
// Check if update is safe (no breaking changes)
if (semver.satisfies(patchedVersion, `^${currentVersion}`)) {
console.log(`Updating ${package} from ${currentVersion} to ${patchedVersion}`);
await this.updatePackage(package, patchedVersion);
} else {
console.log(`Manual review required for ${package} update`);
await this.createPullRequest(vulnerability);
}
}
}
```
### Code Fixes
```javascript
// Automated code security fixes
const fixes = {
// Fix SQL injection
'sql-injection': (code) => {
return code.replace(
/database\.query\(`(.+?)\$\{(.+?)\}`\)/g,
"database.query('$1?', [$2])"
);
},
// Fix XSS vulnerabilities
'xss-vulnerability': (code) => {
return code.replace(
/\.innerHTML\s*=\s*(.+)/g,
'.textContent = $1'
);
},
// Fix insecure random
'insecure-random': (code) => {
return code.replace(
/Math\.random\(\)/g,
'crypto.randomBytes(4).readUInt32BE(0) / 0x100000000'
);
}
};
```
## Reporting & Monitoring
### Security Dashboard
```javascript
const securityMetrics = {
vulnerabilities: {
critical: 0,
high: 2,
medium: 5,
low: 12
},
compliance: {
'owasp-top-10': 'passing',
'cis-benchmarks': 'warning',
'pci-dss': 'passing'
},
trends: {
vulnerabilitiesFixed: 15,
newVulnerabilities: 3,
securityScore: 8.7
}
};
```
### Integration with Security Tools
```javascript
// DefectDojo integration
const defectDojoClient = {
async uploadResults(scanResults) {
const formData = new FormData();
formData.append('file', scanResults);
formData.append('scan_type', 'Semgrep JSON Report');
formData.append('engagement', this.engagementId);
return fetch(`${this.baseUrl}/api/v2/import-scan/`, {
method: 'POST',
headers: {
'Authorization': `Token ${this.apiKey}`
},
body: formData
});
}
};
// Slack notifications
const securityAlert = {
channel: '#security-alerts',
text: '🚨 Critical Security Vulnerability Detected',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: '*SQL Injection vulnerability found in user authentication*'
}
},
{
type: 'section',
fields: [
{
type: 'mrkdwn',
text: '*Severity:* Critical'
},
{
type: 'mrkdwn',
text: '*File:* auth/login.js:42'
}
]
},
{
type: 'actions',
elements: [
{
type: 'button',
text: {
type: 'plain_text',
text: 'View Details'
},
url: 'https://security-dashboard.example.com/vuln/123'
}
]
}
]
};
```