HIGH formula injectionactixmutual tls

Formula Injection in Actix with Mutual Tls

Formula Injection in Actix with Mutual Tls

Formula Injection occurs when user-controlled data is concatenated into executable formulas, scripts, or configuration language that a downstream system interprets. In Actix-web, this risk can emerge when an endpoint accepts a parameter intended for a calculation, template, or spreadsheet-like expression and passes it to a service that evaluates the result. When Mutual Transport Layer Security (Mutual Tls) is used, the client presents a certificate, which may be inspected and logged by the server or middleware. If the code treats certificate fields (such as the Common Name or Subject Alternative Names) as part of a formula input, or reflects them in responses that downstream systems evaluate, the combination of Mutual Tls and formula evaluation can expose sensitive logic or enable injection.

Consider an Actix endpoint that accepts a numeric parameter for a financial calculation and also receives the client certificate. A developer might log or forward the certificate subject together with the parameter to an evaluation service that parses expressions. If the subject contains attacker-controlled values and is merged into the expression without validation, the attacker can inject crafted payloads. For example, a subject like CN=1;system("rm -rf /") could be appended to a formula string and later interpreted by an unsafe evaluator, leading to unintended command execution or logic manipulation. The Mutual Tls handshake ensures authenticated clients, but it does not sanitize the content of certificate attributes; if those attributes become part of formula construction, the server must treat them as untrusted input.

Another scenario involves an Actix service that uses client certificates for authorization and builds dynamic configuration or query strings from certificate metadata. If the code interpolates certificate fields into a JSON payload that is later evaluated as a formula or passed to an interpreter, injection can occur. For instance, embedding the organization unit in an expression like base + org_unit without escaping or type validation allows attackers to close the expression and append malicious syntax. Because Mutual Tls provides identity, developers may assume safety and skip input validation, increasing the likelihood of formula injection. The key is to treat certificate-derived data as any other external input: validate, sanitize, and avoid direct concatenation into evaluatable expressions.

Mutual Tls-Specific Remediation in Actix

To mitigate formula injection when using Mutual Tls in Actix, treat certificate fields as untrusted and enforce strict input validation before any formula construction. Do not directly interpolate certificate subject fields into expressions. Instead, map certificate attributes to a controlled set of values or identifiers and apply parameterized handling. Below are concrete code examples demonstrating secure practices.

use actix_web::{web, App, HttpServer, Responder, HttpRequest};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

fn create_ssl_config() -> SslAcceptor {
    let mut builder = SslAcceptor::mozilla_server(SslMethod::tls()).unwrap();
    builder.set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
    builder.set_certificate_chain_file("cert.pem").unwrap();
    builder.set_verify(openssl::ssl::SslVerifyMode::PEER | openssl::ssl::SslVerifyMode::FAIL_IF_NO_PEER_CERT, verify_callback);
    builder.build()
}

fn verify_callback(ssl: &openssl::ssl::Ssl) -> bool {
    // Perform certificate validation using OpenSSL APIs
    // Ensure the certificate meets policy requirements
    true
}

async fn calculate(query: web::Query, req: HttpRequest) -> impl Responder {
    // Extract certificate subject as an identifier, not as formula input
    let subject = req.extensions().get::()
        .map(|s| s.as_str())
        .unwrap_or("unknown");

    // Validate and map subject to an allowed role or tenant
    let tenant_id = match subject {
        "CN=tenantA,O=Example" => 1,
        "CN=tenantB,O=Example" => 2,
        _ => return actix_web::error::ErrorBadRequest("Unauthorized subject"),
    };

    // Use parameterized values in calculations, never concatenate raw subject into expressions
    let result = compute_formula(query.value, tenant_id);
    format!("Result: {}", result)
}

fn compute_formula(value: f64, tenant_id: i32) -> f64 {
    // Safe: value is numeric and tenant_id is controlled; no string interpolation into formula
    (value * 100.0) + (tenant_id as f64 * 0.5)
}

#[derive(serde::Deserialize)]
struct CalcParams {
    value: f64,
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let ssl = create_ssl_config();
    HttpServer::new(move || {
        App::new()
            .wrap(actix_web_httpauth::middleware::HttpAuthentication::basic(|_req, credentials| {
                // Not used; client cert provides identity
                Ok(())
            }))
            .service(web::resource("/calc").route(web::get().to(calculate)))
    })
    .bind_openssl("127.0.0.1:8443", ssl)?
    .run()
    .await
}

In this example, the client certificate is used only for authentication and authorization. The subject is mapped to a tenant identifier, and the identifier is used as a numeric parameter in a safe computation. No raw certificate fields are concatenated into expressions that could be interpreted as formulas. This approach prevents formula injection while still leveraging Mutual Tls for client identity.

Additionally, avoid building dynamic formulas by string concatenation. If your application must construct expressions, use a dedicated parser with a strict grammar and reject any input that does not conform. Combine this with Mutual Tls to ensure that only authenticated clients submit data, but do not rely on authentication alone to prevent injection. Regularly review how certificate metadata flows through your application to ensure it never reaches evaluatable contexts.

Frequently Asked Questions

Can Mutual Tls alone prevent formula injection in Actix?
No. Mutual Tls provides client authentication, but certificate fields such as subject or extensions remain untrusted input. If these fields are concatenated into formulas or expressions, formula injection can still occur. You must validate and sanitize certificate-derived data before using it in any evaluatable context.
What should I do if my Actix service uses certificate metadata in calculations?
Map certificate attributes to a controlled set of identifiers or enums, and use those identifiers as numeric or enumerated parameters in calculations. Avoid string interpolation of certificate fields into formulas, and employ a dedicated expression parser with a strict grammar if dynamic formulas are required.