Deployment of Wrong Handler
Description
Deployment of Wrong Handler is a vulnerability where the wrong "handler" is assigned to process an object. This weakness occurs when incorrect processing mechanisms handle objects, leading to unexpected behavior or security issues. Common examples include invoking a servlet that reveals JSP source code instead of executing it, automatically determining object types despite explicit type specifications contradicting the determination, or processing uploaded files with handlers that don't match the declared file type.
Risk
Wrong handler deployment can lead to severe security consequences including source code disclosure, security bypass, and arbitrary code execution. When a script file is processed by a static file handler instead of the script engine, source code containing credentials or logic is exposed. When file type validation is bypassed by mismatched handlers, attackers can execute arbitrary code through uploaded files. Content-Type mishandling can cause browsers to execute malicious content. The risk is amplified when handler selection relies on easily-manipulated inputs like file extensions or user-supplied headers.
Solution
Perform type checks before interpreting objects to ensure the handler matches the actual content type. Reject any inconsistent types, such as a file with a .GIF extension that appears to consist of PHP code. Implement defense in depth by validating both declared type and actual content. Configure web servers to enforce strict handler mappings and prevent fallback to default handlers. Use content sniffing prevention headers (X-Content-Type-Options: nosniff). Validate uploaded files against expected content signatures, not just extensions.
Common Consequences
| Impact | Details |
|---|---|
| Integrity | Scope: Integrity, Other Varies by Context - The consequences depend on context but typically result in unexpected application states. Unexpected State - Wrong handler may process content in unintended ways, leading to information disclosure or security bypass. |
Example Code
Vulnerable Code
// Vulnerable: Servlet container misconfiguration
// web.xml that allows direct servlet invocation
<servlet-mapping>
<servlet-name>JspServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
// Missing: No protection against direct class invocation
// Attacker can invoke: /servlet/com.example.InternalServlet
// This bypasses JSP processing and may expose source or internal functionality
<?php
// Vulnerable: Extension-based handler selection
function vulnerable_process_upload($filename, $content) {
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Vulnerable: Trusts extension without content validation
switch (strtolower($extension)) {
case 'jpg':
case 'gif':
case 'png':
// Processes as image, but content might be PHP!
move_uploaded_file($content, "/uploads/" . $filename);
break;
case 'txt':
// Treats as text
file_put_contents("/uploads/" . $filename, $content);
break;
}
}
// Attacker uploads "malicious.php.jpg" or "image.gif" containing PHP code
// If web server executes .gif files as PHP, code runs
?>
# Vulnerable: Content-Type based handler selection without validation
from flask import Flask, request, send_file
app = Flask(__name__)
@app.route('/process', methods=['POST'])
def vulnerable_process():
content_type = request.content_type
# Vulnerable: Trusts Content-Type header
if 'image' in content_type:
# Processes as image
return process_image(request.data)
elif 'text' in content_type:
# Processes as text
return process_text(request.data)
elif 'application/json' in content_type:
# Processes as JSON
return process_json(request.data)
# Vulnerable: Attacker sends PHP with Content-Type: image/jpeg
# Vulnerable: Apache configuration with wrong handler
# Handler mismatch can expose source code
# Missing AddHandler directive allows wrong processing
<Directory /var/www/cgi-bin>
# Vulnerable: No explicit handler - may serve as static files
Options ExecCGI
</Directory>
# Vulnerable: Extension collision
AddHandler application/x-httpd-php .php
AddHandler text/html .phps # Should be for viewing source, easily confused
Fixed Code
// Fixed: Proper servlet security configuration
// web.xml with handler restrictions
<web-app>
<!-- Fixed: Block direct servlet invocation -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Servlets</web-resource-name>
<url-pattern>/servlet/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- No roles = no access -->
</auth-constraint>
</security-constraint>
<!-- Fixed: Explicit handler mapping only -->
<servlet-mapping>
<servlet-name>JspServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<!-- Fixed: Default servlet for unmapped requests -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?php
// Fixed: Validate content matches declared type
function secure_process_upload($filename, $tmp_path) {
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Fixed: Validate actual content type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$actual_mime = $finfo->file($tmp_path);
// Fixed: Define allowed types with content validation
$allowed_types = [
'jpg' => ['image/jpeg'],
'gif' => ['image/gif'],
'png' => ['image/png'],
'txt' => ['text/plain'],
];
if (!isset($allowed_types[$extension])) {
throw new Exception("Unsupported file type");
}
// Fixed: Verify content matches extension
if (!in_array($actual_mime, $allowed_types[$extension])) {
throw new Exception("Content type mismatch: expected " .
implode('/', $allowed_types[$extension]) . ", got " . $actual_mime);
}
// Fixed: Generate safe filename
$safe_name = bin2hex(random_bytes(16)) . '.' . $extension;
// Fixed: Store outside web root or with execution disabled
move_uploaded_file($tmp_path, "/var/uploads/" . $safe_name);
return $safe_name;
}
?>
# Fixed: Validate content matches declared type
from flask import Flask, request
import magic
app = Flask(__name__)
ALLOWED_HANDLERS = {
'image/jpeg': process_jpeg,
'image/png': process_png,
'image/gif': process_gif,
'application/json': process_json,
'text/plain': process_text,
}
@app.route('/process', methods=['POST'])
def secure_process():
# Fixed: Use magic bytes to detect actual content type
actual_type = magic.from_buffer(request.data, mime=True)
declared_type = request.content_type.split(';')[0].strip()
# Fixed: Verify declared type matches actual content
if actual_type != declared_type:
return {"error": f"Content type mismatch: declared {declared_type}, actual {actual_type}"}, 400
# Fixed: Only allow known handlers
handler = ALLOWED_HANDLERS.get(actual_type)
if handler is None:
return {"error": f"Unsupported content type: {actual_type}"}, 415
# Fixed: Use validated handler
return handler(request.data)
# Fixed: Add content type header to responses
@app.after_request
def add_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
return response
# Fixed: Explicit handler configuration
<Directory /var/www/cgi-bin>
# Fixed: Require explicit handler
Options -ExecCGI
SetHandler none
# Fixed: Only enable CGI for specific extensions
<FilesMatch "\.cgi$">
SetHandler cgi-script
Options +ExecCGI
</FilesMatch>
</Directory>
# Fixed: Strict PHP handling
<FilesMatch "\.php$">
SetHandler application/x-httpd-php
</FilesMatch>
# Fixed: Prevent double extension attacks
<FilesMatch "\.php\.">
SetHandler none
Require all denied
</FilesMatch>
# Fixed: Disable execution in uploads directory
<Directory /var/www/uploads>
SetHandler none
php_flag engine off
Options -ExecCGI
<FilesMatch ".*">
SetHandler default-handler
</FilesMatch>
</Directory>
CVE Examples
- CVE-2001-0004 — Source code disclosure via manipulated file extension causing parsing by wrong DLL.
- CVE-2002-0025 — Web browser mishandling Content-Type headers, causing wrong application to process content.
- CVE-2000-1052 — Source code disclosure through direct servlet invocation.
- CVE-2002-1742 — Arbitrary Perl functions loaded via non-existent function handler activation.
References
- MITRE Corporation. "CWE-430: Deployment of Wrong Handler." https://cwe.mitre.org/data/definitions/430.html
- CAPEC-11. "Cause Web Server Misclassification." https://capec.mitre.org/data/definitions/11.html