Skip to main content

hightower_wireguard/
protocol.rs

1use crate::crypto::{PrivateKey, PublicKey25519, dh_generate};
2use crate::initiator::{InitiatorState, SessionKeys};
3use crate::messages::{HandshakeInitiation, HandshakeResponse};
4use crate::replay::ReplayWindow;
5use crate::responder::ResponderState;
6use crate::{Result, WireGuardError};
7use std::collections::HashMap;
8use std::net::SocketAddr;
9use std::time::Duration;
10
11/// Time after which to initiate a new handshake (RFC: REKEY-AFTER-TIME)
12pub const REKEY_AFTER_TIME: Duration = Duration::from_secs(120);
13
14/// Time after which to reject packets and require new handshake (RFC: REJECT-AFTER-TIME)
15pub const REJECT_AFTER_TIME: Duration = Duration::from_secs(180);
16
17/// Time to wait before sending keep-alive if no data has been sent
18pub const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(10);
19
20/// Configuration and metadata for a WireGuard peer
21#[derive(Debug, Clone)]
22pub struct PeerInfo {
23    /// Peer's public key for authentication and key derivation
24    pub public_key: PublicKey25519,
25    /// Optional preshared key for additional security
26    pub preshared_key: Option<[u8; 32]>,
27    /// Network endpoint (IP address and port) for the peer
28    pub endpoint: Option<SocketAddr>,
29    /// IP ranges allowed for this peer (IP address and prefix length)
30    pub allowed_ips: Vec<(std::net::IpAddr, u8)>, // IP and prefix length
31    /// Interval in seconds for keepalive packets
32    pub persistent_keepalive: Option<u16>,
33}
34
35/// Active cryptographic session with established transport keys
36#[derive(Debug, Clone)]
37pub struct ActiveSession {
38    /// Transport keys for encrypting/decrypting data
39    pub keys: SessionKeys,
40    /// Public key of the peer this session is with
41    pub peer_public_key: PublicKey25519,
42    /// Timestamp when this session was created (handshake completed)
43    pub created_at: std::time::Instant,
44    /// Timestamp of last activity on this session
45    pub last_used: std::time::Instant,
46    /// Timestamp of last data sent on this session
47    pub last_send: std::time::Instant,
48    /// Current endpoint address for this peer (updated on packet receipt)
49    pub endpoint: Option<SocketAddr>,
50    /// Replay protection window for received packets
51    pub replay_window: ReplayWindow,
52}
53
54/// Main WireGuard protocol handler managing peers and sessions
55pub struct WireGuardProtocol {
56    local_private_key: PrivateKey,
57    local_public_key: PublicKey25519,
58    peers: HashMap<PublicKey25519, PeerInfo>,
59    active_sessions: HashMap<u32, ActiveSession>, // sender_id -> session
60    pending_initiations: HashMap<u32, InitiatorState>, // sender_id -> state
61    pending_responses: HashMap<u32, ResponderState>, // sender_id -> state
62}
63
64impl WireGuardProtocol {
65    /// Create new WireGuard protocol instance
66    pub fn new(private_key: Option<PrivateKey>) -> Self {
67        let (private_key, public_key) = if let Some(key) = private_key {
68            let public_key = {
69                use x25519_dalek::{PublicKey, StaticSecret};
70                let secret = StaticSecret::from(key);
71                PublicKey::from(&secret).to_bytes()
72            };
73            (key, public_key)
74        } else {
75            dh_generate()
76        };
77
78        Self {
79            local_private_key: private_key,
80            local_public_key: public_key,
81            peers: HashMap::new(),
82            active_sessions: HashMap::new(),
83            pending_initiations: HashMap::new(),
84            pending_responses: HashMap::new(),
85        }
86    }
87
88    /// Get our public key
89    pub fn public_key(&self) -> PublicKey25519 {
90        self.local_public_key
91    }
92
93    /// Add a peer to the protocol
94    pub fn add_peer(&mut self, peer_info: PeerInfo) {
95        self.peers.insert(peer_info.public_key, peer_info);
96    }
97
98    /// Remove a peer
99    pub fn remove_peer(&mut self, public_key: &PublicKey25519) {
100        self.peers.remove(public_key);
101
102        // Clean up any sessions for this peer
103        self.active_sessions
104            .retain(|_, session| session.peer_public_key != *public_key);
105    }
106
107    /// Get peer info
108    pub fn get_peer(&self, public_key: &PublicKey25519) -> Option<&PeerInfo> {
109        self.peers.get(public_key)
110    }
111
112    /// Initiate handshake with a peer
113    pub fn initiate_handshake(
114        &mut self,
115        peer_public_key: &PublicKey25519,
116    ) -> Result<HandshakeInitiation> {
117        let peer_info = self
118            .peers
119            .get(peer_public_key)
120            .ok_or_else(|| WireGuardError::ProtocolError("Unknown peer".to_string()))?;
121
122        let mut initiator = InitiatorState::new(
123            self.local_private_key,
124            *peer_public_key,
125            peer_info.preshared_key,
126        );
127
128        let initiation = initiator.create_initiation()?;
129        let sender_id = initiation.sender;
130
131        // Store the initiator state for when we receive the response
132        self.pending_initiations.insert(sender_id, initiator);
133
134        Ok(initiation)
135    }
136
137    /// Process received handshake initiation
138    pub fn process_initiation(&mut self, msg: &HandshakeInitiation) -> Result<HandshakeResponse> {
139        // Create responder state
140        let mut responder = ResponderState::new(self.local_private_key, None);
141
142        // Process the initiation to discover the peer
143        let peer_public_key = responder.process_initiation(msg)?;
144
145        // Look up peer info to get PSK if available
146        let peer_info = self
147            .peers
148            .get(&peer_public_key)
149            .ok_or_else(|| WireGuardError::ProtocolError("Unknown peer".to_string()))?;
150
151        // Create new responder with correct PSK
152        let mut responder = ResponderState::new(self.local_private_key, peer_info.preshared_key);
153        let _peer_key = responder.process_initiation(msg)?; // Process again with PSK
154
155        // Create response
156        let response = responder.create_response(msg.sender)?;
157        let sender_id = response.sender;
158
159        // Derive keys and create active session
160        let keys = responder.derive_keys()?;
161        let now = std::time::Instant::now();
162        let session = ActiveSession {
163            keys,
164            peer_public_key,
165            created_at: now,
166            last_used: now,
167            last_send: now,
168            endpoint: None,
169            replay_window: ReplayWindow::new(),
170        };
171
172        // Store the active session
173        self.active_sessions.insert(sender_id, session);
174
175        #[cfg(feature = "transport")]
176        {
177            use tracing::info;
178            let peer_key_hex = hex::encode(peer_public_key);
179            info!(
180                session_id = sender_id,
181                peer_public_key = &peer_key_hex[..8],
182                "SESSION: New session created (responder)"
183            );
184        }
185
186        Ok(response)
187    }
188
189    /// Process received handshake response
190    pub fn process_response(&mut self, msg: &HandshakeResponse) -> Result<PublicKey25519> {
191        // Find the corresponding initiator state
192        let mut initiator = self
193            .pending_initiations
194            .remove(&msg.receiver)
195            .ok_or_else(|| {
196                WireGuardError::ProtocolError("No pending initiation found".to_string())
197            })?;
198
199        // Get the peer's public key from the initiator state
200        let peer_public_key = initiator.remote_static_public();
201
202        // Process the response to get session keys
203        let keys = initiator.process_response(msg)?;
204
205        // Create active session
206        let now = std::time::Instant::now();
207        let session = ActiveSession {
208            keys,
209            peer_public_key,
210            created_at: now,
211            last_used: now,
212            last_send: now,
213            endpoint: None,
214            replay_window: ReplayWindow::new(),
215        };
216
217        // Store the active session using the sender ID from the response
218        self.active_sessions.insert(msg.sender, session);
219
220        #[cfg(feature = "transport")]
221        {
222            use tracing::info;
223            let peer_key_hex = hex::encode(peer_public_key);
224            info!(
225                session_id = msg.sender,
226                peer_public_key = &peer_key_hex[..8],
227                "SESSION: New session created (initiator)"
228            );
229        }
230
231        Ok(peer_public_key)
232    }
233
234    /// Get active session by sender ID
235    pub fn get_session(&self, sender_id: u32) -> Option<&ActiveSession> {
236        self.active_sessions.get(&sender_id)
237    }
238
239    /// Get mutable active session by sender ID
240    pub fn get_session_mut(&mut self, sender_id: u32) -> Option<&mut ActiveSession> {
241        self.active_sessions.get_mut(&sender_id)
242    }
243
244    /// Check and update replay window for a received packet
245    ///
246    /// Returns Ok(()) if the counter is valid and not a replay, Err otherwise
247    pub fn check_replay(&mut self, sender_id: u32, counter: u64) -> Result<()> {
248        let session = self
249            .get_session_mut(sender_id)
250            .ok_or_else(|| WireGuardError::ProtocolError("No active session".to_string()))?;
251
252        if session.replay_window.check_and_update(counter) {
253            session.last_used = std::time::Instant::now();
254            Ok(())
255        } else {
256            Err(WireGuardError::ProtocolError("Replay detected".to_string()))
257        }
258    }
259
260    /// Get a reference to all active sessions
261    ///
262    /// Returns a map of session IDs to active sessions
263    pub fn active_sessions(&self) -> &HashMap<u32, ActiveSession> {
264        &self.active_sessions
265    }
266
267    /// Get a reference to all configured peers
268    ///
269    /// Returns a map of public keys to peer information
270    pub fn peers(&self) -> &HashMap<PublicKey25519, PeerInfo> {
271        &self.peers
272    }
273
274    /// Remove expired sessions and stale pending handshakes
275    ///
276    /// Should be called periodically to prevent resource leaks
277    pub fn cleanup(&mut self) {
278        let now = std::time::Instant::now();
279        let session_timeout = std::time::Duration::from_secs(180); // 3 minutes
280        let _handshake_timeout = std::time::Duration::from_secs(30); // 30 seconds
281
282        // Remove expired sessions
283        self.active_sessions
284            .retain(|_, session| now.duration_since(session.last_used) < session_timeout);
285
286        // Remove expired pending handshakes
287        // Note: This is a simple cleanup - in reality we'd track creation time
288        if self.pending_initiations.len() > 100 {
289            self.pending_initiations.clear();
290        }
291        if self.pending_responses.len() > 100 {
292            self.pending_responses.clear();
293        }
294    }
295
296    /// Update endpoint address for a session when receiving a packet
297    ///
298    /// Supports endpoint roaming (mobile devices changing networks)
299    pub fn update_endpoint(&mut self, sender_id: u32, new_endpoint: SocketAddr) {
300        if let Some(session) = self.active_sessions.get_mut(&sender_id) {
301            let old_endpoint = session.endpoint;
302            if old_endpoint != Some(new_endpoint) {
303                #[cfg(feature = "transport")]
304                {
305                    use tracing::info;
306                    let peer_key_hex = hex::encode(session.peer_public_key);
307                    info!(
308                        session_id = sender_id,
309                        peer_public_key = &peer_key_hex[..8],
310                        old_endpoint = ?old_endpoint,
311                        new_endpoint = %new_endpoint,
312                        "ROAMING: Endpoint updated for session"
313                    );
314                }
315            }
316            session.endpoint = Some(new_endpoint);
317        }
318    }
319
320    /// Update last send time for a session
321    pub fn update_last_send(&mut self, sender_id: u32) {
322        if let Some(session) = self.active_sessions.get_mut(&sender_id) {
323            session.last_send = std::time::Instant::now();
324        }
325    }
326
327    /// Check if a session needs rekeying based on age
328    ///
329    /// Returns true if the session is older than REKEY_AFTER_TIME
330    pub fn needs_rekey(&self, sender_id: u32) -> bool {
331        if let Some(session) = self.active_sessions.get(&sender_id) {
332            let age = std::time::Instant::now().duration_since(session.created_at);
333            age >= REKEY_AFTER_TIME
334        } else {
335            false
336        }
337    }
338
339    /// Check if a session should be rejected (too old)
340    ///
341    /// Returns true if the session is older than REJECT_AFTER_TIME
342    pub fn should_reject(&self, sender_id: u32) -> bool {
343        if let Some(session) = self.active_sessions.get(&sender_id) {
344            let age = std::time::Instant::now().duration_since(session.created_at);
345            age >= REJECT_AFTER_TIME
346        } else {
347            true
348        }
349    }
350
351    /// Find session by peer public key
352    pub fn find_session_by_peer(&self, peer_public_key: &PublicKey25519) -> Option<(u32, &ActiveSession)> {
353        self.active_sessions
354            .iter()
355            .find(|(_, session)| session.peer_public_key == *peer_public_key)
356            .map(|(id, session)| (*id, session))
357    }
358
359    /// Find mutable session by peer public key
360    pub fn find_session_by_peer_mut(&mut self, peer_public_key: &PublicKey25519) -> Option<(u32, &mut ActiveSession)> {
361        self.active_sessions
362            .iter_mut()
363            .find(|(_, session)| session.peer_public_key == *peer_public_key)
364            .map(|(id, session)| (*id, session))
365    }
366}