vanguards_rs/
lib.rs

1//! # vanguards-rs
2//!
3//! A Rust implementation of the Python vanguards library for enhanced Tor hidden service security.
4//!
5//! # Overview
6//!
7//! vanguards-rs provides protection against guard discovery attacks through persistent
8//! vanguard relay selection, and additional protections through multiple security components:
9//!
10//! - **Vanguard Selection** ([`vanguards`]): Persistent layer2/layer3 guard selection
11//! - **Bandwidth Monitoring** ([`bandguards`]): Detect bandwidth-based side-channel attacks
12//! - **Rendezvous Point Analysis** ([`rendguard`]): Detect statistical attacks on rendezvous points
13//! - **Log Monitoring** ([`logguard`]): Monitor Tor logs for security-relevant events
14//! - **Circuit Build Timeout Verification** ([`cbtverify`]): Verify circuit construction timing
15//! - **Path Verification** ([`pathverify`]): Verify circuit paths conform to vanguard configuration
16//!
17//! ## Module Overview
18//!
19//! | Module | Purpose |
20//! |--------|---------|
21//! | [`api`] | High-level [`Vanguards`] struct for programmatic use |
22//! | [`config`] | Configuration management (TOML, CLI, environment) |
23//! | [`error`] | Error types and [`Result`] alias |
24//! | [`control`] | Main event loop and Tor connection management |
25//! | [`vanguards`] | Vanguard state and guard selection |
26//! | [`bandguards`] | Bandwidth monitoring and attack detection |
27//! | [`rendguard`] | Rendezvous point usage tracking |
28//! | [`logguard`] | Tor log monitoring and buffering |
29//! | [`cbtverify`] | Circuit build timeout verification |
30//! | [`pathverify`] | Circuit path verification |
31//! | [`node_selection`] | Bandwidth-weighted relay selection |
32//! | [`logger`] | Logging infrastructure using tracing |
33//!
34//! # What This Library Does NOT Do
35//!
36//! - **Direct relay communication**: Use [`stem_rs::client`] for ORPort connections
37//! - **Descriptor parsing**: Use [`stem_rs::descriptor`] module
38//! - **Exit policy evaluation**: Use [`stem_rs::exit_policy`]
39//! - **Running a Tor relay**: This library protects hidden services, not relays
40//! - **Onion service creation**: Use Tor's `ADD_ONION` command via stem-rs
41//!
42//! # Quick Start
43//!
44//! ## As a Library
45//!
46//! ```rust,no_run
47//! use vanguards_rs::{Config, Vanguards};
48//!
49//! #[tokio::main]
50//! async fn main() -> vanguards_rs::Result<()> {
51//!     // Load configuration
52//!     let config = Config::default();
53//!     
54//!     // Create and run vanguards protection
55//!     let mut vanguards = Vanguards::from_config(config).await?;
56//!     vanguards.run().await
57//! }
58//! ```
59//!
60//! ## As a CLI Application
61//!
62//! ```bash
63//! # Run with default settings
64//! vanguards-rs
65//!
66//! # Connect to specific control port
67//! vanguards-rs --control-ip 127.0.0.1 --control-port 9051
68//!
69//! # Use Unix socket with custom state file
70//! vanguards-rs --control-socket /run/tor/control --state /var/lib/tor/vanguards.state
71//!
72//! # Generate default configuration file
73//! vanguards-rs --generate_config vanguards.conf
74//! ```
75//!
76//! # Configuration
77//!
78//! Configuration can be loaded from multiple sources in order of precedence:
79//!
80//! ```text
81//! ┌─────────────────┐
82//! │   CLI Arguments │ ◄── Highest priority (overrides all)
83//! └────────┬────────┘
84//!          │
85//! ┌────────▼────────┐
86//! │   Environment   │ ◄── VANGUARDS_STATE, VANGUARDS_CONFIG
87//! │    Variables    │
88//! └────────┬────────┘
89//!          │
90//! ┌────────▼────────┐
91//! │   Config File   │ ◄── TOML file (default: vanguards.conf)
92//! │     (TOML)      │
93//! └────────┬────────┘
94//!          │
95//! ┌────────▼────────┐
96//! │    Defaults     │ ◄── Sensible defaults for all options
97//! └─────────────────┘
98//! ```
99//!
100//! See [`Config`] for all available options.
101//!
102//! # State File Compatibility
103//!
104//! State files are compatible with Python vanguards for seamless migration.
105//! The library reads and writes Python pickle format state files, allowing
106//! you to switch between Python vanguards and vanguards-rs without losing
107//! your guard selections.
108//!
109//! # Security Considerations
110//!
111//! - **Memory Safety**: Passwords are cleared from memory after use (using zeroize)
112//! - **File Permissions**: State files are written with restrictive permissions (0600)
113//! - **Input Validation**: All external inputs are validated before use
114//! - **Error Handling**: Error messages do not leak sensitive information
115//! - **Guard Persistence**: Vanguard selections persist across restarts to prevent
116//!   guard discovery through restart attacks
117//!
118//! # See Also
119//!
120//! - [Python vanguards](https://github.com/mikeperry-tor/vanguards) - Original Python implementation
121//! - [stem-rs documentation](https://stem.tn3w.dev/docs/) - Tor control library used by vanguards-rs
122//! - [Tor Control Protocol Specification](https://spec.torproject.org/control-spec) - Protocol reference
123//! - [Vanguards Specification](https://github.com/torproject/torspec/blob/main/proposals/292-mesh-vanguards.txt) - Tor proposal 292
124//! - [Guard Discovery Attacks](https://www.freehaven.net/anonbib/cache/wpes12-cogs.pdf) - Academic paper on the attacks vanguards mitigates
125
126#![warn(missing_docs)]
127#![warn(rustdoc::broken_intra_doc_links)]
128
129pub mod api;
130pub mod bandguards;
131pub mod cbtverify;
132pub mod config;
133pub mod control;
134pub mod error;
135pub mod logger;
136pub mod logguard;
137pub mod node_selection;
138pub mod pathverify;
139pub mod rendguard;
140pub mod vanguards;
141
142pub use api::{SecurePassword, Vanguards};
143pub use bandguards::{
144    BandwidthStats, BwCircuitStat, BwGuardStat, CircuitLimitResult, ConnectivityStatus,
145    CELL_PAYLOAD_SIZE, MAX_CIRC_DESTROY_LAG_SECS, RELAY_HEADER_SIZE, RELAY_PAYLOAD_SIZE,
146};
147pub use cbtverify::{CircuitStat, TimeoutStats};
148pub use config::{
149    BandguardsConfig, CliArgs, Config, LogLevel, LogguardConfig, RendguardConfig, VanguardsConfig,
150};
151pub use error::{Error, Result};
152pub use logguard::{LogEntry, LogGuard};
153pub use node_selection::{
154    is_valid_country_code, is_valid_fingerprint, is_valid_ip_or_network, BwWeightedGenerator,
155    FlagsRestriction, NodeRestriction, NodeRestrictionList, Position,
156};
157pub use pathverify::{
158    Layer1Guards, Layer1Stats, PathVerify, ROUTELEN_FOR_PURPOSE, ROUTELEN_FOR_PURPOSE_LITE,
159};
160pub use rendguard::{RendCheckResult, NOT_IN_CONSENSUS_ID};
161pub use vanguards::{ExcludeNodes, GuardNode, RendGuard, RendUseCount, VanguardState};
162
163pub use control::{
164    authenticate_any, configure_tor, control_loop, get_close_circuits, get_consensus_weights,
165    new_consensus_event, run_main, set_close_circuits, signal_event, try_close_circuit, AppState,
166    VERSION,
167};