Generated banner for Security Review
Generated logo for Security Review

Security Review

SentryOfficialPublished by Sentry

  • Skill
  • Review and audit
  • Security
  • CC-BY-SA-4.0
  • Medium risk

From the author

Security code review for vulnerabilities. Use when asked to "security review", "find vulnerabilities", "check for security issues", "audit security", "OWASP review", or review code for injection, XSS, authentication, authorization, cryptography issues. Provides systematic review with confidence-based reporting.
— the description by Sentry

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/getsentry/security-review/download
  2. Unzip 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

LevelCriteriaAction
HIGHVulnerable pattern + attacker-controlled input confirmedReport with severity
MEDIUMVulnerable pattern, input source unclearNote as "Needs verification"
LOWTheoretical, best practice, defense-in-depthDo 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:

SourceExampleWhy It's Safe
Django settingssettings.API_URL, settings.ALLOWED_HOSTSSet via config/env at deployment
Environment variablesos.environ.get('DATABASE_URL')Deployment configuration
Config filesconfig.yaml, app.config['KEY']Server-side files
Framework constantsdjango.conf.settings.*Not user-modifiable
Hardcoded valuesBASE_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:

PatternWhy 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 TypeLoad These References
API endpoints, routesauthorization.md, authentication.md, injection.md
Django/DRF views, permission classes, object-level accessUse the django-access-review skill if available for access control; otherwise authorization.md
Frontend, templatesxss.md, csrf.md, modern-threats.md (DOM clobbering, prototype pollution)
File handling, uploadsfile-security.md
Crypto, secrets, tokenscryptography.md, data-protection.md
Data serializationdeserialization.md
External requestsssrf.md
Business workflowsbusiness-logic.md
GraphQL, REST designapi-security.md
Config, headers, CORSmisconfiguration.md
CI/CD, dependenciessupply-chain.md
Error handlingerror-handling.md
Audit, logginglogging.md
Object merging/cloning, __proto__, DOM id/name lookups, WebSocket handlers, LLM prompt constructionmodern-threats.md
2. Load Language Guide

Based on file extension or imports:

IndicatorsGuide
.py, django, flask, fastapilanguages/python.md
.js, .ts, express, react, vue, nextlanguages/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 TypeGuide
Dockerfile, .dockerignoreinfrastructure/docker.md
GitHub Actions workflowsUse the gha-security-review skill if available; otherwise references/supply-chain.md
Other CI/CD pipelines, lockfiles, package manifestsreferences/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.argssettings.X, app.config['X']
request.json, request.data, request.bodyos.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 usersFramework 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

SeverityImpactExamples
CriticalDirect exploit, severe impact, no auth requiredRCE, SQL injection to data, auth bypass, hardcoded secrets
HighExploitable with conditions, significant impactStored XSS, SSRF to metadata, IDOR to sensitive data
MediumSpecific conditions required, moderate impactReflected XSS, CSRF on state-changing actions, path traversal
LowDefense-in-depth, minimal direct impactMissing 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.js
Always 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 injection
Always 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 module

Output 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:456

  • Question: [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 security

Files

references/error-handling.md

Error Handling Security Reference

Overview

Improper error handling can lead to information disclosure, denial of service, or security bypasses. This includes verbose error messages exposing internals, fail-open patterns that skip security checks on errors, and unhandled exceptions that crash services or leave systems in insecure states.


Information Disclosure

Stack Traces in Responses
# VULNERABLE: Stack trace exposed to users
@app.errorhandler(Exception)
def handle_error(e):
    return f"Error: {traceback.format_exc()}", 500

# VULNERABLE: Detailed exception info
@app.route('/api/user/<id>')
def get_user(id):
    try:
        return User.query.get(id).to_dict()
    except Exception as e:
        return jsonify({
            'error': str(e),
            'type': type(e).__name__,
            'args': e.args
        }), 500
Secure Error Handling
# SAFE: Generic messages, detailed logging
import logging

logger = logging.getLogger(__name__)

@app.errorhandler(Exception)
def handle_error(e):
    # Log full details server-side
    logger.error(f"Unhandled exception: {e}", exc_info=True)

    # Return generic message to client
    return jsonify({'error': 'An internal error occurred'}), 500

# SAFE: Custom exceptions with safe messages
class UserNotFoundError(Exception):
    pass

@app.route('/api/user/<id>')
def get_user(id):
    try:
        user = User.query.get(id)
        if not user:
            raise UserNotFoundError()
        return user.to_dict()
    except UserNotFoundError:
        return jsonify({'error': 'User not found'}), 404
    except Exception:
        logger.exception("Error fetching user")
        return jsonify({'error': 'Internal error'}), 500

Fail-Open Patterns

Authentication Bypass on Error
# VULNERABLE: Fail-open authentication
def authenticate(token):
    try:
        user = verify_token(token)
        return user
    except Exception:
        return None  # Returns None, might be treated as valid

# VULNERABLE: Exception allows bypass
def check_permission(user, resource):
    try:
        return permission_service.check(user, resource)
    except ServiceUnavailable:
        return True  # DANGEROUS: Allows access on service failure

# VULNERABLE: Default to authorized on error
@app.route('/admin')
def admin():
    try:
        if not is_admin(current_user):
            abort(403)
    except Exception:
        pass  # Silently continues to admin page
    return render_admin_panel()
Secure Fail-Closed Patterns
# SAFE: Fail-closed authentication
def authenticate(token):
    try:
        user = verify_token(token)
        if user is None:
            raise AuthenticationError("Invalid token")
        return user
    except Exception as e:
        logger.error(f"Auth error: {e}")
        raise AuthenticationError("Authentication failed")

# SAFE: Deny on service unavailable
def check_permission(user, resource):
    try:
        return permission_service.check(user, resource)
    except ServiceUnavailable:
        logger.error("Permission service unavailable")
        return False  # Deny access when unable to verify

# SAFE: Explicit denial on error
@app.route('/admin')
def admin():
    try:
        if not is_admin(current_user):
            abort(403)
    except Exception as e:
        logger.error(f"Admin check failed: {e}")
        abort(500)  # Don't proceed on error
    return render_admin_panel()

Exception Swallowing

Dangerous Patterns
# VULNERABLE: Silent exception swallowing
try:
    validate_input(user_input)
except:
    pass  # Validation skipped entirely

# VULNERABLE: Catch-all hides security issues
try:
    result = dangerous_operation(user_data)
except Exception:
    result = default_value  # May hide injection attempts

# VULNERABLE: Empty except block
try:
    decrypt_sensitive_data(data)
except:
    pass  # Continues with encrypted/invalid data
Secure Exception Handling
# SAFE: Handle specific exceptions
try:
    validate_input(user_input)
except ValidationError as e:
    logger.warning(f"Validation failed: {e}")
    return jsonify({'error': 'Invalid input'}), 400
except Exception as e:
    logger.error(f"Unexpected validation error: {e}")
    return jsonify({'error': 'Validation error'}), 500

# SAFE: Never silently swallow security-critical exceptions
try:
    result = dangerous_operation(user_data)
except SecurityException as e:
    logger.error(f"Security exception: {e}")
    raise  # Re-raise security exceptions
except ValueError as e:
    logger.warning(f"Invalid data: {e}")
    result = None

Differential Error Messages

User Enumeration via Errors
# VULNERABLE: Different messages reveal user existence
@app.route('/login', methods=['POST'])
def login():
    user = User.query.filter_by(email=email).first()
    if not user:
        return jsonify({'error': 'User not found'}), 401  # Reveals user doesn't exist
    if not check_password(password, user.password):
        return jsonify({'error': 'Wrong password'}), 401  # Reveals user exists
    return create_session(user)

# VULNERABLE: Timing difference reveals user existence
def login(email, password):
    user = User.query.filter_by(email=email).first()
    if not user:
        return False  # Fast return
    return check_password(password, user.password)  # Slow hash check
Secure Consistent Errors
# SAFE: Consistent error messages
@app.route('/login', methods=['POST'])
def login():
    user = User.query.filter_by(email=email).first()
    if not user or not check_password(password, user.password):
        return jsonify({'error': 'Invalid credentials'}), 401  # Same message
    return create_session(user)

# SAFE: Constant-time comparison with dummy hash
DUMMY_HASH = generate_password_hash('dummy')

def login(email, password):
    user = User.query.filter_by(email=email).first()
    if user:
        valid = check_password(password, user.password)
    else:
        check_password(password, DUMMY_HASH)  # Constant time even if user not found
        valid = False
    return valid

Resource Exhaustion via Errors

Uncontrolled Exception Logging
# VULNERABLE: Attacker can fill logs
@app.route('/api/data')
def get_data():
    try:
        return process_data(request.json)
    except Exception as e:
        # Logs entire request body - attacker sends huge payloads
        logger.error(f"Error processing: {request.json}")
        return jsonify({'error': 'Error'}), 500
Secure Logging
# SAFE: Limit logged data
@app.route('/api/data')
def get_data():
    try:
        return process_data(request.json)
    except Exception as e:
        # Log limited info, not full payload
        logger.error(f"Error processing request from {request.remote_addr}")
        return jsonify({'error': 'Error'}), 500

Unhandled Async Exceptions

Dangerous Patterns
// VULNERABLE: Unhandled promise rejection
async function processUser(userId) {
    const user = await fetchUser(userId);  // No catch
    return user;
}

// VULNERABLE: Missing error handler
app.get('/api/data', async (req, res) => {
    const data = await fetchData();  // Unhandled rejection crashes server
    res.json(data);
});
Secure Async Handling
// SAFE: Always handle async errors
async function processUser(userId) {
    try {
        const user = await fetchUser(userId);
        return user;
    } catch (error) {
        logger.error('Failed to fetch user', { userId, error });
        throw new UserFetchError('Unable to fetch user');
    }
}

// SAFE: Express async wrapper
const asyncHandler = (fn) => (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
};

app.get('/api/data', asyncHandler(async (req, res) => {
    const data = await fetchData();
    res.json(data);
}));

// Global handler for unhandled rejections
process.on('unhandledRejection', (reason, promise) => {
    logger.error('Unhandled Rejection', { reason });
    // Don't exit - handle gracefully
});

Error-Based SQL Injection Indicators

Verbose Database Errors
# VULNERABLE: Database errors exposed
@app.route('/api/search')
def search():
    try:
        results = db.execute(f"SELECT * FROM items WHERE name = '{query}'")
        return jsonify(results)
    except Exception as e:
        return jsonify({'error': str(e)}), 500
        # Exposes: "syntax error at or near 'OR'" - reveals SQL injection possibility
Secure Database Error Handling
# SAFE: Generic database errors
@app.route('/api/search')
def search():
    try:
        results = db.execute("SELECT * FROM items WHERE name = %s", (query,))
        return jsonify(results)
    except DatabaseError as e:
        logger.error(f"Database error: {e}")
        return jsonify({'error': 'Search failed'}), 500

Cleanup on Error

Resource Leaks
# VULNERABLE: Resource not cleaned up on error
def process_file(filename):
    f = open(filename)
    data = f.read()
    process(data)  # If this raises, file handle leaks
    f.close()

# VULNERABLE: Connection not returned to pool
def query_db():
    conn = pool.get_connection()
    result = conn.execute(query)  # If this raises, connection leaks
    pool.return_connection(conn)
    return result
Secure Resource Management
# SAFE: Context managers ensure cleanup
def process_file(filename):
    with open(filename) as f:
        data = f.read()
        process(data)  # File closed even on exception

# SAFE: Try-finally for cleanup
def query_db():
    conn = pool.get_connection()
    try:
        result = conn.execute(query)
        return result
    finally:
        pool.return_connection(conn)  # Always returns connection

Grep Patterns for Detection

# Bare except clauses
grep -rn "except:" --include="*.py" | grep -v "except Exception"

# Empty exception handlers
grep -rn "except.*:\s*$" -A1 --include="*.py" | grep "pass"

# Stack traces in responses
grep -rn "traceback\|format_exc\|exc_info" --include="*.py" | grep -v "logger\|logging"

# Fail-open patterns
grep -rn "except.*:\s*$" -A2 --include="*.py" | grep "return True\|return None"

# Detailed error messages
grep -rn "str(e)\|str(err)\|e\.args\|e\.message" --include="*.py" | grep "return\|jsonify\|response"

# Differential error messages
grep -rn "not found\|does not exist\|invalid password\|wrong password" --include="*.py"

# Unhandled async
grep -rn "await.*[^;]$" --include="*.js" --include="*.ts" | grep -v "try\|catch"

Testing Checklist

  • [ ] No stack traces in production error responses

  • [ ] All security checks fail-closed (deny on error)

  • [ ] No empty except/catch blocks for security-critical code

  • [ ] Consistent error messages for auth (no user enumeration)

  • [ ] Async operations have error handlers

  • [ ] Resources cleaned up on error (files, connections)

  • [ ] Error logging doesn't include full user input

  • [ ] Database errors don't expose query structure

  • [ ] Rate limiting on error-generating endpoints


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