How to Prevent Denial-of-Service in Rust Applications

Prevent DoS in Rust by enforcing strict input size limits and using non-blocking I/O to avoid resource exhaustion.

Prevent Denial-of-Service in Rust by enforcing strict input limits and using non-blocking I/O to avoid resource exhaustion.

use std::io::{self, Read};
use std::time::Duration;

fn read_safe(input: &mut impl Read) -> io::Result<Vec<u8>> {
    let mut buffer = Vec::with_capacity(1024 * 1024); // Limit to 1MB
    let mut timeout = Duration::from_secs(5);
    
    // Note: Actual timeout requires async runtime or platform-specific APIs
    // This example demonstrates the capacity limit principle
    let bytes_read = input.read_to_end(&mut buffer)?;
    
    if bytes_read > 1024 * 1024 {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "Input too large"));
    }
    
    Ok(buffer)
}
  1. Set a maximum buffer size to prevent memory exhaustion.
  2. Validate input length immediately after reading.
  3. Reject requests exceeding the limit with an error.
  4. Use async runtimes like tokio for non-blocking I/O timeouts.