Exception Handling Vulnerabilities

This skill should be used when the user asks about "XXE", "XML External Entity", "error handling", "exception disclosure", "stack trace exposure", "improper error handling", or needs to find exception-related vulnerabilities during whitebox security review.

14 stars

Best use case

Exception Handling Vulnerabilities is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

This skill should be used when the user asks about "XXE", "XML External Entity", "error handling", "exception disclosure", "stack trace exposure", "improper error handling", or needs to find exception-related vulnerabilities during whitebox security review.

Teams using Exception Handling Vulnerabilities should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/exception-handling/SKILL.md --create-dirs "https://raw.githubusercontent.com/allsmog/vuln-scout/main/vuln-scout/skills/exception-handling/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/exception-handling/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How Exception Handling Vulnerabilities Compares

Feature / AgentException Handling VulnerabilitiesStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

This skill should be used when the user asks about "XXE", "XML External Entity", "error handling", "exception disclosure", "stack trace exposure", "improper error handling", or needs to find exception-related vulnerabilities during whitebox security review.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Exception Handling Vulnerabilities

## Purpose

Provide detection patterns for vulnerabilities related to improper exception and error handling, including XXE (XML External Entity) injection, stack trace disclosure, and authentication bypass via exceptions.

## OWASP Top 10 Mapping

**Category**: Context-dependent

Improper exception handling is not a standalone official OWASP Top 10 bucket. In practice, findings from this skill often map to:
- A05 - Security Misconfiguration
- A08 - Software and Data Integrity Failures
- A03 - Injection, when XXE or parser misuse is the concrete issue

**CWEs**:
- CWE-390: Detection of Error Condition Without Action
- CWE-392: Missing Report of Error Condition
- CWE-460: Improper Cleanup on Thrown Exception
- CWE-611: Improper Restriction of XML External Entity Reference (XXE)
- CWE-755: Improper Handling of Exceptional Conditions

## When to Use

Activate this skill when:
- Searching for XML parsing vulnerabilities
- Reviewing error handling code
- Looking for information disclosure via exceptions
- Finding authentication/authorization bypass via exception paths

---

## XXE (XML External Entity) Injection

### Overview

XXE occurs when XML parsers process external entity references in untrusted XML input, allowing attackers to read files, perform SSRF, or cause DoS.

### Detection Patterns

#### Java

```bash
# Vulnerable XML parsers
grep -rniE "DocumentBuilderFactory|SAXParserFactory|XMLInputFactory|TransformerFactory|SchemaFactory|XMLReader" --include="*.java"

# Check for disabled external entities (SAFE patterns)
grep -rniE "setFeature.*FEATURE_SECURE_PROCESSING|setFeature.*disallow-doctype-decl|setExpandEntityReferences.*false" --include="*.java"
```

**Vulnerable Pattern**:
```java
// VULNERABLE: Default parser allows XXE
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(userInputStream);  // XXE possible
```

**Secure Pattern**:
```java
// SAFE: External entities disabled
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
```

#### Python

```bash
# Vulnerable XML parsers
grep -rniE "xml\.etree\.ElementTree|xml\.dom\.minidom|xml\.sax|lxml\.etree" --include="*.py"

# Check for defusedxml (SAFE)
grep -rniE "defusedxml|defused" --include="*.py"
```

**Vulnerable Pattern**:
```python
# VULNERABLE: Standard library allows XXE
import xml.etree.ElementTree as ET
tree = ET.parse(user_input)  # XXE possible
```

**Secure Pattern**:
```python
# SAFE: Use defusedxml
import defusedxml.ElementTree as ET
tree = ET.parse(user_input)  # XXE blocked
```

#### PHP

```bash
# Vulnerable XML functions
grep -rniE "simplexml_load|DOMDocument|XMLReader|SimpleXMLElement" --include="*.php"

# Check for entity loader disabled (SAFE)
grep -rniE "libxml_disable_entity_loader|LIBXML_NOENT" --include="*.php"
```

**Vulnerable Pattern**:
```php
// VULNERABLE: External entities enabled
$xml = simplexml_load_string($userInput);  // XXE possible
```

**Secure Pattern**:
```php
// SAFE: Disable external entities (PHP < 8.0)
libxml_disable_entity_loader(true);
$xml = simplexml_load_string($userInput, 'SimpleXMLElement', LIBXML_NOENT);
```

#### Go

```bash
# XML parsing
grep -rniE "xml\.Unmarshal|xml\.Decoder|xml\.NewDecoder" --include="*.go"
```

**Note**: Go's `encoding/xml` does not process external entities by default, making it safe from XXE. However, third-party libraries may be vulnerable.

#### TypeScript/JavaScript

```bash
# XML parsing libraries
grep -rniE "xml2js|fast-xml-parser|libxmljs|DOMParser|parseFromString" --include="*.ts" --include="*.js"
```

**Vulnerable Pattern**:
```typescript
// VULNERABLE: Some libraries allow XXE
const parser = new DOMParser();
const doc = parser.parseFromString(userInput, "text/xml");
```

---

## Stack Trace / Error Disclosure

### Overview

Exposing stack traces or detailed error messages to users reveals internal paths, library versions, and application structure.

### Detection Patterns

#### Java

```bash
# Stack trace printing
grep -rniE "printStackTrace|getStackTrace|\.getMessage\(\)" --include="*.java"

# Exposed to response
grep -rniE "response\.getWriter\(\).*exception|sendError.*getMessage" --include="*.java"
```

**Vulnerable Pattern**:
```java
// VULNERABLE: Stack trace sent to user
catch (Exception e) {
    response.getWriter().println(e.getMessage());
    e.printStackTrace(response.getWriter());
}
```

#### Python

```bash
# Traceback exposure
grep -rniE "traceback\.print_exc|traceback\.format_exc|sys\.exc_info" --include="*.py"

# Debug mode
grep -rniE "DEBUG.*=.*True|app\.debug.*=.*True" --include="*.py"
```

**Vulnerable Pattern**:
```python
# VULNERABLE: Traceback in response
except Exception as e:
    return jsonify({"error": traceback.format_exc()})  # Exposes internals
```

#### PHP

```bash
# Error display
grep -rniE "display_errors|error_reporting|var_dump|print_r" --include="*.php"
```

**Vulnerable Pattern**:
```php
// VULNERABLE: Errors displayed to users
ini_set('display_errors', 1);
error_reporting(E_ALL);
```

#### Go

```bash
# Stack trace functions
grep -rniE "debug\.PrintStack|runtime\.Stack|debug\.Stack" --include="*.go"

# Error exposure
grep -rniE "http\.Error.*err\.Error\(\)|json\..*err\.Error\(\)" --include="*.go"
```

**Vulnerable Pattern**:
```go
// VULNERABLE: Internal error exposed
if err != nil {
    http.Error(w, err.Error(), 500)  // May leak internal paths
}
```

#### TypeScript

```bash
# Stack exposure
grep -rniE "\.stack|Error\(\)\.stack|console\.error" --include="*.ts"
```

---

## Empty Catch Blocks

### Overview

Empty catch blocks silently swallow exceptions, potentially hiding security failures or allowing bypasses.

### Detection Patterns

```bash
# Java - Empty catch
grep -rniE "catch\s*\([^)]+\)\s*\{\s*\}" --include="*.java"

# Python - pass in except
grep -rniE "except.*:\s*pass" --include="*.py"

# PHP - empty catch
grep -rniE "catch\s*\([^)]+\)\s*\{\s*\}" --include="*.php"

# TypeScript - empty catch
grep -rniE "catch\s*\([^)]*\)\s*\{\s*\}" --include="*.ts"
```

**Vulnerable Pattern**:
```java
// VULNERABLE: Authentication failure silently ignored
try {
    authenticateUser(token);
} catch (AuthenticationException e) {
    // Empty - user proceeds as authenticated!
}
```

---

## Exception-Based Authentication Bypass

### Overview

When authentication/authorization logic is inside try blocks, exceptions may allow bypass.

### Detection Patterns

```bash
# Auth in try blocks
grep -rniE "try.*\{[^}]*(authenticate|authorize|checkPermission|isAdmin)" --include="*.java" --include="*.py" --include="*.go" --include="*.ts" --include="*.php"

# Catch blocks that continue execution
grep -rniE "catch.*\{[^}]*(continue|return true|return null)" --include="*.java"
```

**Vulnerable Pattern**:
```java
// VULNERABLE: Exception allows bypass
boolean isAuthorized = false;
try {
    isAuthorized = authService.checkPermission(user, resource);
} catch (Exception e) {
    // Exception occurs, isAuthorized stays false... or does it?
    log.error("Auth check failed", e);
}
// If exception + isAuthorized not checked properly = bypass
```

---

## Resource Exhaustion via Exceptions

### Overview

Repeated exception generation can exhaust resources (CPU, memory, logs).

### Detection Patterns

```bash
# Exceptions in loops
grep -rniE "(for|while).*\{[^}]*throw new|try.*\{[^}]*(for|while)" --include="*.java" --include="*.py" --include="*.go"

# Unbounded recursion
grep -rniE "catch.*\{[^}]*throw|except.*raise" --include="*.java" --include="*.py"
```

---

## Language-Specific Secure Patterns

### Java - Safe Exception Handling

```java
// Log internally, return generic message
catch (Exception e) {
    logger.error("Operation failed", e);  // Internal log with stack
    throw new ApiException("An error occurred", 500);  // Generic to user
}
```

### Python - Safe Exception Handling

```python
# Log internally, return generic message
except Exception as e:
    logger.exception("Operation failed")  # Logs full traceback
    return jsonify({"error": "An error occurred"}), 500  # Generic to user
```

### Go - Safe Exception Handling

```go
// Wrap errors, don't expose internals
if err != nil {
    log.Printf("operation failed: %v", err)  // Internal log
    http.Error(w, "Internal server error", 500)  // Generic to user
}
```

### PHP - Safe Exception Handling

```php
// Production error handling
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_log($e->getMessage());  // Log internally
echo json_encode(["error" => "An error occurred"]);  // Generic to user
```

### TypeScript - Safe Exception Handling

```typescript
// Sanitize errors before response
catch (error) {
    logger.error('Operation failed', { error });  // Internal log
    res.status(500).json({ error: 'An error occurred' });  // Generic
}
```

---

## Verification Steps

1. **Find XML parsers** → Check if external entities are disabled
2. **Find catch/except blocks** → Check if they're empty or expose details
3. **Find error responses** → Check if stack traces or internal errors are included
4. **Find auth in try blocks** → Check exception handling doesn't bypass auth
5. **Test XXE** → Send payload with external entity reference

### XXE Test Payloads

```xml
<!-- File read -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<foo>&xxe;</foo>

<!-- SSRF -->
<?xml version="1.0"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://internal-server/admin">]>
<foo>&xxe;</foo>

<!-- DoS (Billion Laughs) -->
<?xml version="1.0"?>
<!DOCTYPE lolz [
  <!ENTITY lol "lol">
  <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
  <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
]>
<lolz>&lol3;</lolz>
```

---

## CWE References

| CWE | Name | Description |
|-----|------|-------------|
| CWE-390 | Detection Without Action | Exception caught but not handled |
| CWE-392 | Missing Report | Exception not logged/reported |
| CWE-460 | Improper Cleanup | Resources not cleaned on exception |
| CWE-611 | XXE | XML parser processes external entities |
| CWE-755 | Improper Handling | Generic exception handling issues |

Related Skills

We are still matching the closest adjacent skills for this page. In the meantime, continue through the full directory.