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://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/logging.md
Security Logging Reference
Overview
Insufficient logging and monitoring failures allow attacks to go undetected. This includes missing audit trails, sensitive data in logs, log injection attacks, and inadequate alerting on security events.
Missing Security Event Logging
Events That Must Be Logged
# VULNERABLE: No logging of security events
def login(username, password):
user = authenticate(username, password)
if user:
return create_session(user)
return None # Failed login not logged
def change_password(user, old_pass, new_pass):
if verify_password(old_pass, user.password):
user.password = hash_password(new_pass)
user.save() # Password change not loggedRequired Security Events
import logging
from datetime import datetime
security_logger = logging.getLogger('security')
# Authentication events
def login(username, password):
user = authenticate(username, password)
if user:
security_logger.info(
"login_success",
extra={
'user_id': user.id,
'username': username,
'ip': request.remote_addr,
'user_agent': request.user_agent.string,
'timestamp': datetime.utcnow().isoformat()
}
)
return create_session(user)
else:
security_logger.warning(
"login_failure",
extra={
'username': username,
'ip': request.remote_addr,
'reason': 'invalid_credentials',
'timestamp': datetime.utcnow().isoformat()
}
)
return None
# Access control events
def access_resource(user, resource):
if not user.can_access(resource):
security_logger.warning(
"access_denied",
extra={
'user_id': user.id,
'resource': resource.id,
'action': 'read',
'ip': request.remote_addr
}
)
raise PermissionDenied()
# Critical data changes
def update_user_role(admin, user, new_role):
old_role = user.role
user.role = new_role
user.save()
security_logger.info(
"role_change",
extra={
'admin_id': admin.id,
'target_user_id': user.id,
'old_role': old_role,
'new_role': new_role
}
)Security Events Checklist
| Event Type | Must Log |
|---|---|
| Login success/failure | User, IP, timestamp, method |
| Logout | User, session duration |
| Password change | User, IP, timestamp |
| Password reset request | Email/user, IP |
| Account lockout | User, reason, duration |
| MFA enrollment/removal | User, method |
| Permission changes | Admin, target, old/new |
| Access denied | User, resource, action |
| Data export | User, data type, volume |
| Admin actions | Admin, action, target |
| API key creation/revocation | User, key ID (not key) |
| Security setting changes | User, setting, old/new |
Sensitive Data in Logs
Dangerous Patterns
# VULNERABLE: Logging passwords
logger.info(f"User {username} login attempt with password {password}")
logger.debug(f"Auth request: {request.json}") # Contains password
# VULNERABLE: Logging tokens/secrets
logger.info(f"API request with key: {api_key}")
logger.debug(f"JWT token: {token}")
logger.info(f"Session: {session_cookie}")
# VULNERABLE: Logging PII
logger.info(f"Processing payment for SSN: {ssn}")
logger.debug(f"User data: {user.__dict__}") # May contain sensitive fields
# VULNERABLE: Logging credit card numbers
logger.info(f"Payment with card: {card_number}")Secure Logging
# SAFE: Never log credentials
logger.info(f"Login attempt for user: {username}") # No password
# SAFE: Mask sensitive data
def mask_token(token):
if len(token) > 8:
return token[:4] + '****' + token[-4:]
return '****'
logger.info(f"API request with key: {mask_token(api_key)}")
# SAFE: Redact PII
def redact_pii(data):
sensitive_fields = {'password', 'ssn', 'credit_card', 'api_key', 'token'}
if isinstance(data, dict):
return {k: '[REDACTED]' if k in sensitive_fields else v
for k, v in data.items()}
return data
logger.debug(f"Request data: {redact_pii(request.json)}")
# SAFE: Use structured logging with explicit fields
logger.info(
"payment_processed",
extra={
'user_id': user.id,
'amount': amount,
'card_last_four': card_number[-4:], # Only last 4
'transaction_id': txn_id
}
)Log Injection
Attack Vector
Attackers inject malicious content into logs to:
Forge log entries
Exploit log viewers (XSS in log dashboards)
Manipulate log analysis tools
Hide malicious activity
Vulnerable Patterns
# VULNERABLE: Unsanitized user input in logs
logger.info(f"User search: {user_input}")
# Attack: user_input = "search\n2024-01-01 INFO admin logged in successfully"
# VULNERABLE: Direct interpolation
logger.info("Search query: " + query)
# Attack: query contains newlines and fake log entries
# VULNERABLE: Format string injection
logger.info("User %s performed action" % user_input)Secure Logging
# SAFE: Sanitize input before logging
import re
def sanitize_log_input(value):
"""Remove newlines and control characters."""
if isinstance(value, str):
# Remove newlines and carriage returns
value = value.replace('\n', '\\n').replace('\r', '\\r')
# Remove other control characters
value = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', value)
return value
logger.info(f"User search: {sanitize_log_input(user_input)}")
# SAFE: Use structured logging (JSON)
import json_logging
json_logging.init_non_web()
logger.info("search_performed", extra={
'query': user_input, # JSON encoding handles special chars
'user_id': user.id
})
# SAFE: Use parameterized logging
logger.info("User %s searched for %s", user_id, sanitize_log_input(query))Log Storage Security
Insecure Patterns
# VULNERABLE: World-readable log files
logging.basicConfig(filename='/var/log/app.log')
os.chmod('/var/log/app.log', 0o644) # Anyone can read
# VULNERABLE: Logs in web-accessible directory
logging.basicConfig(filename='/var/www/html/logs/app.log')
# VULNERABLE: No log rotation (can fill disk)
logging.basicConfig(filename='app.log') # Grows foreverSecure Log Configuration
# SAFE: Restricted permissions
import os
from logging.handlers import RotatingFileHandler
log_file = '/var/log/app/security.log'
handler = RotatingFileHandler(
log_file,
maxBytes=10*1024*1024, # 10MB
backupCount=10
)
# Set restrictive permissions
os.chmod(log_file, 0o600) # Owner only
# SAFE: Centralized logging with encryption
import logging.handlers
syslog_handler = logging.handlers.SysLogHandler(
address=('secure-syslog.company.com', 514),
socktype=socket.SOCK_STREAM # TCP for reliability
)
# Use TLS for syslog transportMissing Alerting
Security Events Requiring Alerts
# These should trigger immediate alerts, not just logging
ALERT_THRESHOLDS = {
'failed_logins': 5, # Per user per hour
'access_denied': 10, # Per user per hour
'admin_login': 1, # Any admin login from new IP
'privilege_escalation': 1, # Any role change
'data_export': 1, # Large data exports
}
def check_alert_threshold(event_type, user_id):
count = get_recent_event_count(event_type, user_id, hours=1)
if count >= ALERT_THRESHOLDS.get(event_type, float('inf')):
send_security_alert(
event_type=event_type,
user_id=user_id,
count=count,
severity='high' if event_type in ['admin_login', 'privilege_escalation'] else 'medium'
)Alert Configuration
# Security monitoring rules
MONITORING_RULES = [
{
'name': 'brute_force_detection',
'condition': 'failed_logins > 5 in 5 minutes from same IP',
'action': 'block_ip, alert_security_team'
},
{
'name': 'impossible_travel',
'condition': 'login from geographically impossible location',
'action': 'require_mfa, alert_user'
},
{
'name': 'off_hours_admin',
'condition': 'admin action outside business hours',
'action': 'alert_security_team'
},
{
'name': 'mass_data_access',
'condition': 'data export > 10000 records',
'action': 'alert_security_team, require_approval'
}
]Audit Trail Requirements
Immutable Audit Logs
# VULNERABLE: Mutable logs
def delete_audit_log(log_id):
AuditLog.query.filter_by(id=log_id).delete() # Can be deleted
# SAFE: Append-only audit logs
class AuditLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, nullable=False)
event_type = db.Column(db.String, nullable=False)
user_id = db.Column(db.Integer)
details = db.Column(db.JSON)
checksum = db.Column(db.String) # Hash of previous entry
@classmethod
def create(cls, event_type, user_id, details):
# Get previous entry's checksum for chain
prev = cls.query.order_by(cls.id.desc()).first()
prev_checksum = prev.checksum if prev else 'genesis'
entry = cls(
timestamp=datetime.utcnow(),
event_type=event_type,
user_id=user_id,
details=details
)
# Chain checksum
entry.checksum = hashlib.sha256(
f"{prev_checksum}{entry.timestamp}{entry.event_type}".encode()
).hexdigest()
db.session.add(entry)
db.session.commit()
return entry
# No delete method - audit logs are immutableRetention Requirements
# Configure retention based on compliance requirements
LOG_RETENTION = {
'security_events': 365, # 1 year
'authentication': 90, # 90 days
'access_logs': 30, # 30 days
'debug_logs': 7, # 7 days
'audit_trail': 2555, # 7 years (compliance)
}
def cleanup_old_logs():
for log_type, days in LOG_RETENTION.items():
cutoff = datetime.utcnow() - timedelta(days=days)
delete_logs_before(log_type, cutoff)Grep Patterns for Detection
# Missing security logging
grep -rn "def login\|def authenticate" --include="*.py" | xargs -I {} grep -L "logger\|logging" {}
# Sensitive data in logs
grep -rn "logger.*password\|logging.*password\|log.*password" --include="*.py"
grep -rn "logger.*token\|logger.*secret\|logger.*key" --include="*.py"
# Unsanitized log input
grep -rn "logger.*f\"\|logger.*%s.*%" --include="*.py"
# Missing log rotation
grep -rn "basicConfig.*filename\|FileHandler" --include="*.py" | grep -v "Rotating"
# World-readable logs
grep -rn "chmod.*644\|chmod.*755" --include="*.py" | grep -i logTesting Checklist
[ ] Authentication events (success/failure) logged
[ ] Authorization failures logged
[ ] Sensitive operations logged (password change, role change)
[ ] No passwords/tokens/secrets in logs
[ ] Log injection prevented (newlines sanitized)
[ ] Logs have restricted file permissions
[ ] Log rotation configured
[ ] Centralized logging for production
[ ] Alerts configured for security events
[ ] Audit trail is immutable
[ ] Log retention meets compliance requirements
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 or Sentry.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download security-review.zip