HIGH ssrf server sideactixmongodb

Ssrf Server Side in Actix with Mongodb

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

Server-side request forgery (SSRF) in an Actix web service that uses MongoDB can occur when user-controlled data is used to form network requests or to build dynamic MongoDB queries. In this stack, SSRF is typically not a native database weakness, but an application-level issue enabled by unsafe handling of inputs that flow into HTTP clients or into aggregation pipelines that reach external services.

Actix-web does not enforce any network destination controls by default. If an endpoint accepts a URL or host header and passes it to an HTTP client (for example to fetch metadata or to act as a proxy), an attacker can supply an internal address such as http://169.254.169.254/latest/meta-data/ or a MongoDB connection string that points to a local admin endpoint. Because Actix services often run in cloud or container environments, this can expose instance metadata services or internal MongoDB deployments that are not exposed to the public internet.

When MongoDB is involved, SSRF can also arise through the application’s data layer. Consider an endpoint that builds a MongoDB aggregation pipeline using user input. If an attacker can inject a $lookup stage or a URL-based stage (in MongoDB 5.0+ where allowed), they may cause the server to make outbound requests to attacker-controlled endpoints. For example, a crafted $lookup with a from field derived from user input or a malicious pipeline can result in network calls that leak internal data or bypass network segregation.

Additionally, if the application deserializes user input into BSON and uses it to construct queries, SSRF-related logic can be abused to probe internal services. An attacker might supply a hostname in a parameter that the application later uses with a MongoDB driver to form a connection string or to validate reachability. Because Actix applications often run with elevated privileges inside containers, such probes can map internal infrastructure and lead to further compromise.

middleBrick detects this risk in such stacks by analyzing the unauthenticated attack surface of Actix endpoints that accept or reflect URLs and by inspecting OpenAPI schemas for unsafe parameter usage. If a path parameter or body field can influence network destinations—either via HTTP clients or via MongoDB operations that trigger network activity—the scan can surface SSRF-style findings with contextual remediation guidance.

Mongodb-Specific Remediation in Actix — concrete code fixes

Remediation focuses on strict input validation, avoiding the use of user-controlled data in network operations, and ensuring MongoDB interactions are constrained to known-safe patterns.

1. Validate and whitelist URLs

Do not forward or fetch user-provided URLs. If your Actix endpoint needs to call external services, use a fixed set of destinations or a strict allowlist. For example, reject any URL that does not match an expected host and scheme:

use actix_web::{web, HttpResponse};
use url::Url;

fn is_allowed_url(input: &str) -> bool {
    let parsed = match Url::parse(input) {
        Ok(u) => u,
        Err(_) => return false,
    };
    let host = match parsed.host_str() {
        Some(h) => h,
        None => return false,
    };
    // Strict allowlist: only example.com and its subdomains
    host.ends_with("example.com")
}

async fn safe_endpoint(web::Json(payload): web::Json<serde_json::Value>) -> HttpResponse {
    let url = match payload.get("url").and_then(|v| v.as_str()) {
        Some(u) if is_allowed_url(u) => u,
        _ => return HttpResponse::BadRequest().body("Invalid or disallowed URL"),
    };
    // Proceed with a known-safe destination
    HttpResponse::Ok().body(format!("Using allowed URL: {}", url))
}

2. Avoid dynamic $lookup with user input

Do not construct $lookup stages where the from or pipeline fields are derived from user input. Use static collections or strict validation. The following shows a safe approach using a hardcoded collection name:

use mongodb::{bson::{doc, Document}, Collection};

async fn safe_lookup(users_collection: &Collection, user_id: &str) -> Result, mongodb::error::Error> {
    // Hardcoded, trusted collection name; user input is used only as an _id value after validation
    let pipeline = vec![
        doc! {
            "$match": doc! {
                "_id": user_id
            }
        },
        doc! {
            "$lookup": doc! {
                "from": "profiles",           // static collection name
                "localField": "profileId",
                "foreignField": "_id",
                "as": "profile"
            }
        }
    ];
    users_collection.aggregate(pipeline, None).await.map(|cursor| cursor.try_collect().unwrap_or_default())
}

3. Sanitize inputs used in connection strings

If you must form MongoDB connection strings, do not concatenate user input into the URI. Use environment variables for hosts and credentials, and validate any provided hostnames against a strict pattern. For example, use a fixed host and port and pass credentials via secure configuration:

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

async fn get_mongo_client() -> Result {
    // Read from environment; do not build from user input
    let uri = std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string());
    let mut client_options = ClientOptions::parse(&uri).await?;
    // Ensure hosts are not overridden by user data
    client_options.hosts = vec!["localhost:27017".parse().unwrap()];
    Client::with_options(client_options)
}

4. Limit metadata exposure in error messages

Ensure MongoDB driver and Actix error responses do not leak stack traces or internal hostnames. Use custom error handlers that return generic messages while logging details securely for investigation.

By combining these measures—strict URL allowlists, static aggregation pipelines, and controlled MongoDB connection practices—you reduce the attack surface for SSRF and related data exposure issues in Actix services using MongoDB. Regular scans with tools like middleBrick can help verify that endpoints remain resilient against SSRF-style misuse of URLs and injection into database operations.

Frequently Asked Questions

Can SSRF in Actix with MongoDB be exploited through the $lookup stage?
Yes, if user-controlled fields are used to construct the from or pipeline in a $lookup stage, the MongoDB server may make outbound network requests. Always use static collection names and avoid passing untrusted input into aggregation stages.
How does middleBrick detect SSRF risks in Actix services using MongoDB?
middleBrick analyzes endpoint behavior for unsafe use of inputs that can influence network destinations, such as URL parameters or dynamic MongoDB aggregation pipelines. It checks OpenAPI specs and runtime interactions to surface SSRF-style findings with remediation guidance.