In an era of increasing cyber threats, protecting our digital assets has become more crucial than ever. As a VPS (Virtual Private Server) owner, I found myself searching for effective ways to secure my server against potential attacks. Traditional firewalls, while useful, often fall short in detecting and preventing more sophisticated probing attempts.
This quest for better security led me to develop a firewall system using Rust. I wanted to create a solution that blocks malicious traffic based on TCP SYN packet analysis. This project emerged from a personal need and has evolved into a tool that I believe can benefit many in the tech community.
Running a VPS comes with its own set of security challenges:
- Constant Probing: VPS instances are often targets of continuous port scans and probing attempts.
- Dynamic Threats: Attack patterns evolve rapidly, making static security rules less effective over time.
- Resource Constraints: Many VPS instances have limited resources, requiring efficient security solutions.
- Remote Management: Being physically separate from the server necessitates robust, autonomous security measures.
This firewall system:
- Monitors network traffic for TCP SYN packets
- Detects potential port scanning attempts
- Automatically blocks IPs that send too many SYN packets
- Implements a time-based unblocking mechanism
- Uses iptables for IP blocking
Rust is an excellent choice for systems programming due to its:
- Memory safety: Prevents common bugs like buffer overflows
- Concurrency: Allows efficient handling of multiple connections
- Performance: Offers speed comparable to C/C++
- Modern syntax: Enhances readability and maintainability
The firewall performs these key functions:
- Captures network packets in real-time
- Analyzes TCP SYN flags to detect potential port scans
- Tracks SYN packets from each IP address
- Automatically blocks IPs exceeding a defined threshold (3 packets)
- Unblocks IPs after a set duration (10 minutes)
- A Linux system with root access
- Rust programming environment (install from rust-lang.org)
- libpcap-dev library for packet capture
- iptables (usually pre-installed on Linux systems)
First, create a new Rust project:
cargo new intelligent_firewall
cd intelligent_firewall
Update Cargo.toml with necessary dependencies:
[package]
name = "intelligent_firewall"
version = "0.1.0"
edition = "2021"
[dependencies]
pcap = "0.9"
pnet = "0.31.0"
nix = "0.26"
We define two key structures:
#[derive(Clone)]
struct ScanInfo {
count: u32,
timestamp: SystemTime,
}
struct BlockTask {
ip: IpAddr,
unblock_time: SystemTime,
}
ScanInfo
: Tracks the number of scan attempts and the timestamp of the first attemptBlockTask
: Represents a blocked IP and its scheduled unblock time
The heart of our system is the handle_packet
function:
fn handle_packet(
ethernet: &EthernetPacket,
scan_tracker: &Arc<Mutex<HashMap<IpAddr, ScanInfo>>>,
unblock_tasks: &Arc<Mutex<Vec<BlockTask>>>,
) {
// Implementation details in the full code
}
This function:
- Extracts IP and TCP information from the packet
- Checks for SYN flags (indicative of potential port scans)
- Updates the scan count for the source IP
- Triggers blocking if the threshold is exceeded
fn block_ip(ip: &IpAddr) {
// Implementation details in the full code
}
fn unblock_ip(ip: &IpAddr) {
// Implementation details in the full code
}
fn main() {
// Setup code
thread::spawn(move || {
while let Ok(packet) = cap.next() {
// Process packets
}
});
loop {
unblock_expired_ips(&unblock_tasks);
thread::sleep(Duration::from_secs(5));
}
}
- Packet Analysis: Understanding TCP flags (like SYN) is crucial for detecting network scans
- Concurrency in Rust: We use Arc and Mutex for safe concurrent access to shared data
- System Integration: The project demonstrates how to interface with system tools like iptables from Rust
- Real-time Processing: The firewall processes packets in real-time, showcasing efficient data handling
To ensure the effectiveness of our intelligent firewall, we conduct comprehensive testing:
# Basic Port Scan
nmap -p 1-1000 <target-ip>
# Rapid Scan
nmap -p 1-1000 -T4 <target-ip>
# Stealth Scan
sudo nmap -sS -p 1-1000 <target-ip>
# Service Detection
nmap -sV -p 1-1000 <target-ip>
For more realistic testing scenarios, you can set up a cross-device testing environment:
- Desktop (Linux) running the Rust firewall
- Secondary device (e.g., MacBook) for testing
- Both devices on the same network
-
Desktop Setup (Firewall Host)
# Build the project cargo build --release # Find your IP address ip addr show # or 'ifconfig' # Run the firewall sudo ./target/release/intelligent_firewall
-
Testing Device Setup
# Install nmap (MacOS example) brew install nmap
-
Test Scenarios
# Basic Port Scan nmap -p 1-1000 <desktop-ip> # Rapid Scan (triggers blocking faster) nmap -p 1-1000 -T4 <desktop-ip> # Stealth Scan sudo nmap -sS -p 1-1000 <desktop-ip> # Service/Version Detection nmap -sV -p 1-1000 <desktop-ip> # TCP Connect Scan nmap -sT -p 1-1000 <desktop-ip> # UDP Scan sudo nmap -sU -p 1-1000 <desktop-ip>
-
Verification Steps
# Check blocked IPs (on Desktop) sudo iptables -L INPUT -n -v
- Watch the firewall's console output for scan detection
- Monitor blocking and unblocking behavior
- Verify if scans fail after IP blocking
- Confirm automatic unblocking after the timeout period
- Ensure both devices are on the same network subnet
- Check firewall settings on both machines
- Verify the correct network interface is being monitored
- Confirm proper permissions for running scans and the firewall
While building security tools is educational, it's crucial to use them ethically:
- Only test on networks you own or have explicit permission to test
- Be aware of legal implications of network scanning and monitoring
- Use this knowledge to improve security, not to exploit vulnerabilities
This project demonstrates the power of Rust in building network security tools. By combining low-level network programming with high-level abstractions, we've created a firewall capable of detecting and blocking potential port scan attempts in real-time.
The skills developed in this project are valuable in various fields:
- Network Security
- Systems Programming
- Real-time Data Processing
- DevOps and Infrastructure Management
As cyber threats evolve, tools like this port scan detector represent a step towards better security systems.
#Rust #NetworkSecurity #CyberSecurity #Programming #OpenSource