Security Scanner
Performs static analysis of source code to identify common security vulnerabilities including injection flaws, broken authentication, insecure data handling, and OWASP Top 10 issues — with concrete mitigation recommendations.
When to Use
- User asks for a "security review" or "vulnerability scan"
- Code handles user input, authentication, file uploads, or external data
- A security audit is required before deployment
- User asks about OWASP compliance or CVE mitigation
- New endpoints are added that accept untrusted input
- Code accesses the filesystem, executes commands, or makes outbound requests based on user data
Process
Triage the attack surface — identify all points where untrusted input enters the system:
- HTTP request params, headers, cookies, bodies
- File uploads
- Environment variables or config files that might be user-controlled
- Data fetched from external APIs or databases
- Inter-process communication (IPC, message queues)
Scan for each vulnerability class using the following checklist:
A01 — Injection
- SQL: string concatenation into queries → require parameterized queries / prepared statements
- Command injection: user input in
exec(), system(), subprocess.call() shell=True
- LDAP/XPath/NoSQL injection: unescaped user input in query objects
- Template injection: user-controlled strings rendered by template engines
A02 — Broken Authentication
- Hardcoded credentials, tokens, or API keys in source
- Weak password hashing (MD5, SHA-1, unsalted) → require bcrypt/argon2
- JWT:
alg: none acceptance, weak secrets, missing expiry validation
- Session tokens not invalidated on logout
A03 — XSS (Cross-Site Scripting)
- User input rendered into HTML without escaping
innerHTML, document.write, eval() with dynamic content
dangerouslySetInnerHTML in React without sanitization
- Missing Content-Security-Policy header
A04 — Insecure Design / IDOR
- Object IDs fetched without ownership verification (e.g.,
GET /orders/:id without checking order.userId === req.user.id)
- Predictable resource identifiers (sequential integers) for sensitive resources
A05 — Security Misconfiguration
- Verbose error messages exposing stack traces to clients
- Debug mode enabled in production
- CORS configured with
* for authenticated routes
- Missing security headers (HSTS, X-Frame-Options, X-Content-Type-Options)
A06 — Path Traversal / File Inclusion
- User-controlled paths used in
fs.readFile(), open(), or includes
- No canonicalization or allowlist check before file access
A07 — Cryptographic Failures
- Sensitive data (PII, passwords, tokens) stored or transmitted in plaintext
- Weak algorithms: DES, RC4, MD5 for security purposes
- Insufficient entropy in token generation (
Math.random() for secrets)
A08 — Supply Chain / Prototype Pollution
merge(), extend(), or _.assign() with untrusted objects in JavaScript
- Unverified package installs or missing lockfiles
Rate each finding by severity:
- 🔴 Critical: immediate exploitability, data loss/RCE risk
- 🟠 High: exploitable with moderate effort
- 🟡 Medium: requires specific conditions or chaining
- 🟢 Low/Info: defense-in-depth improvements
Provide concrete mitigations with code snippets for each finding.
Summarize the overall security posture and list top 3 priority fixes.
Output Format
## Security Scan Report
**Files analyzed:** 8
**Findings:** 🔴 1 Critical · 🟠 2 High · 🟡 3 Medium · 🟢 2 Low
---
### 🔴 Critical — SQL Injection
**File:** `src/db/queries.js:34`
**CWE:** CWE-89
```js
// ❌ Vulnerable
const sql = `SELECT * FROM users WHERE username = '${req.body.username}'`;
Mitigation:
// ✅ Use parameterized query
const sql = 'SELECT * FROM users WHERE username = ?';
db.query(sql, [req.body.username]);
🟠 High — Missing Authorization Check (IDOR)
File: src/routes/documents.js:67
GET /documents/:id fetches the document by ID without verifying
the authenticated user owns it.
Mitigation:
const doc = await Document.findById(req.params.id);
if (!doc || doc.ownerId !== req.user.id) {
return res.status(404).json({ error: 'Not found' });
}
## Examples
### Example Input
```python
@app.route('/files')
def get_file():
filename = request.args.get('name')
with open(f'/var/app/uploads/{filename}') as f:
return f.read()
Example Output
🔴 Critical — Path Traversal (CWE-22)
An attacker can pass `name=../../etc/passwd` to read arbitrary files.
Mitigation:
```python
import os
UPLOAD_DIR = '/var/app/uploads'
@app.route('/files')
def get_file():
filename = request.args.get('name', '')
# Resolve and validate the path stays within UPLOAD_DIR
safe_path = os.path.realpath(os.path.join(UPLOAD_DIR, filename))
if not safe_path.startswith(UPLOAD_DIR + os.sep):
abort(400, 'Invalid filename')
with open(safe_path) as f:
return f.read()
## Boundaries
- Do NOT attempt to exploit vulnerabilities — analysis is static and advisory only.
- Do NOT flag false positives as confirmed vulnerabilities — use hedged language ("may be vulnerable", "appears to lack") when confidence is lower.
- Do NOT scan minified or transpiled output — request source files.
- Do NOT report findings in third-party library internals unless the library itself is known-vulnerable (check CVE databases separately).
- Do NOT recommend security-through-obscurity as a mitigation (renaming endpoints, hiding error codes, etc.).
- If code is incomplete (functions without implementations), note that the scan is partial and may miss issues in missing code.
- Always recommend defense-in-depth — even if one layer is secure, suggest additional controls where appropriate.
1---2name: security-scanner3description: Detects common vulnerability patterns (XSS, SQL injection, path traversal, IDOR) in source code and suggests mitigations. Invoke when asked to security review code, find vulnerabilities, check for injection risks, audit authentication, or assess OWASP compliance.4---56# Security Scanner78Performs static analysis of source code to identify common security vulnerabilities including injection flaws, broken authentication, insecure data handling, and OWASP Top 10 issues — with concrete mitigation recommendations.910## When to Use1112- User asks for a "security review" or "vulnerability scan"13- Code handles user input, authentication, file uploads, or external data14- A security audit is required before deployment15- User asks about OWASP compliance or CVE mitigation16- New endpoints are added that accept untrusted input17- Code accesses the filesystem, executes commands, or makes outbound requests based on user data1819## Process20211. **Triage the attack surface** — identify all points where untrusted input enters the system:22 - HTTP request params, headers, cookies, bodies23 - File uploads24 - Environment variables or config files that might be user-controlled25 - Data fetched from external APIs or databases26 - Inter-process communication (IPC, message queues)27282. **Scan for each vulnerability class** using the following checklist:2930 **A01 — Injection**31 - SQL: string concatenation into queries → require parameterized queries / prepared statements32 - Command injection: user input in `exec()`, `system()`, `subprocess.call()` shell=True33 - LDAP/XPath/NoSQL injection: unescaped user input in query objects34 - Template injection: user-controlled strings rendered by template engines3536 **A02 — Broken Authentication**37 - Hardcoded credentials, tokens, or API keys in source38 - Weak password hashing (MD5, SHA-1, unsalted) → require bcrypt/argon239 - JWT: `alg: none` acceptance, weak secrets, missing expiry validation40 - Session tokens not invalidated on logout4142 **A03 — XSS (Cross-Site Scripting)**43 - User input rendered into HTML without escaping44 - `innerHTML`, `document.write`, `eval()` with dynamic content45 - `dangerouslySetInnerHTML` in React without sanitization46 - Missing Content-Security-Policy header4748 **A04 — Insecure Design / IDOR**49 - Object IDs fetched without ownership verification (e.g., `GET /orders/:id` without checking `order.userId === req.user.id`)50 - Predictable resource identifiers (sequential integers) for sensitive resources5152 **A05 — Security Misconfiguration**53 - Verbose error messages exposing stack traces to clients54 - Debug mode enabled in production55 - CORS configured with `*` for authenticated routes56 - Missing security headers (HSTS, X-Frame-Options, X-Content-Type-Options)5758 **A06 — Path Traversal / File Inclusion**59 - User-controlled paths used in `fs.readFile()`, `open()`, or includes60 - No canonicalization or allowlist check before file access6162 **A07 — Cryptographic Failures**63 - Sensitive data (PII, passwords, tokens) stored or transmitted in plaintext64 - Weak algorithms: DES, RC4, MD5 for security purposes65 - Insufficient entropy in token generation (`Math.random()` for secrets)6667 **A08 — Supply Chain / Prototype Pollution**68 - `merge()`, `extend()`, or `_.assign()` with untrusted objects in JavaScript69 - Unverified package installs or missing lockfiles70713. **Rate each finding** by severity:72 - 🔴 Critical: immediate exploitability, data loss/RCE risk73 - 🟠 High: exploitable with moderate effort74 - 🟡 Medium: requires specific conditions or chaining75 - 🟢 Low/Info: defense-in-depth improvements76774. **Provide concrete mitigations** with code snippets for each finding.78795. **Summarize the overall security posture** and list top 3 priority fixes.8081## Output Format8283```84## Security Scan Report8586**Files analyzed:** 887**Findings:** 🔴 1 Critical · 🟠 2 High · 🟡 3 Medium · 🟢 2 Low8889---9091### 🔴 Critical — SQL Injection92**File:** `src/db/queries.js:34`93**CWE:** CWE-899495```js96// ❌ Vulnerable97const sql = `SELECT * FROM users WHERE username = '${req.body.username}'`;98```99100**Mitigation:**101```js102// ✅ Use parameterized query103const sql = 'SELECT * FROM users WHERE username = ?';104db.query(sql, [req.body.username]);105```106107---108109### 🟠 High — Missing Authorization Check (IDOR)110**File:** `src/routes/documents.js:67`111112`GET /documents/:id` fetches the document by ID without verifying113the authenticated user owns it.114115**Mitigation:**116```js117const doc = await Document.findById(req.params.id);118if (!doc || doc.ownerId !== req.user.id) {119 return res.status(404).json({ error: 'Not found' });120}121```122```123124## Examples125126### Example Input127```python128@app.route('/files')129def get_file():130 filename = request.args.get('name')131 with open(f'/var/app/uploads/{filename}') as f:132 return f.read()133```134135### Example Output136```137🔴 Critical — Path Traversal (CWE-22)138An attacker can pass `name=../../etc/passwd` to read arbitrary files.139140Mitigation:141```python142import os143144UPLOAD_DIR = '/var/app/uploads'145146@app.route('/files')147def get_file():148 filename = request.args.get('name', '')149 # Resolve and validate the path stays within UPLOAD_DIR150 safe_path = os.path.realpath(os.path.join(UPLOAD_DIR, filename))151 if not safe_path.startswith(UPLOAD_DIR + os.sep):152 abort(400, 'Invalid filename')153 with open(safe_path) as f:154 return f.read()155```156```157158## Boundaries159160- Do NOT attempt to exploit vulnerabilities — analysis is static and advisory only.161- Do NOT flag false positives as confirmed vulnerabilities — use hedged language ("may be vulnerable", "appears to lack") when confidence is lower.162- Do NOT scan minified or transpiled output — request source files.163- Do NOT report findings in third-party library internals unless the library itself is known-vulnerable (check CVE databases separately).164- Do NOT recommend security-through-obscurity as a mitigation (renaming endpoints, hiding error codes, etc.).165- If code is incomplete (functions without implementations), note that the scan is partial and may miss issues in missing code.166- Always recommend defense-in-depth — even if one layer is secure, suggest additional controls where appropriate.