HIGH ssrf server sideaxummongodb

Ssrf Server Side in Axum with Mongodb

Ssrf Server Side in Axum with Mongodb — how this specific combination creates or exposes the vulnerability

Server-side request forgery (SSRF) in an Axum service that uses MongoDB can occur when user-controlled input is used to form HTTP requests initiated by the server and when those requests influence MongoDB operations. For example, an endpoint that accepts a URL parameter to fetch external data and then writes that data into MongoDB can allow an attacker to direct the server to internal endpoints or metadata services. In Rust, if an HTTP client is invoked with a user-supplied string without strict validation, an attacker can supply an internal address such as http://169.254.169.254/latest/meta-data/iam/security-credentials/ to reach cloud metadata from within the server environment. If the response is then stored in a MongoDB collection without validation, the SSRF becomes a data-exposure vector. Axum does not restrict what targets your HTTP client may call; the risk arises when application logic trusts external input. MongoDB itself does not cause SSRF, but the way fetched data is handled before insertion can amplify impact, such as storing sensitive responses or triggering side effects in downstream systems. The SSRF issue is not specific to MongoDB, yet the combination matters because MongoDB can persist maliciously obtained data and later expose it through other endpoints or administrative interfaces. Attackers may also leverage SSRF to reach MongoDB instances that are bound to localhost if the server is misconfigured to proxy requests internally. MiddleBrick scans such endpoints to detect SSRF by observing whether outbound requests are made to internal or unexpected targets and whether responses are persisted, providing findings mapped to OWASP API Top 10 and related guidance.

Mongodb-Specific Remediation in Axum — concrete code fixes

To mitigate SSRR in Axum while working with MongoDB, validate and restrict all external inputs before using them for HTTP requests or database writes. Use a strict allowlist for URLs, prefer typed configuration over dynamic user-provided targets, and avoid passing raw user input to HTTP clients. When storing data into MongoDB, validate content and enforce schema rules. Below are concrete Rust examples for Axum handlers that implement these practices.

1. Validate URL input before making HTTP requests

Ensure the user-controlled URL is limited to expected domains and schemes. Do not allow internal IPs or metadata addresses.

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

async fn fetch_data(url: String) -> Result {
    // Strict allowlist: only HTTPS to known external domains
    let parsed = url.parse::().map_err(|_| {
        reqwest::Error::new(reqwest::StatusCode::BAD_REQUEST, "Invalid URL")
    })?;
    if parsed.scheme() != "https" {
        return Err(reqwest::Error::new(reqwest::StatusCode::BAD_REQUEST, "Only HTTPS allowed"));
    }
    let host = parsed.host_str().unwrap_or("");
    if host.ends_with("internal.example.com") || host == "127.0.0.1" || host == "169.254.169.254" {
        return Err(reqwest::Error::new(reqwest::StatusCode::BAD_REQUEST, "Blocked target"));
    }
    let client = Client::new();
    let resp = client.get(url).send().await?;
    resp.text().await
}

async fn handler(url: String) -> Result {
    fetch_data(url).await.map_err(|e| (e.status().unwrap_or(axum::http::StatusCode::BAD_REQUEST), e.to_string()))
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/fetch", get(|url: String| async move { handler(url).await }));
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr).serve(app.into_make_service()).await.unwrap();
}

2. Sanitize and validate data before MongoDB insertion

Use MongoDB Rust driver with validated BSON documents and avoid directly inserting raw text from external sources without checks.

use mongodb::{Client, options::ClientOptions};
use serde_json::Value;

async fn store_fetched_data(uri: &str, content: &str) -> mongodb::error::Result<()> {
    let client_options = ClientOptions::parse("mongodb://localhost:27017").await?;
    let client = Client::with_options(client_options)?;
    let db = client.database("appdb");
    let collection = db.collection("external");

    // Validate content size and structure before insertion
    let doc: Value = serde_json::from_str(content).map_err(|_| {
        mongodb::error::Error::from(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid JSON"))
    })?;
    if doc.as_object().map_or(true, |o| o.is_empty()) {
        return Err(mongodb::error::Error::from(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Empty document")));
    }

    collection.insert_one(doc, None).await?;
    Ok(())
}

#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
    store_fetched_data("https://example.com/data", "{\"safe\": true}").await
}

3. Combine SSRF-safe fetching with MongoDB storage in an Axum handler

Integrate the validated fetch and store steps to ensure data from external sources is not used to compromise internal services or stored unchecked.

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

#[derive(Deserialize)]
struct FetchRequest {
    url: String,
}

#[derive(Serialize)]
struct ApiResponse {
    message: String,
}

async fn safe_fetch_and_store(Json(payload): Json) -> Result, (axum::http::StatusCode, String)> {
    let content = fetch_data(payload.url).await?;
    store_fetched_data("mongodb://localhost:27017", &content).await.map_err(|e| {
        (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
    })?;
    Ok(Json(ApiResponse { message: "Stored safely".to_string() }))
}

// In main, attach the route as before

Frequently Asked Questions

Can SSRF in Axum with MongoDB lead to unauthorized access to the database?
Yes, if the server uses SSRF to reach an internal MongoDB instance that is improperly exposed or accepts connections from the server without authentication, an attacker may influence what data is stored or retrieve sensitive information. Mitigations include network segmentation, binding MongoDB to localhost without proxying external input, and strict input validation.
Does middleBrick detect SSRF when MongoDB is involved?
middleBrick scans endpoints and identifies SSRF by analyzing outbound requests and data persistence patterns. It checks whether user-influenced requests reach internal or unexpected targets and whether responses are written to storage, providing findings with remediation guidance independent of the database used.