HIGH server side template injectionaxumbasic auth

Server Side Template Injection in Axum with Basic Auth

Server Side Template Injection in Axum with Basic Auth — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) occurs when an attacker can inject template expressions that are subsequently evaluated by a server-side templating engine. In Axum, this typically arises when user-controlled input is passed into a rendering function without proper escaping or sandboxing. Axum does not include a built-in HTML template engine, but it is commonly paired with crates like askama, tera, or handlebars-rust. When these engines process unsanitized input, they may interpret template syntax, enabling arbitrary code execution or information disclosure.

Combining SSTI with Basic Auth creates a nuanced attack surface. Basic Auth is often used for initial authentication, but if the application uses the authenticated identity (e.g., username or roles from the Basic Auth header) within a template, an attacker who can influence the authentication context may exploit this to inject malicious template content. For example, if a handler extracts the identity from the request’s authorization header and passes it directly to a template, an attacker who can partially control the credentials (e.g., via a proxy or misconfigured client) might inject template metacharacters.

Consider a scenario where a Basic Auth username is used to personalize a response via a template. If the username is not validated and is rendered using a vulnerable engine, characters like {{ and }} in the username could trigger template evaluation. In tera, this could lead to execution of arbitrary filters or access to internal context, potentially exposing configuration or triggering local file inclusion depending on how the template is defined. The risk is compounded when the application processes unauthenticated or partially trusted inputs alongside authenticated ones, as the boundary between trusted and untrusted data blurs.

middleBrick can detect such misconfigurations by analyzing the unauthenticated attack surface and cross-referencing OpenAPI specifications with runtime behavior. For instance, if an endpoint accepts Basic Auth and also references user-controlled data in templates, the scanner can flag unsafe data flow patterns. Findings may include evidence of insufficient input validation around authenticated identifiers and exposure of internal context through templates, both of which map to OWASP API Top 10 categories such as Broken Object Level Authorization and Injection.

Real-world CVEs in related ecosystems, such as those affecting templating crates, illustrate the impact. An attacker might leverage SSTI to access filesystem paths or execute system commands, depending on the template engine’s capabilities and the application’s environment. Because Axum relies on external crates for rendering, the security of the integration depends heavily on correct configuration and strict input validation, especially when authentication data is involved.

Basic Auth-Specific Remediation in Axum — concrete code fixes

Remediation focuses on ensuring that authenticated data never reaches templates unescaped and that template engines are configured securely. Below are concrete Axum examples demonstrating safe handling of Basic Auth credentials.

1. Avoid passing authentication data directly to templates: Instead of injecting the username or parsed credentials into the template context, use them only for access control or logging.

use axum::{routing::get, Router};
use tower_http::auth::{AuthLayer, credentials::BasicAuth};

async fn handler() -> String {
    // Safe: return a static or sanitized response
    "Welcome".to_string()
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(AuthLayer::basic(|_: &str, _: &str| async { Ok(Some(BasicAuth::default())) }));
}

2. Validate and sanitize any user-derived data before templating: If you must include user data, use allowlists and strict encoding.

use axum::{routing::get, Json};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct Claims {
    username: String,
}

#[derive(Serialize)]
struct SafeTemplateData {
    username: String,
}

async fn handler(Json(payload): Json) -> Json {
    // Validate username format (alphanumeric only)
    let safe_username = payload.username
        .chars()
        .filter(|c| c.is_alphanumeric())
        .collect::();
    Json(SafeTemplateData { username: safe_username })
}

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

3. Configure template engines with autoescaping: When using Askama, enable autoescaping to neutralize injected template syntax.

// In your Askama template (templates/user.html.j2):
// {{ username | e }} ensures HTML escaping

// In Rust handler:
use askama::Template;

#[derive(Template)]
#[template(path = "user.html")]
struct UserTemplate {
    username: String,
}

async fn handler() -> UserTemplate {
    UserTemplate { username: "trusted_user".to_string() }
}

4. Use middleware to strip or reject suspicious characters early: Intercept requests containing template metacharacters in authentication headers before they reach handlers.

use axum::{http::HeaderValue, middleware::Next, response::Response, Extension, Json};
use std::convert::Infallible;

async fn validation_middleware(
    headers: axum::http::Headers,
    next: Next,
) -> Result {
    if let Some(auth) = headers.get("authorization") {
        if auth.to_str().unwrap_or("").contains("{{") {
            return Ok(Response::builder()
                .status(400)
                .body("Invalid characters".into())
                .unwrap());
        }
    }
    next.run().await
}

Frequently Asked Questions

How can I test if my Axum Basic Auth integration is vulnerable to SSTI?
Use middleBrick to scan your endpoint. Submit the URL via the CLI (`middlebrick scan `) or Web Dashboard. The scanner will test unauthenticated surfaces and, if authentication data is reflected in templates, it will flag potential SSTI indicators such as unescaped template syntax in responses.
Does middleBrick fix SSTI vulnerabilities in Axum?
middleBrick detects and reports findings with remediation guidance, but it does not fix vulnerabilities. You must apply the suggested code changes, such as validating inputs, using autoescaping templates, and avoiding injection of authentication data into template contexts.