Skip to content

Commit

Permalink
[README] (#27)
Browse files Browse the repository at this point in the history
* upgrade README

* fix fmt

* document code

* example in readme
  • Loading branch information
biandratti authored Dec 1, 2024
1 parent 8458b48 commit ea8d43c
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 21 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
[package]
name = "passivetcp-rs"
version = "0.1.0-alpha.0"
edition = "2021"
description = "A Rust library for passive traffic fingerprinting [p0f]"
license = "MIT OR Apache-2.0"
description = "Passive traffic fingerprinting [p0f]"
license = "MIT"
authors = ["Maximiliano Biandratti <biandratti@example.com>"]
repository = "https://github.com/biandratti/passivetcp-rs"
readme = "README.md"
Expand All @@ -18,10 +19,6 @@ log = "0.4.22"
lazy_static = "1.5.0"
ttl_cache = "0.5.1"

[lib]
name = "passivetcp"
path = "src/lib.rs"

[[example]]
name = "p0f"
path = "examples/p0f.rs"
81 changes: 69 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
### Get network Interface
```
ip link show
```
# Passive traffic fingerprinting
An experimental Rust library inspired by p0f, the well-known passive OS fingerprinting tool originally written in C. This library aims to bring the power of passive TCP/IP fingerprinting to the Rust ecosystem while offering a more modern, efficient, and extensible implementation.

### Process packages
```
cargo build --release --examples
sudo RUST_BACKTRACE=1 ./target/release/examples/p0f --interface <INTERFACE>
```
#### What is Passive TCP Fingerprinting?
Passive TCP fingerprinting is a technique that allows you to infer information about a remote host's operating system and network stack without sending any probes. By analyzing characteristics of the TCP/IP packets that are exchanged during a normal network conversation, passivetcp-rs provides insights into the remote system’s OS type, version, and network stack implementation.

#### This technique is useful for a variety of purposes, including:
- Network analysis: Identifying the types of devices and systems on a network without active scanning.
- Security: Discovering hidden or obscure systems by their network behavior.
- Fingerprinting for research: Understanding patterns in network traffic and improving security posture.
About passivetcp-rs

### A snippet of typical p0f output may look like this:
This Rust implementation of passive TCP fingerprinting is still in its experimental phase, and while it builds upon the established ideas of p0f, it is not yet feature-complete. The library currently provides basic functionality, but we plan to expand its capabilities as the project matures.

```
#### A snippet of typical p0f output may look like this:

```text
.-[ 1.2.3.4/1524 -> 4.3.2.1/80 (syn) ]-
|
| client = 1.2.3.4
Expand Down Expand Up @@ -48,4 +50,59 @@ sudo RUST_BACKTRACE=1 ./target/release/examples/p0f --interface <INTERFACE>
| raw_freq = 250.00 Hz
|
`----
```
```

### Installation
To use passivetcp-rs in your Rust project, add the following dependency to your `Cargo.toml`:
```toml
[dependencies]
passivetcp-rs = "0.1.0-alpha.0"
```

### Usage
Here’s a basic example of how to use passivetcp-rs:
```rust
use passivetcp_rs::db::Database;
use passivetcp_rs::P0f;

let args = Args::parse();
let interface_name = args.interface;
let db = Database::default();
let mut p0f = P0f::new(&db, 100);

let interfaces: Vec<NetworkInterface> = datalink::interfaces();
let interface = interfaces
.into_iter()
.find(|iface| iface.name == interface_name)
.expect("Could not find the interface");

let config = Config {
promiscuous: true,
..Config::default()
};

let (_tx, mut rx) = match datalink::channel(&interface, config) {
Ok(datalink::Channel::Ethernet(tx, rx)) => (tx, rx),
Ok(_) => panic!("Unhandled channel type"),
Err(e) => panic!("Unable to create channel: {}", e),
};

loop {
match rx.next() {
Ok(packet) => {
let p0f_output = p0f.analyze_tcp(packet);
p0f_output.syn.map(|syn| println!("{}", syn));
p0f_output.syn_ack.map(|syn_ack| println!("{}", syn_ack));
p0f_output.mtu.map(|mtu| println!("{}", mtu));
p0f_output.uptime.map(|uptime| println!("{}", uptime));
}
Err(e) => eprintln!("Failed to read packet: {}", e),
}
}
```

### Contributing
This library is in its early stages, and contributions are very welcome. If you have ideas for additional features, bug fixes, or optimizations, please feel free to open issues or submit pull requests. We are particularly looking for help with extending the feature set and improving the performance of the library.

### License
This project is licensed under the MIT License.
10 changes: 10 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Get network Interface
```
ip link show
```

### Process packages
```
cargo build --release --examples
sudo RUST_BACKTRACE=1 ./target/release/examples/p0f --interface <INTERFACE>
```
3 changes: 2 additions & 1 deletion examples/p0f.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use clap::Parser;
use log::debug;
use passivetcp::{db::Database, P0f};
use passivetcp_rs::db::Database;
use passivetcp_rs::P0f;
use pnet::datalink::{self, Config, NetworkInterface};

#[derive(Parser, Debug)]
Expand Down
12 changes: 11 additions & 1 deletion src/db.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::{http, tcp};
use std::fmt;

#[allow(dead_code)] //TODO: WIP
/// Represents the database used by `P0f` to store signatures and associated metadata.
/// The database contains signatures for analyzing TCP and HTTP traffic, as well as
/// other metadata such as MTU mappings and user agent-to-operating system mappings.
#[derive(Debug)]
pub struct Database {
pub classes: Vec<String>,
Expand All @@ -13,6 +15,8 @@ pub struct Database {
pub http_response: Vec<(Label, Vec<http::Signature>)>,
}

/// Represents a label associated with a signature, which provides metadata about
/// the signature, such as type, class, name, and optional flavor details.
#[derive(Clone, Debug, PartialEq)]
pub struct Label {
pub ty: Type,
Expand All @@ -21,13 +25,19 @@ pub struct Label {
pub flavor: Option<String>,
}

/// Enum representing the type of `Label`.
/// - `Specified`: A specific label with well-defined characteristics.
/// - `Generic`: A generic label with broader characteristics.
#[derive(Clone, Debug, PartialEq)]
pub enum Type {
Specified,
Generic,
}

impl fmt::Display for Type {
/// Creates a default instance of the `Database` by parsing a configuration file
/// located at `config/p0f.fp`. This file is expected to define the default
/// signatures and mappings used for analysis.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
Expand Down
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,34 @@ pub struct P0f<'a> {
cache: TtlCache<Connection, SynData>,
}

/// A passive TCP fingerprinting engine inspired by `p0f`.
///
/// The `P0f` struct acts as the core component of the library, handling TCP packet
/// analysis and matching signatures using a database of known fingerprints.
impl<'a> P0f<'a> {
/// Creates a new instance of `P0f`.
///
/// # Parameters
/// - `database`: A reference to the database containing known TCP/IP signatures.
/// - `cache_capacity`: The maximum number of connections to maintain in the TTL cache.
///
/// # Returns
/// A new `P0f` instance initialized with the given database and cache capacity.
pub fn new(database: &'a Database, cache_capacity: usize) -> Self {
let matcher: SignatureMatcher = SignatureMatcher::new(database);
let cache: TtlCache<Connection, SynData> = TtlCache::new(cache_capacity);
Self { matcher, cache }
}

/// Analyzes a TCP packet and returns the corresponding `P0fOutput`.
///
/// # Parameters
/// - `packet`: A byte slice representing the raw TCP packet to analyze.
///
/// # Returns
/// A `P0fOutput` containing the analysis results, including matched signatures,
/// observed MTU, uptime information, and other details. If no valid data is observed, an empty output is returned.
pub fn analyze_tcp(&mut self, packet: &[u8]) -> P0fOutput {
if let Ok(observable_signature) = ObservableSignature::extract(packet, &mut self.cache) {
if observable_signature.from_client {
Expand Down

0 comments on commit ea8d43c

Please sign in to comment.