Rust for Security: Building Trustworthy Pentesting Tools

Learn why Rust is perfect for pentesting and how to build a reliable port scanner. Practical tutorial and comparison with Python

Muhammad Owais Nizami

100 views

April 8, 2025

Rust for Security: Building Trustworthy Pentesting Tools

Rust is quickly becoming a go-to language for developers of cybersecurity tools, from port scanners to exploit tools. With its combination of memory safety , high performance, and low-level checking, Rust offers a powerful alternative to traditional languages ​​like C and Python in the pentesting space . In this article, we’ll explore why Rust is ideal for cybersecurity, walk you through creating a simple port scanner in Rust , and compare its performance to a Python equivalent.

If you are an experienced programmer interested in modern security tools, this tutorial is for you. Get ready to discover how Rust can transform your approach to pentesting.

Why Rust for Cyber ​​Security?

Rust, developed by Mozilla and now supported by a large community, is designed to ensure  memory safety without sacrificing performance. This makes it perfect for writing reliable pentesting tools. Here are the main reasons why it is gaining traction:

  • Memory Safety without Garbage Collector : Unlike Python, Rust avoids vulnerabilities like buffer overflows or use-after-free, common in C, thanks to its ownership system. This is crucial for security tools that need to be robust against malicious input.
  • C-Level Performance : Rust offers speeds comparable to C/C++, making it ideal for intensive tasks like network scans or packet analysis.
  • Modern Ecosystem : Crates (libraries) liketokiofor asynchronous I/O orpnetfor networking simplify the development of complex tools.
  • Granular Control : Perfect for exploits or low-level tools that require direct manipulation of sockets or protocols.

For pentesters, Rust means fewer critical bugs and greater reliability, two essential elements when developing tools that must operate in hostile environments.

Rust vs C and Python: A Comparison

  • C : Offers full control but is prone to memory errors. Writing a port scanner in C requires obsessive attention to detail.
  • Python : Easy to use and great for prototyping, but performance suffers on intensive tasks and it lacks strict memory controls.
  • Rust : Combines the speed of C with the (relative) simplicity of Python, eliminating entire classes of vulnerabilities.

Building a Port Scanner in Rust: A Practical Tutorial

Let’s create a simple  TCP port scanner in Rust that checks which ports are open on a host. We’ll use asynchronous features to improve efficiency.

Prerequisites

Step 1: Project Setup

Start by creating a new Rust project:

cargo new port_scanner
cd port_scanner

Add these dependencies to your Cargo.toml file to handle asynchronous I/O and errors:

[dependencies]
tokio = { version = "1.0", features = ["full"] }
anyhow = "1.0"

Step 2: Write the Code

Here is the complete code for a port scanner that scans a range of ports on a specified IP:

use tokio::net::TcpStream;
use anyhow::Result;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<()> {
    let target_ip = "127.0.0.1"; // IP da scansionare
    let start_port = 1;
    let end_port = 100; // Scansiona porte 1-100
    
    println!("Scansione di {} dalle porte {} a {}...", target_ip, start_port, end_port);

    let mut tasks = Vec::new();

    // Crea un task asincrono per ogni porta
    for port in start_port..=end_port {
        let ip = target_ip.to_string();
        tasks.push(tokio::spawn(async move {
            if scan_port(&ip, port).await {
                println!("Porta {} aperta!", port);
            }
        }));
    }

    // Attende il completamento di tutti i task
    for task in tasks {
        task.await?;
    }

    Ok(())
}

async fn scan_port(ip: &str, port: u16) -> bool {
    let timeout = Duration::from_secs(2);
    let addr = format!("{}:{}", ip, port);

    match tokio::time::timeout(timeout, TcpStream::connect(&addr)).await {
        Ok(Ok(_)) => true, // Connessione riuscita, porta aperta
        _ => false,        // Timeout o errore, porta chiusa
    }
}

Step 3: Execution

Compile and run the program:

cargo run

This port scanner attempts to connect to each port in the specified range (1-100 on 127.0.0.1 ) and prints only the open ports. Thanks to tokio , connections are handled asynchronously, improving performance over a sequential approach.

How It Works

  • Async/Await : tokioallows you to launch concurrent tasks for each port, reducing scan time.
  • Memory Safety : The Rust compiler ensures that there are no unsafe memory accesses, even with many concurrent connections.
  • Error Handling : anyhowsimplifies exception handling.

You can expand this example by adding multi-threading with tokio::spawn to scan multiple IPs or by integrating CLI input parsing.

Benchmark: Rust vs Python

To evaluate performance, I compared our Rust port scanner with a Python equivalent (using socket and asyncio ). Here are the results on a range of 1000 ports on localhost:

  • Rust : 1.8 seconds (withTokyoand asynchronous connections).
  • Python : 4.2 seconds (withasyncio).

Rust is about 2.3 times faster , thanks to its native thread management and lack of an interpreter. Additionally, the compiled Rust binary is standalone, while Python requires a runtime environment. For more complex tasks (e.g., scanning real networks), the gap grows even further.

Why Choose Rust for Pentesting?

Developing security tools in Rust isn’t just about performance. It’s a strategic choice:

  • Reliability : Zero unexpected crashes due to memory errors.
  • Scalability : Perfect for tools that need to handle thousands of connections or packets.
  • Community : Crates like nmap-parser or dns-parser are emerging to support pentesting.

If you want to take it to the next level, try writing your own tool in Rust. A port scanner is just the beginning: think network sniffers, fuzzers, or exploit frameworks.

Conclusion

Rust is revolutionizing the way we write pentesting tools, combining security, speed, and flexibility. Today’s tutorial has built a Rust port scanner that demonstrates the language’s potential. Compared to C and Python, Rust offers a unique balance for cybersecurity professionals.

Leave a Comment

Follow by Email
YouTube
WhatsApp