Security Review
SentryOfficialPublished by Sentry
- Skill
- Review and audit
- Security
- CC-BY-SA-4.0
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Security Review skill provides a structured approach to auditing code for security vulnerabilities. It emphasizes deep research into data flow and context to distinguish between theoretical risks and truly exploitable issues. By focusing on attacker-controlled inputs and framework-specific mitigations, it reduces false positives and ensures that reported findings are actionable and high-confidence.
What it does
- Performs systematic security audits on provided code snippets or files.
- Traces data flow to confirm if inputs are attacker-controlled or server-controlled.
- Evaluates code against common vulnerability patterns like injection, XSS, and authentication flaws.
- Filters out false positives by checking for framework-level protections and sanitization.
- Categorizes findings by severity and confidence levels.
- Provides a standardized reporting format for identified vulnerabilities.
When to use it
- When you need to audit code for potential security vulnerabilities.
- When performing an OWASP-based security review.
- When you need to verify if a specific code pattern is exploitable.
- When checking for common security issues like SQL injection, XSS, or insecure authentication.
Advantages
- Reduces noise by filtering out theoretical issues and server-controlled configurations.
- Ensures high-confidence reporting by requiring codebase research before flagging.
- Provides clear, actionable remediation advice for identified vulnerabilities.
- Standardizes the security review process across different codebases.
Usage examples
- “Perform a security review on this file: [code snippet]”
- The agent will analyze the code, trace the data flow of inputs, and provide a report of any high-confidence vulnerabilities found, or state that none were identified.
- “Check this API endpoint for potential injection vulnerabilities.”
- The agent will examine the endpoint's input handling and database queries to determine if user input is properly parameterized or sanitized.
- “Audit this authentication logic for security issues.”
- The agent will review the authentication implementation against best practices, such as password storage algorithms and brute-force protections.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/getsentry/security-review/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip security-review.zip -d .agents/skills
Documentation by Sentry
<!-- Reference material based on OWASP Cheat Sheet Series (CC BY-SA 4.0) https://cheatsheetseries.owasp.org/ -->
Security Review Skill
Identify exploitable security vulnerabilities in code. Report only HIGH CONFIDENCE findings—clear vulnerable patterns with attacker-controlled input.
Scope: Research vs. Reporting
CRITICAL DISTINCTION:
Report on: Only the specific file, diff, or code provided by the user
Research: The ENTIRE codebase to build confidence before reporting
Before flagging any issue, you MUST research the codebase to understand:
Where does this input actually come from? (Trace data flow)
Is there validation/sanitization elsewhere?
How is this configured? (Check settings, config files, middleware)
What framework protections exist?
Do NOT report issues based solely on pattern matching. Investigate first, then report only what you're confident is exploitable.
Confidence Levels
| Level | Criteria | Action |
|---|---|---|
| HIGH | Vulnerable pattern + attacker-controlled input confirmed | Report with severity |
| MEDIUM | Vulnerable pattern, input source unclear | Note as "Needs verification" |
| LOW | Theoretical, best practice, defense-in-depth | Do not report |
Do Not Flag
General Rules
Test files (unless explicitly reviewing test security)
Dead code, commented code, documentation strings
Patterns using constants or server-controlled configuration
Code paths that require prior authentication to reach (note the auth requirement instead)
Server-Controlled Values (NOT Attacker-Controlled)
These are configured by operators, not controlled by attackers:
| Source | Example | Why It's Safe |
|---|---|---|
| Django settings | settings.API_URL, settings.ALLOWED_HOSTS | Set via config/env at deployment |
| Environment variables | os.environ.get('DATABASE_URL') | Deployment configuration |
| Config files | config.yaml, app.config['KEY'] | Server-side files |
| Framework constants | django.conf.settings.* | Not user-modifiable |
| Hardcoded values | BASE_URL = "https://api.internal" | Compile-time constants |
SSRF Example - NOT a vulnerability:
# SAFE: URL comes from Django settings (server-controlled)
response = requests.get(f"{settings.SEER_AUTOFIX_URL}{path}")SSRF Example - IS a vulnerability:
# VULNERABLE: URL comes from request (attacker-controlled)
response = requests.get(request.GET.get('url'))Framework-Mitigated Patterns
Check language guides before flagging. Common false positives:
| Pattern | Why It's Usually Safe |
|---|---|
Django {{ variable }} | Auto-escaped by default |
React {variable} | Auto-escaped by default |
Vue {{ variable }} | Auto-escaped by default |
User.objects.filter(id=input) | ORM parameterizes queries |
cursor.execute("...%s", (input,)) | Parameterized query |
innerHTML = "<b>Loading...</b>" | Constant string, no user input |
Only flag these when:
Django:
{{ var|safe }},{% autoescape off %},mark_safe(user_input)React:
dangerouslySetInnerHTML={{__html: userInput}}Vue:
v-html="userInput"ORM:
.raw(),.extra(),RawSQL()with string interpolation
Review Process
1. Detect Context
What type of code am I reviewing?
| Code Type | Load These References |
|---|---|
| API endpoints, routes | authorization.md, authentication.md, injection.md |
| Django/DRF views, permission classes, object-level access | Use the django-access-review skill if available for access control; otherwise authorization.md |
| Frontend, templates | xss.md, csrf.md, modern-threats.md (DOM clobbering, prototype pollution) |
| File handling, uploads | file-security.md |
| Crypto, secrets, tokens | cryptography.md, data-protection.md |
| Data serialization | deserialization.md |
| External requests | ssrf.md |
| Business workflows | business-logic.md |
| GraphQL, REST design | api-security.md |
| Config, headers, CORS | misconfiguration.md |
| CI/CD, dependencies | supply-chain.md |
| Error handling | error-handling.md |
| Audit, logging | logging.md |
Object merging/cloning, __proto__, DOM id/name lookups, WebSocket handlers, LLM prompt construction | modern-threats.md |
2. Load Language Guide
Based on file extension or imports:
| Indicators | Guide |
|---|---|
.py, django, flask, fastapi | languages/python.md |
.js, .ts, express, react, vue, next | languages/javascript.md |
For other languages there is no dedicated guide; rely on the references/ files and verify framework protections directly in the codebase.
3. Load Infrastructure Guide (if applicable)
| File Type | Guide |
|---|---|
Dockerfile, .dockerignore | infrastructure/docker.md |
| GitHub Actions workflows | Use the gha-security-review skill if available; otherwise references/supply-chain.md |
| Other CI/CD pipelines, lockfiles, package manifests | references/supply-chain.md |
4. Research Before Flagging
For each potential issue, research the codebase to build confidence:
Where does this value actually come from? Trace the data flow.
Is it configured at deployment (settings, env vars) or from user input?
Is there validation, sanitization, or allowlisting elsewhere?
What framework protections apply?
Only report issues where you have HIGH confidence after understanding the broader context.
5. Verify Exploitability
For each potential finding, confirm:
Is the input attacker-controlled?
| Attacker-Controlled (Investigate) | Server-Controlled (Usually Safe) |
|---|---|
request.GET, request.POST, request.args | settings.X, app.config['X'] |
request.json, request.data, request.body | os.environ.get('X') |
request.headers (most headers) | Hardcoded constants |
request.cookies (unsigned) | Internal service URLs from config |
URL path segments: /users/<id>/ | Database content from admin/system |
| File uploads (content and names) | Signed session data |
| Database content from other users | Framework settings |
| WebSocket messages |
Does the framework mitigate this?
Check language guide for auto-escaping, parameterization
Check for middleware/decorators that sanitize
Is there validation upstream?
Input validation before this code
Sanitization libraries (DOMPurify, bleach, etc.)
6. Report HIGH Confidence Only
Skip theoretical issues. Report only what you've confirmed is exploitable after research.
Severity Classification
| Severity | Impact | Examples |
|---|---|---|
| Critical | Direct exploit, severe impact, no auth required | RCE, SQL injection to data, auth bypass, hardcoded secrets |
| High | Exploitable with conditions, significant impact | Stored XSS, SSRF to metadata, IDOR to sensitive data |
| Medium | Specific conditions required, moderate impact | Reflected XSS, CSRF on state-changing actions, path traversal |
| Low | Defense-in-depth, minimal direct impact | Missing headers, verbose errors, weak algorithms in non-critical context |
Quick Patterns Reference
Always Flag (Critical)
eval(user_input) # Any language
exec(user_input) # Any language
pickle.loads(user_data) # Python
yaml.load(user_data) # Python (not safe_load)
unserialize($user_data) # PHP
deserialize(user_data) # Java ObjectInputStream
shell=True + user_input # Python subprocess
child_process.exec(user) # Node.jsAlways Flag (High)
innerHTML = userInput # DOM XSS
dangerouslySetInnerHTML={user} # React XSS
v-html="userInput" # Vue XSS
f"SELECT * FROM x WHERE {user}" # SQL injection
`SELECT * FROM x WHERE ${user}` # SQL injection
os.system(f"cmd {user_input}") # Command injectionAlways Flag (Secrets)
password = "hardcoded"
api_key = "sk-..."
AWS_SECRET_ACCESS_KEY = "..."
private_key = "-----BEGIN"Check Context First (MUST Investigate Before Flagging)
# SSRF - ONLY if URL is from user input, NOT from settings/config
requests.get(request.GET['url']) # FLAG: User-controlled URL
requests.get(settings.API_URL) # SAFE: Server-controlled config
requests.get(f"{settings.BASE}/{x}") # CHECK: Is 'x' user input?
# Path traversal - ONLY if path is from user input
open(request.GET['file']) # FLAG: User-controlled path
open(settings.LOG_PATH) # SAFE: Server-controlled config
open(f"{BASE_DIR}/{filename}") # CHECK: Is 'filename' user input?
# Open redirect - ONLY if URL is from user input
redirect(request.GET['next']) # FLAG: User-controlled redirect
redirect(settings.LOGIN_URL) # SAFE: Server-controlled config
# Weak crypto - ONLY if used for security purposes
hashlib.md5(file_content) # SAFE: File checksums, caching
hashlib.md5(password) # FLAG: Password hashing
random.random() # SAFE: Non-security uses (UI, sampling)
random.random() for token # FLAG: Security tokens need secrets moduleOutput Format
## Security Review: [File/Component Name]
### Summary
- **Findings**: X (Y Critical, Z High, ...)
- **Risk Level**: Critical/High/Medium/Low
- **Confidence**: High/Mixed
### Findings
#### [VULN-001] [Vulnerability Type] (Severity)
- **Location**: `file.py:123`
- **Confidence**: High
- **Issue**: [What the vulnerability is]
- **Impact**: [What an attacker could do]
- **Evidence**:
```python
[Vulnerable code snippet]Fix: [How to remediate]
Needs Verification
[VERIFY-001] [Potential Issue]
Location:
file.py:456Question: [What needs to be verified]
If no vulnerabilities found, state: "No high-confidence vulnerabilities identified."
---
## Reference Files
### Core Vulnerabilities (`references/`)
| File | Covers |
|------|--------|
| `injection.md` | SQL, NoSQL, OS command, LDAP, template injection |
| `xss.md` | Reflected, stored, DOM-based XSS |
| `authorization.md` | Authorization, IDOR, privilege escalation |
| `authentication.md` | Sessions, credentials, password storage |
| `cryptography.md` | Algorithms, key management, randomness |
| `deserialization.md` | Pickle, YAML, Java, PHP deserialization |
| `file-security.md` | Path traversal, uploads, XXE |
| `ssrf.md` | Server-side request forgery |
| `csrf.md` | Cross-site request forgery |
| `data-protection.md` | Secrets exposure, PII, logging |
| `api-security.md` | REST, GraphQL, mass assignment |
| `business-logic.md` | Race conditions, workflow bypass |
| `modern-threats.md` | Prototype pollution, LLM injection, WebSocket |
| `misconfiguration.md` | Headers, CORS, debug mode, defaults |
| `error-handling.md` | Fail-open, information disclosure |
| `supply-chain.md` | Dependencies, build security |
| `logging.md` | Audit failures, log injection |
### Language Guides (`languages/`)
- `python.md` - Django, Flask, FastAPI patterns
- `javascript.md` - Node, Express, React, Vue, Next.js
### Infrastructure (`infrastructure/`)
- `docker.md` - Container securityFiles
- ATTRIBUTION.mdAdded by AutoGineer902 B
- LICENSE884 B
- SKILL.md11.5 KiB
- SPEC.md8.8 KiB
- infrastructure/docker.md9.2 KiB
- languages/javascript.md9.8 KiB
- languages/python.md9.3 KiB
- references/api-security.md12.4 KiB
- references/authentication.md8.9 KiB
- references/authorization.md9.8 KiB
- references/business-logic.md12.4 KiB
- references/cryptography.md8.5 KiB
- references/csrf.md9.7 KiB
- references/data-protection.md9.3 KiB
- references/deserialization.md10.0 KiB
- references/error-handling.md11.4 KiB
- references/file-security.md12.1 KiB
- references/injection.md6.7 KiB
- references/logging.md11.7 KiB
- references/misconfiguration.md10.1 KiB
- references/modern-threats.md13.0 KiB
- references/ssrf.md10.5 KiB
- references/supply-chain.md8.9 KiB
- references/xss.md7.4 KiB
references/csrf.md
Cross-Site Request Forgery (CSRF) Prevention Reference
Overview
CSRF attacks trick authenticated users into performing unintended actions by exploiting the browser's automatic credential transmission. The attack works because browsers automatically include cookies with requests to a domain, regardless of the request's origin.
Attack Scenario
<!-- Attacker's page -->
<img src="https://bank.com/transfer?to=attacker&amount=10000">
<!-- Or form submission -->
<form action="https://bank.com/transfer" method="POST" id="evil">
<input name="to" value="attacker">
<input name="amount" value="10000">
</form>
<script>document.getElementById('evil').submit();</script>When a logged-in user visits the attacker's page, their browser makes the request with their session cookie.
Primary Defenses
1. Synchronizer Token Pattern
Generate and validate a unique token per session.
import secrets
# Generate token on session creation
def create_csrf_token(session_id):
token = secrets.token_urlsafe(32)
store_csrf_token(session_id, token)
return token
# Include in forms
def render_form():
token = get_csrf_token(session.id)
return f'''
<form method="POST">
<input type="hidden" name="csrf_token" value="{token}">
<!-- form fields -->
</form>
'''
# Validate on submission
def validate_csrf():
submitted_token = request.form.get('csrf_token')
stored_token = get_csrf_token(session.id)
if not submitted_token or not secrets.compare_digest(submitted_token, stored_token):
raise CSRFValidationError()2. Double Submit Cookie Pattern (Stateless)
Use a cryptographically signed token that doesn't require server-side storage.
import hmac
import hashlib
import time
SECRET_KEY = os.environ['CSRF_SECRET']
def generate_csrf_token(session_id):
"""Generate signed token tied to session."""
timestamp = int(time.time())
message = f"{session_id}:{timestamp}"
signature = hmac.new(
SECRET_KEY.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return f"{timestamp}:{signature}"
def validate_csrf_token(token, session_id):
"""Validate token matches session and isn't expired."""
try:
timestamp, signature = token.split(':')
timestamp = int(timestamp)
# Check expiry (1 hour)
if time.time() - timestamp > 3600:
return False
# Verify signature
message = f"{session_id}:{timestamp}"
expected = hmac.new(
SECRET_KEY.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return secrets.compare_digest(signature, expected)
except:
return False3. SameSite Cookie Attribute
# Modern browsers respect SameSite attribute
response.set_cookie(
'session_id',
value=session_id,
samesite='Lax', # Or 'Strict' for maximum protection
secure=True,
httponly=True
)SameSite Values:
| Value | Behavior |
|---|---|
| Strict | Never sent cross-site |
| Lax | Sent only with safe methods (GET) on top-level navigation |
| None | Always sent (requires Secure) |
4. Custom Request Headers
For AJAX/API requests, require a custom header that can't be set cross-origin without CORS.
// Client
fetch('/api/transfer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': getCSRFToken() // Or any custom header
},
body: JSON.stringify(data)
});# Server
@app.before_request
def verify_csrf_header():
if request.method in ('POST', 'PUT', 'DELETE', 'PATCH'):
token = request.headers.get('X-CSRF-Token')
if not validate_csrf_token(token):
return jsonify({'error': 'CSRF validation failed'}), 403Framework Implementations
Django
# Enabled by default via middleware
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
...
]
# In templates
<form method="POST">
{% csrf_token %}
...
</form>
# For AJAX
<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
fetch('/api/endpoint', {
method: 'POST',
headers: {'X-CSRFToken': csrftoken},
...
});
</script>Flask
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
# In templates
<form method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
...
</form>
# Exempt specific routes if needed (be careful!)
@csrf.exempt
@app.route('/webhook', methods=['POST'])
def webhook():
passExpress.js
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
app.use(csrfProtection);
app.get('/form', (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});
// In template
<form method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
...
</form>Origin and Referer Validation
As a supplementary defense:
def verify_origin():
"""Verify request origin matches expected domain."""
origin = request.headers.get('Origin')
referer = request.headers.get('Referer')
# Prefer Origin header
if origin:
if not is_trusted_origin(origin):
return False
return True
# Fall back to Referer
if referer:
parsed = urlparse(referer)
if not is_trusted_origin(f"{parsed.scheme}://{parsed.netloc}"):
return False
return True
# No origin info - could be same-origin or direct request
# Decision depends on security requirements
return True # Or False for strict validation
def is_trusted_origin(origin):
TRUSTED = {'https://example.com', 'https://admin.example.com'}
return origin in TRUSTEDFetch Metadata Headers
Modern browsers send additional headers that indicate request context:
def check_fetch_metadata():
"""Use Fetch Metadata headers for CSRF protection."""
sec_fetch_site = request.headers.get('Sec-Fetch-Site')
sec_fetch_mode = request.headers.get('Sec-Fetch-Mode')
# Allow same-origin requests
if sec_fetch_site == 'same-origin':
return True
# Allow navigation requests (clicking links)
if sec_fetch_site == 'none' and sec_fetch_mode == 'navigate':
return True
# Block cross-origin state-changing requests
if request.method in ('POST', 'PUT', 'DELETE', 'PATCH'):
if sec_fetch_site in ('cross-site', 'same-site'):
return False
return TrueClient-Side CSRF
Modern variant where JavaScript code uses attacker-controlled input:
// VULNERABLE: URL fragment used in request
const param = window.location.hash.substring(1);
fetch(`/api/action?${param}`, { method: 'POST' });
// Attack: https://example.com#action=delete&target=all
// SAFE: Validate before use
const allowedActions = ['view', 'refresh'];
const param = window.location.hash.substring(1);
const parsed = new URLSearchParams(param);
if (allowedActions.includes(parsed.get('action'))) {
fetch(`/api/action?${param}`, { method: 'POST' });
}Common Mistakes
1. GET Requests for State Changes
# VULNERABLE: State change via GET
@app.route('/delete/<id>')
def delete_item(id):
Item.delete(id) # Attacker: <img src="/delete/123">
# SAFE: Use POST for state changes
@app.route('/delete/<id>', methods=['POST'])
@csrf_required
def delete_item(id):
Item.delete(id)2. CORS Misconfiguration
# VULNERABLE: Allows any origin with credentials
@app.after_request
def add_cors(response):
response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin')
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response
# SAFE: Explicit allowlist
ALLOWED_ORIGINS = {'https://trusted.com'}
@app.after_request
def add_cors(response):
origin = request.headers.get('Origin')
if origin in ALLOWED_ORIGINS:
response.headers['Access-Control-Allow-Origin'] = origin
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response3. Token in URL
<!-- VULNERABLE: Token exposed in URL (logged, cached, referer) -->
<a href="/action?csrf_token=abc123">Do Action</a>
<!-- SAFE: Token in form -->
<form method="POST" action="/action">
<input type="hidden" name="csrf_token" value="abc123">
<button type="submit">Do Action</button>
</form>Grep Patterns for Detection
# Missing CSRF protection
grep -rn "@app\.route.*POST\|@router\.post" --include="*.py" | grep -v "csrf"
# State-changing GET requests
grep -rn "\.delete\|\.update\|\.create" --include="*.py" | grep "GET"
# CORS wildcards
grep -rn "Access-Control-Allow-Origin.*\*" --include="*.py"
# Framework CSRF disabled
grep -rn "csrf_exempt\|WTF_CSRF_ENABLED.*False\|csrf.*disable" --include="*.py"Testing Checklist
[ ] All state-changing requests require POST/PUT/DELETE
[ ] CSRF tokens included in all forms
[ ] CSRF tokens validated on submission
[ ] SameSite cookie attribute set (Lax or Strict)
[ ] Custom headers required for API requests
[ ] Origin/Referer validated as secondary defense
[ ] Fetch Metadata headers checked where supported
[ ] CORS properly configured (no wildcard with credentials)
[ ] Token not exposed in URL/logs
[ ] GET requests never change state
References
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs an API key, Needs Python
Security
What our scanner noticed· Medium risk
- References to credential files
- Instructions that use the network
- Encoded commands that are executed
- Downloads piped into a shell
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Sentry
- Publisher
- Sentry (Official)
- Source
- getsentry/skills · skills/security-review · commit e94f222
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Sentry.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download security-review.zip