Skip to content

root3315/safe-packet-analyzer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Safe Packet Analyzer

A memory-safe network packet analyzer written in Rust for secure packet inspection.

Overview

Safe Packet Analyzer is a high-performance, memory-safe tool for parsing and analyzing network packets. Built with Rust's ownership model, it provides strong guarantees against common memory-related vulnerabilities such as buffer overflows, use-after-free, and data races.

Features

  • Memory Safety: Leverages Rust's ownership and borrowing system to prevent memory-related bugs
  • Protocol Support: Parses Ethernet II, IPv4, TCP, UDP, and ICMP protocols
  • Connection Tracking: Maintains state information for TCP connections
  • Suspicious Pattern Detection: Identifies potential security threats including:
    • SYN flood attacks
    • Unusual TCP flag combinations
    • Connections to suspicious ports
    • Unusually large payloads
  • Comprehensive Error Handling: Detailed error types for debugging and logging
  • Multiple Output Formats: Text and JSON output options
  • Extensible Architecture: Modular design for easy extension

Installation

Prerequisites

  • Rust 1.70 or later (install via rustup)

Build from Source

git clone https://github.com/example/safe-packet-analyzer.git
cd safe-packet-analyzer
cargo build --release

The binary will be available at target/release/safe-packet-analyzer.

Install via Cargo

cargo install safe-packet-analyzer

Usage

Command Line Interface

# Display help
safe-packet-analyzer --help

# Run built-in demonstration
safe-packet-analyzer demo

# Display library information
safe-packet-analyzer info

# Analyze packets from a file
safe-packet-analyzer analyze packets.bin

# Analyze with JSON output
safe-packet-analyzer analyze packets.bin --format json

# Parse a single packet from hex
safe-packet-analyzer parse "ff:ff:ff:ff:ff:ff:00:11:22:33:44:55:08:00"

# Configure analysis options
safe-packet-analyzer analyze packets.bin --max-packets 1000 --verbose

Command Options

Option Description Default
-v, --verbose Enable verbose output false
-m, --max-packets <N> Maximum packets to analyze 10000
--no-pattern-detection Disable suspicious pattern detection false
--no-connection-tracking Disable connection tracking false

Subcommands

Command Description
analyze <file> Analyze packets from a binary file
parse <hex> Parse and display a single packet from hex
demo Run built-in demonstration
info Display library information

File Format

The analyzer expects packet files in a simple binary format:

  • Each packet is prefixed with a 2-byte big-endian length field
  • Packet data follows immediately after the length field

Example file structure:

[2-byte length][packet data][2-byte length][packet data]...

Library Usage

Add to your Cargo.toml:

[dependencies]
safe-packet-analyzer = "0.1"

Example

use safe_packet_analyzer::packet::Packet;
use safe_packet_analyzer::analyzer::{PacketAnalyzer, AnalyzerConfig};

// Parse a packet
let data = vec![
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55,
    0x08, 0x00,
];
let packet = Packet::from_bytes(&data)?;
println!("Parsed: {}", packet);

// Analyze packets
let config = AnalyzerConfig::default();
let mut analyzer = PacketAnalyzer::new(config);
let result = analyzer.analyze_packets(&[packet])?;

println!("Total packets: {}", result.stats.total_packets);
println!("Suspicious patterns: {}", result.stats.suspicious_patterns_found);

How It Works

Packet Parsing

The analyzer processes packets in layers, following the OSI model:

  1. Ethernet Layer: Extracts MAC addresses and EtherType
  2. Network Layer: Parses IPv4 headers, validates checksums
  3. Transport Layer: Parses TCP/UDP headers based on protocol field
  4. Application Layer: Payload data available for inspection

Memory Safety Guarantees

  • Bounds Checking: All array/slice accesses are bounds-checked
  • No Raw Pointers: Uses safe Rust references throughout
  • Ownership Model: Prevents use-after-free and double-free
  • Immutable by Default: Data is immutable unless explicitly mutable
  • Type Safety: Strong typing prevents protocol confusion attacks

Connection Tracking

TCP connections are tracked using a 5-tuple key:

  • Source IP address
  • Source port
  • Destination IP address
  • Destination port
  • Protocol

Connection states follow TCP state machine transitions:

  • NEW → SYN_SENT → SYN_RECEIVED → ESTABLISHED → FIN_WAIT → CLOSED

Suspicious Pattern Detection

The analyzer identifies potential threats:

Pattern Detection Method Severity
SYN Flood >100 SYN packets from same source High
Unusual Flags SYN+FIN, SYN+RST combinations Medium
Suspicious Ports Connections to ports 4444, 5555, 6666, 31337 Medium
Large Payload Payload >65000 bytes Low

Architecture

safe-packet-analyzer/
├── src/
│   ├── main.rs          # CLI entry point
│   ├── lib.rs           # Library root
│   ├── error.rs         # Error types
│   ├── packet.rs        # Packet parsing
│   └── analyzer.rs      # Analysis logic
├── tests/
│   └── integration_test.rs
├── Cargo.toml
└── README.md

Testing

Run all tests:

cargo test

Run with verbose output:

cargo test -- --nocapture

Run specific test:

cargo test test_full_tcp_packet_parsing

Performance

The analyzer is optimized for:

  • Zero-copy parsing: Where possible, borrows from input data
  • Minimal allocations: Reuses buffers when analyzing multiple packets
  • Efficient data structures: HashMaps and HashSet for O(1) lookups

Security Considerations

  • Input validation prevents malformed packet crashes
  • Maximum packet size limits prevent memory exhaustion
  • Pattern detection helps identify potential attacks
  • No external network access (offline analysis only)

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: cargo test
  5. Run clippy: cargo clippy
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

Acknowledgments

About

memory safe network packet analyzer written in rust for secure packet inspection

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages