HIGH denial of serviceaxum

Denial Of Service in Axum

How Denial Of Service Manifests in Axum

Denial of Service (DoS) in Axum applications typically manifests through resource exhaustion patterns that exploit the framework's asynchronous nature. The most common vectors include request flooding, slowloris attacks, memory exhaustion from unbounded request processing, and CPU exhaustion from expensive operations without rate limiting.

Request flooding exploits Axum's default behavior of accepting unlimited concurrent connections. Since Axum uses Tokio's default executor without built-in connection limits, an attacker can overwhelm the thread pool by sending thousands of requests simultaneously. This causes legitimate requests to queue indefinitely, effectively denying service to valid users.

Slowloris attacks are particularly effective against Axum because the framework holds connections open until the client completes the request. An attacker can send partial HTTP requests and keep connections alive indefinitely, consuming server resources while doing minimal work. Since Axum doesn't enforce request timeouts by default, these connections remain open until the client disconnects.

Memory exhaustion occurs when handlers process requests without size limits or timeouts. For example, a file upload endpoint without content length validation can be exploited to consume all available memory. Similarly, recursive operations or unbounded data structures in request handlers can lead to heap exhaustion.

CPU exhaustion happens when endpoints perform expensive computations without rate limiting or circuit breakers. An attacker can repeatedly trigger computationally intensive operations like cryptographic operations, database queries, or complex JSON parsing, consuming CPU cycles that should be available for legitimate traffic.

use axum::extract::RequestParts;
use axum::http::Request;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use tokio::time::{sleep, Duration};

// Vulnerable endpoint - no rate limiting
async fn expensive_operation() {
    sleep(Duration::from_millis(100)).await;
    // Simulate expensive computation
}

async fn vulnerable_handler() -> impl IntoResponse {
    expensive_operation().await;
    "OK"
}

let app = Router::new().route("/vulnerable", get(vulnerable_handler));

Axum-Specific Detection

Detecting DoS vulnerabilities in Axum requires both static analysis of the codebase and dynamic runtime monitoring. Static analysis should focus on identifying endpoints without rate limiting, timeout configurations, or size validations.

middleBrick's black-box scanning approach is particularly effective for Axum applications since it tests the actual runtime behavior without requiring source code access. The scanner sends controlled traffic patterns to identify rate limiting gaps, timeout configurations, and resource exhaustion vulnerabilities.

For Axum applications, middleBrick tests authentication bypass scenarios that could lead to DoS by allowing unauthenticated users to trigger expensive operations. It also checks for missing rate limiting on endpoints that perform database queries, file operations, or other resource-intensive tasks.

The scanner's input validation tests are crucial for Axum since the framework's extractors can be exploited if not properly configured. middleBrick sends oversized payloads to test content length validation and malformed requests to test request timeout handling.

middleBrick's continuous monitoring feature is valuable for production Axum applications, as it can detect when DoS vulnerabilities are introduced through code changes or dependency updates. The GitHub Action integration allows teams to automatically scan staging APIs before deployment, ensuring DoS protections are in place.

Runtime monitoring should include tracking request latencies, connection counts, and error rates. Axum's structured logging can be configured to log slow requests, which helps identify endpoints that could be exploited for DoS.

use axum::extract::RequestParts;
use axum::http::Request;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use tower_crate::rate_limit::RateLimitLayer;

// Scan with middleBrick CLI
// $ middlebrick scan https://your-axum-app.com

// Or use the GitHub Action in CI/CD
// - uses: middlebrick/middlebrick-action@v1
//   with:
//     url: ${{ secrets.API_URL }}
//     fail_if_score_below: C

Axum-Specific Remediation

Remediating DoS vulnerabilities in Axum requires implementing multiple layers of protection at both the application and infrastructure levels. The most effective approach combines Axum's native middleware ecosystem with Tokio's concurrency controls.

Rate limiting is the first line of defense. Axum integrates seamlessly with tower-crate's rate limiting middleware, which can be applied globally or to specific routes. The middleware supports various strategies including token bucket, sliding window, and fixed window rate limiting.

Timeout configuration is critical for preventing slowloris attacks and resource exhaustion. Axum applications should configure Tokio's default executor with appropriate timeout settings and use Axum's timeout middleware for individual routes that might perform expensive operations.

Content length validation prevents memory exhaustion from large payloads. Axum's RequestParts extractor allows checking Content-Length headers before processing requests, and the framework can be configured to reject requests exceeding size limits.

Connection limiting prevents request flooding by restricting the number of concurrent connections. This can be implemented using Tokio's semaphore or by configuring the underlying HTTP server (like hyper) with connection limits.

Implementing proper error handling prevents information leakage that could aid attackers. Axum's error handling middleware should provide generic error responses without exposing internal implementation details.

use axum::extract::RequestParts;
use axum::http::Request;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use tower_crate::rate_limit::RateLimitLayer;
use tower_crate::timeout::TimeoutLayer;
use tokio::time::Duration;
use tower::limit::concurrency::ConcurrencyLimitLayer;

// Global rate limiting - 100 requests per minute
let rate_limit_layer = RateLimitLayer::new(100, Duration::from_secs(60));

// Global timeout - 30 seconds for all requests
let timeout_layer = TimeoutLayer::new(Duration::from_secs(30));

// Global connection limit - 1000 concurrent connections
let concurrency_limit_layer = ConcurrencyLimitLayer::new(1000);

let app = Router::new()
    .route("/public", get(public_handler))
    .route("/expensive", get(expensive_handler))
    .layer(rate_limit_layer)
    .layer(timeout_layer)
    .layer(concurrency_limit_layer)
    .layer(TraceLayer::new_for_http());

// Route-specific timeout for expensive operations
async fn expensive_handler() -> impl IntoResponse {
    // This request will timeout after 5 seconds
    tokio::time::timeout(Duration::from_secs(5), expensive_operation()).await??
    "OK"
}

async fn expensive_operation() {
    // Simulate expensive computation
    tokio::time::sleep(Duration::from_millis(100)).await;
}

// Content length validation
async fn upload_handler(RequestParts { headers, .. }: RequestParts) -> impl IntoResponse {
    if let Some(content_length) = headers.get("content-length") {
        if let Ok(length) = content_length.to_str().unwrap().parse::() {
            if length > 10_000_000 { // 10MB limit
                return (413, "Payload Too Large");
            }
        }
    }
    "OK"
}

Related CWEs: resourceConsumption

CWE IDNameSeverity
CWE-400Uncontrolled Resource Consumption HIGH
CWE-770Allocation of Resources Without Limits MEDIUM
CWE-799Improper Control of Interaction Frequency MEDIUM
CWE-835Infinite Loop HIGH
CWE-1050Excessive Platform Resource Consumption MEDIUM

Frequently Asked Questions

How does middleBrick detect DoS vulnerabilities in Axum applications?
middleBrick performs black-box scanning by sending controlled traffic patterns to your Axum endpoints. It tests for missing rate limiting by sending rapid requests, checks timeout configurations by holding connections open, and validates content length enforcement by sending oversized payloads. The scanner runs 12 security checks in parallel and provides a security score with specific findings for each vulnerability category.
Can I integrate middleBrick scanning into my Axum CI/CD pipeline?
Yes, middleBrick offers a GitHub Action that integrates directly into your CI/CD pipeline. You can configure it to scan your staging or production APIs before deployment and fail builds if security scores drop below your threshold. The action supports scanning OpenAPI specifications alongside runtime endpoints, ensuring your API contracts match your security posture.