Cors Wildcard in Axum
How Cors Wildcard Manifests in Axum
CORS wildcard configurations in Axum can create significant security vulnerabilities when improperly implemented. The most common manifestation occurs when developers use overly permissive allow_origin settings that accept any origin, effectively disabling cross-origin protections.
use axum::extract::CorsLayer;
use axum::routing::get;
use axum::Router;
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(
CorsLayer::new()
.allow_origin("*")
.allow_methods(vec!["GET", "POST", "PUT", "DELETE"])
.allow_headers(vec!["Content-Type", "Authorization"])
);
This configuration allows any website to make cross-origin requests to your API, enabling several attack vectors:
- Credential leakage: Malicious sites can read responses from authenticated API calls made by your users
- CSRF bypass: While CORS doesn't prevent CSRF, wildcard origins combined with
Access-Control-Allow-Credentials: truecreates dangerous combinations - Data exfiltration: Attackers can craft requests that include sensitive user data in responses accessible to their domains
A more subtle manifestation occurs with dynamic origin validation failures. Developers often attempt to implement "secure" wildcard behavior:
use axum::extract::CorsLayer;
use axum::http::HeaderValue;
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(
CorsLayer::new()
.allow_origin_fn(|origin| {
// Flawed logic: only checks TLD
origin.as_str().ends_with(".example.com")
})
);
This approach fails against subdomain takeover attacks and IDN homograph attacks. An attacker registering examplє.com (using Cyrillic 'р') bypasses this check.
Another Axum-specific manifestation involves middleware ordering. CORS middleware must execute before authentication and authorization checks:
// INSECURE: CORS applied after auth
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(auth_layer())
.layer(
CorsLayer::new()
.allow_origin("*")
);
// SECURE: CORS applied first
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(
CorsLayer::new()
.allow_origin("https://yourdomain.com")
)
.layer(auth_layer());
The insecure ordering allows unauthenticated preflight requests to succeed, potentially exposing API structure to attackers before authentication fails.
Axum-Specific Detection
Detecting CORS wildcard vulnerabilities in Axum applications requires both static analysis and runtime testing. Using middleBrick's API security scanner provides comprehensive detection:
# Install middleBrick CLI
npm install -g middlebrick
# Scan your Axum API
middlebrick scan https://yourapi.com
middleBrick specifically tests for CORS misconfigurations by:
- Sending cross-origin requests with various origins and methods
- Analyzing
Access-Control-Allow-Originheaders for wildcard patterns - Testing credentialed requests with wildcard origins
- Checking for overly permissive
Access-Control-Allow-Methodsheaders
For manual detection in Axum codebases, search for these patterns:
grep -r "allow_origin.*\"*\"" src/ # Wildcard origins
grep -r "allow_origin_fn" src/ # Dynamic origin validation
Look for these red flags in your Axum middleware chain:
use axum::extract::CorsLayer;
// Red flag: wildcard with credentials
let cors = CorsLayer::new()
.allow_origin("*")
.allow_credentials(true); // DANGEROUS
// Red flag: overly permissive methods
let cors = CorsLayer::new()
.allow_origin("https://trusted.com")
.allow_methods(vec!["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]);
middleBrick's LLM/AI security module also detects if your Axum API serves AI endpoints with CORS misconfigurations, testing for system prompt leakage through cross-origin requests to AI endpoints.
Axum-Specific Remediation
Remediating CORS wildcard vulnerabilities in Axum requires precise configuration. Start by defining exact allowed origins:
use axum::extract::CorsLayer;
let allowed_origins = vec![
"https://yourapp.com",
"https://admin.yourapp.com",
"https://api.yourapp.com",
];
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(
CorsLayer::new()
.allow_origin(allowed_origins)
.allow_methods(vec!["GET", "POST"])
.allow_headers(vec!["Content-Type", "Authorization"])
.allow_credentials(true) // Only if needed
);
For applications requiring dynamic origin validation, implement strict domain verification:
use axum::extract::CorsLayer;
use axum::http::HeaderValue;
use axum::middleware::Next;
use axum::response::IntoResponse;
fn validate_origin(origin: &str) -> bool {
let allowed_domains = ["yourapp.com", "yourapp.io"];
if let Ok(domain) = url::Url::parse(origin) {
let host = domain.host_str().unwrap_or("");
allowed_domains.iter().any(|allowed| host.ends_with(allowed))
} else {
false
}
}
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(
CorsLayer::new()
.allow_origin_fn(validate_origin)
.allow_credentials(true)
);
Implement proper middleware ordering to ensure CORS checks occur before sensitive operations:
use axum::extract::CorsLayer;
use axum::middleware::Next;
use axum::response::IntoResponse;
let cors = CorsLayer::new()
.allow_origin("https://yourapp.com")
.allow_methods(vec!["GET", "POST"]);
let auth = axum::middleware::from_fn(|mut req: Request, next: Next| async move {
// Authentication logic
next.run(req).await
});
let app = Router::new()
.route("/api/*", get(api_handler))
.layer(cors) // CORS first
.layer(auth); // Then auth
For AI/ML endpoints in Axum, apply additional CORS restrictions:
let ai_router = Router::new()
.route("/chat/*", post(chat_handler))
.layer(
CorsLayer::new()
.allow_origin("https://yourapp.com")
.allow_methods(vec!["POST"])
.allow_headers(vec!["Content-Type"])
.max_age(0) // Disable caching of preflight responses
);
Test your remediation using middleBrick's continuous monitoring in the Pro plan to ensure CORS configurations remain secure as your API evolves.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
Why is allowing credentials with wildcard origins dangerous in Axum?
Allowing credentials (allow_credentials(true)) with wildcard origins (allow_origin("*")) is dangerous because browsers will reject this combination entirely, but if you use allow_origin_fn that returns true for all origins while enabling credentials, it creates a security bypass. Attackers can read authenticated user data through cross-origin requests, effectively stealing session cookies and tokens.
How does middleBrick detect CORS wildcard vulnerabilities in Axum APIs?
middleBrick sends cross-origin requests with various origins to your Axum API endpoints, analyzing the Access-Control-Allow-Origin headers for wildcard patterns (*). It tests credentialed requests, checks if overly permissive methods are allowed, and verifies that dynamic origin validation isn't vulnerable to subdomain takeover or IDN homograph attacks. The scanner provides specific findings with severity levels and remediation guidance tailored to your Axum implementation.