HIGH dangling dnsaxumapi keys

Dangling Dns in Axum with Api Keys

Dangling Dns in Axum with Api Keys — how this specific combination creates or exposes the vulnerability

A dangling DNS configuration in an Axum service becomes more exploitable when API keys are used for routing or tenant isolation. Axum is a Rust web framework, and in API designs it often relies on middleware to extract and validate API keys before routing requests to the correct handler. If the routing logic uses a hostname or subdomain derived from the API key or tenant identifier, and that identifier is not strictly validated, an attacker can supply a crafted key that resolves to an internal or unintended host.

In practice, this can happen when an Axum app uses a key-to-service mapping to forward requests internally, for example in a multi-tenant setup where each tenant has a subdomain like tenant-{key}.api.example.com. If the key is accepted without strict format validation and the application performs DNS resolution on the derived hostname, an attacker can point the key to a dangling or internal DNS name that resolves unpredictably. This may expose non-public endpoints, internal services, or trigger SSRF-like behavior when combined with other weaknesses.

The risk is compounded because Axum typically expects structured routing and typed extractors; if a developer uses the API key to dynamically build a URI or hostname without strict allowlisting, the unvalidated input becomes a pivot point. For example, an API key like tenant1.attacker-controlled.example.com could lead the application to resolve an internal hostname, bypassing expected network boundaries. middleBrick detects such patterns by correlating OpenAPI routing definitions with runtime behavior, highlighting mismatches between declared authentication schemes and observed key usage patterns.

middleBrick’s LLM/AI Security checks are especially relevant in API ecosystems where language models assist developers in generating routing or key-validation code. The scanner checks for system prompt leakage and active prompt injection attempts that could be used to manipulate key validation logic. These checks are valuable because insecure key handling can be introduced inadvertently when using AI-generated snippets for routing or tenant resolution in Axum.

When evaluating an Axum API, middleBrick runs unauthenticated scans focused on the public attack surface. It tests whether API keys accepted by the service can influence DNS resolution paths, and whether responses reveal internal hostnames or errors that should not be exposed. Findings include severity-ranked items, remediation guidance, and mappings to frameworks such as OWASP API Top 10 and common misconfigurations in API gateways or service meshes.

Api Keys-Specific Remediation in Axum — concrete code fixes

Secure handling of API keys in Axum requires strict validation, type-safe extraction, and no dynamic DNS construction from key material. Below are concrete, safe patterns you can apply.

1. Use typed extractors and reject malformed keys

Define a wrapper that only accepts keys matching an allowlist or strict regex, and use Axum extractors to enforce this before any routing logic.

use axum::{{
    async_trait,
    extract::{FromRequest, Request},
    http::StatusCode,
}};
use std::convert::Infallible;

/// A safe API key extractor that validates format and rejects dangerous characters.
struct ValidatedApiKey(String);

#[async_trait]
impl FromRequest for ValidatedApiKey
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);

    async fn from_request(req: Request, _state: &S) -> Result {
        let key = req.headers()
            .get("x-api-key")
            .and_then(|v| v.to_str().ok())
            .filter(|k| is_valid_key(k)) // strict validation
            .ok_or((StatusCode::UNAUTHORIZED, "Invalid or missing API key"))?;
        Ok(ValidatedApiKey(key.to_string()))
    }
}

fn is_valid_key(key: &str) -> bool {
    // Example: alphanumeric with optional hyphens, fixed length
    key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') && key.len() == 32
}

2. Avoid building hostnames from API keys

Never interpolate API keys into hostnames or paths that could lead to DNS confusion. If multi-tenancy requires subdomains, map keys to tenant IDs through a secure lookup table instead of string concatenation.

use axum::{routing::get, Router};
use std::net::SocketAddr;

async fn handler(key: ValidatedApiKey) -> &'static str {
    // Map key to tenant via secure store, not string manipulation
    match resolve_tenant(&key.0) {
        Ok(tenant) => tenant,
        Err(_) => "unknown",
    }
}

fn resolve_tenant(key: &str) -> Result<&'static str, &'static str> {
    // Example static mapping; in production use a secure, cached lookup
    match key {
        "abc123..." => Ok("tenant-a"),
        "def456..." => Ok("tenant-b"),
        _ => Err("not found"),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/resource", get(|key: ValidatedApiKey| async move { handler(key) }));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

3. Enforce strict routing definitions and disable dynamic host resolution

Define routes explicitly and avoid runtime URI composition that depends on API key content. If you must support dynamic routing, validate the target against a strict allowlist of internal services and avoid DNS lookups on user-controlled input.

4. Use middleBrick to validate your API surface

Run middleBrick scans against your Axum endpoints to detect risky patterns such as unauthenticated endpoints, improper key usage, and potential SSRF indicators. The CLI tool and GitHub Action help you enforce security gates in development and CI/CD pipelines.

# Example CLI usage
middlebrick scan https://api.example.com/openapi.json

By combining strict key validation, safe routing patterns, and automated scanning, you reduce the likelihood that a dangling DNS misconfiguration can be leveraged through API keys in Axum services.

Frequently Asked Questions

Can a dangling DNS issue be triggered without API keys in Axum?
Yes. Any user-supplied input used to construct hostnames or perform DNS lookups can lead to dangling DNS or SSRF-like behavior, even without API keys. Validate and restrict all external inputs.
Does middleBrick fix dangling DNS misconfigurations in Axum?
No. middleBrick detects and reports findings with remediation guidance. You must apply secure coding practices and configuration changes to address issues.