Dns Rebinding in Actix with Api Keys
Dns Rebinding in Actix with Api Keys — how this specific combination creates or exposes the vulnerability
DNS Rebinding is an attack that manipulates DNS responses to make a victim’s browser believe a remote host is reachable at an IP address that is not publicly routable, such as 127.0.0.1 or a local network address. In an Actix web service that relies on API keys for access control, this combination can bypass intended network-level restrictions if the API key is treated as a substitute for network or origin validation.
Actix is a Rust-based web framework, and API keys are commonly implemented as middleware that inspects request headers before routing or business logic executes. If the API key check occurs before or without validating the request origin, an attacker can use a DNS Rebinding sequence to first resolve a domain to a public IP that passes any IP allowlist, then serve a malicious page that rebinds the hostname to a local address. The victim’s browser, now on a page served from the public-facing domain, can make authenticated requests using the valid API key, but to internal endpoints that should not be exposed to external clients.
This works because the API key is often scoped to a user or service identity rather than to a network boundary. The attacker’s malicious page can read responses from the rebound local endpoint and exfiltrate data or perform actions on behalf of the authenticated user, effectively bypassing network segregation. MiddleBrick’s scan checks for weak origin validation and missing same-origin or CORS controls that, when combined with API key usage, can leave such paths open.
In practice, this manifests when an endpoint like /admin or /internal accepts an API key in a header but does not enforce strict source IP or strict CORS rules. The framework’s routing and guards do not inherently prevent a rebinded request; the developer must explicitly validate Origin and, where appropriate, enforce strict referrer policies. Without these, an API key alone cannot protect against a client-side DNS Rebinding pivot.
MiddleBrick’s checks for CORS misconfiguration and input validation can surface missing origin controls that, when paired with API key authentication, create a pathway for rebinding-based access to private services. The scanner also tests for exposed internal endpoints that should never be reachable from the public internet, regardless of authentication.
Api Keys-Specific Remediation in Actix — concrete code fixes
To secure an Actix service using API keys against DNS Rebinding, treat the API key as an authentication credential and enforce strict origin and referrer checks alongside it. Do not rely on network address checks alone, and avoid using API keys to authorize requests that originate from browser contexts without validating the source.
Below is a concrete, syntactically correct example of API key middleware in Actix that validates both the key and the Origin header, rejecting requests with mismatched origins. This pattern reduces the risk of DNS Rebinding by ensuring that even a valid API key cannot be used from unexpected origins.
use actix_web::{dev::ServiceRequest, Error, HttpMessage, web};
use actix_web::http::header::ORIGIN;
use actix_web::middleware::Next;
use std::collections::HashSet;
struct ApiKeyGuard {
valid_keys: HashSet,
allowed_origins: HashSet,
}
impl ApiKeyGuard {
fn new(keys: Vec<&str>, origins: Vec<&str>) -> Self {
Self {
valid_keys: keys.into_iter().map(String::from).collect(),
allowed_origins: origins.into_iter().map(String::from).collect(),
}
}
}
impl actix_web::middleware::Transform for ApiKeyGuard
where
S: actix_web::dev::Service<actix_web::dev::ServiceRequest, Response = actix_web::dev::ServiceResponse, Error = Error>,
S::Future: 'static,
{
type Response = actix_web::dev::ServiceResponse;
type Error = Error;
type InitError = ();
type Transform = ApiKeyMiddleware<S>;
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(ApiKeyMiddleware { service, keys: self.valid_keys.clone(), origins: self.allowed_origins.clone() }))
}
}
struct ApiKeyMiddleware<S> {
service: S,
keys: HashSet<String>,
origins: HashSet<String>,
}
impl<S> actix_web::dev::Service<ServiceRequest> for ApiKeyMiddleware<S>
where
S: actix_web::dev::Service<ServiceRequest, Response = actix_web::dev::ServiceResponse, Error = Error>,
S::Future: 'static,
{
type Response = actix_web::dev::ServiceResponse;
type Error = Error;
type Future = std::pin::Pin<Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&self, req: ServiceRequest) -> Self::Future {
let api_key = match req.headers().get("X-API-Key") {
Some(v) => v.to_str().unwrap_or(""),
None => "",
};
let origin = req.headers().get(ORIGIN).and_then(|v| v.to_str().ok()).unwrap_or("");
if !self.keys.contains(api_key) {
let response = actix_web::error::ErrorUnauthorized("Invalid API key");
return Box::pin(async { Err(response) });
}
if !self.origins.contains(origin) {
let response = actix_web::error::ErrorForbidden("Origin not allowed");
return Box::pin(async { Err(response) });
}
let fut = self.service.call(req);
Box::pin(async move { fut.await })
}
}
/// In main app setup:
/// let guard = ApiKeyGuard::new(vec!["super-secret-key"], vec!["https://trusted.example.com"]);
/// let app = App::new()
/// .wrap(guard)
/// .service(your_routes);
For production, rotate keys regularly and avoid embedding them in JavaScript where possible. When API keys must be used client-side, pair them with strict CORS rules (e.g., Actix’s wrap_fn or a CORS middleware that validates Origin and Access-Control-Allow-Credentials) and consider short-lived tokens to reduce exposure if a rebinding scenario occurs.
MiddleBrick’s GitHub Action can be configured with a threshold to fail builds if risk scores indicate missing origin validation or overly permissive CORS rules. The CLI can produce JSON output that highlights these findings so you can automate remediation checks alongside your API keys policy.