CWE-1104 in APIs
- CWE ID
- CWE-1104
- Category
- Inventory Management
- Severity
- MEDIUM
- Short Name
- Outdated Components
What is CWE-1104?
CWE-1104:2020-06-22 - 2020 Top 25 Most Dangerous Software Weaknesses
CWE-1104 describes a scenario where untrusted data is sent to a different system or component than intended. This can occur when an application sends sensitive data to an unintended recipient, such as a different API endpoint, database, or service. The weakness arises from improper validation or control over where data is transmitted, potentially exposing sensitive information to unauthorized parties.
In API contexts, CWE-1104 manifests when APIs inadvertently send data to incorrect endpoints, misconfigured services, or unauthorized third parties. This can result from URL manipulation, header injection, or logic flaws that cause the API to communicate with the wrong destination.
CWE-1104 in API Contexts
APIs are particularly vulnerable to CWE-1104 due to their distributed nature and the complexity of modern microservice architectures. Several API-specific scenarios commonly lead to this weakness:
Misconfigured Service Discovery
APIs often use service discovery mechanisms to locate and communicate with other services. If these mechanisms are misconfigured or manipulated, an API might send requests to unintended services:
# Vulnerable: Service discovery without validation
import requests
def get_user_data(user_id):
# Service discovery returns wrong endpoint
service_url = discover_service('user-service')
response = requests.get(f"{service_url}/users/{user_id}")
return response.json()
Header Injection Attacks
Attackers can manipulate HTTP headers to redirect API requests to malicious endpoints:
# Vulnerable: Trusting Host header
from flask import Flask, request
app = Flask(__name__)
@app.route('/api/data')
def api_data():
host = request.headers.get('Host', 'default-service')
url = f"https://{host}/internal/data"
response = requests.get(url)
return response.json()
Open Redirects in API Responses
APIs that include redirect URLs in responses without proper validation can be exploited:
// Vulnerable: No redirect validation
app.get('/api/redirect', (req, res) => {
const redirectUrl = req.query.url;
res.redirect(redirectUrl); // Could redirect to malicious site
});
Cross-Origin Resource Sharing (CORS) Misconfiguration
Improper CORS policies can allow unauthorized domains to receive API responses:
# Vulnerable: Wildcard CORS
from flask import Flask, jsonify
app = Flask(__name__)
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
return response
Detection
Detecting CWE-1104 requires both static analysis and dynamic testing approaches. Here are key detection strategies:
Static Analysis
Code review should focus on:
- Service discovery implementations and endpoint resolution logic
- Header processing and validation routines
- URL construction and validation mechanisms
- Redirect handling and validation
- CORS configuration and policy enforcement
Dynamic Testing
Security testing should include:
- Header injection testing to manipulate request destinations
- URL manipulation attempts to redirect API calls
- CORS policy testing with unauthorized domains
- Service discovery endpoint validation
Automated Scanning with middleBrick
middleBrick's black-box scanning approach can detect CWE-1104 vulnerabilities by testing the unauthenticated attack surface. The scanner examines:
- Header injection vulnerabilities that could redirect requests
- Service discovery misconfigurations through endpoint analysis
- CORS policy weaknesses that allow unauthorized data access
- URL manipulation attempts in API responses
The scanning process takes 5–15 seconds and provides a security risk score with prioritized findings. For example, a misconfigured CORS policy might be flagged as a "Data Exposure" finding with specific remediation guidance.
middleBrick CLI Example
# Scan API endpoint for CWE-1104 vulnerabilities
middlebrick scan https://api.example.com/v1
# Output includes:
# - Security risk score (A-F)
# - CWE-1104 related findings if detected
# - Specific remediation steps
# - Severity level (Critical/High/Medium/Low)
Remediation
Fixing CWE-1104 vulnerabilities requires a defense-in-depth approach with multiple validation layers:
Service Discovery Security
# Secure: Validate service endpoints
import requests
from urllib.parse import urlparse
def get_user_data(user_id):
service_url = discover_service('user-service')
# Validate service URL
parsed = urlparse(service_url)
if not parsed.scheme in ['http', 'https']:
raise ValueError('Invalid service URL scheme')
if not is_whitelisted_service(parsed.netloc):
raise ValueError('Unauthorized service endpoint')
response = requests.get(f"{service_url}/users/{user_id}")
return response.json()
Header Validation
# Secure: Validate Host header
from flask import Flask, request, abort
app = Flask(__name__)
# Whitelist of allowed hosts
ALLOWED_HOSTS = ['api.example.com', 'api.staging.example.com']
@app.route('/api/data')
def api_data():
host = request.headers.get('Host', 'default-service')
if host not in ALLOWED_HOSTS:
abort(400, 'Invalid Host header')
url = f"https://{host}/internal/data"
response = requests.get(url)
return response.json()
Redirect Validation
// Secure: Validate redirect URLs
const url = require('url');
const validRedirectDomains = ['example.com', 'example.org'];
app.get('/api/redirect', (req, res) => {
const redirectUrl = req.query.url;
// Parse and validate URL
const parsedUrl = url.parse(redirectUrl);
if (!parsedUrl.hostname ||
!validRedirectDomains.includes(parsedUrl.hostname)) {
return res.status(400).json({ error: 'Invalid redirect URL' });
}
res.redirect(redirectUrl);
});
CORS Policy Hardening
# Secure: Restrict CORS to specific origins
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
# Only allow specific origins
ALLOWED_ORIGINS = [
'https://example.com',
'https://app.example.com'
]
CORS(app, origins=ALLOWED_ORIGINS)
@app.route('/api/data')
def api_data():
return jsonify({'data': 'secure response'})
Input Validation and Sanitization
# Secure: Sanitize all external inputs
import re
def sanitize_url(input_url):
# Remove potentially dangerous protocols
sanitized = re.sub(r'^(javascript|data|vbscript):', '', input_url, flags=re.IGNORECASE)
# Validate URL structure
try:
result = urlparse(sanitized)
if not all([result.scheme, result.netloc]):
raise ValueError('Invalid URL structure')
return sanitized
except:
raise ValueError('Invalid URL format')