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
11pub const REKEY_AFTER_TIME: Duration = Duration::from_secs(120);
13
14pub const REJECT_AFTER_TIME: Duration = Duration::from_secs(180);
16
17pub const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(10);
19
20#[derive(Debug, Clone)]
22pub struct PeerInfo {
23 pub public_key: PublicKey25519,
25 pub preshared_key: Option<[u8; 32]>,
27 pub endpoint: Option<SocketAddr>,
29 pub allowed_ips: Vec<(std::net::IpAddr, u8)>, pub persistent_keepalive: Option<u16>,
33}
34
35#[derive(Debug, Clone)]
37pub struct ActiveSession {
38 pub keys: SessionKeys,
40 pub peer_public_key: PublicKey25519,
42 pub created_at: std::time::Instant,
44 pub last_used: std::time::Instant,
46 pub last_send: std::time::Instant,
48 pub endpoint: Option<SocketAddr>,
50 pub replay_window: ReplayWindow,
52}
53
54pub struct WireGuardProtocol {
56 local_private_key: PrivateKey,
57 local_public_key: PublicKey25519,
58 peers: HashMap<PublicKey25519, PeerInfo>,
59 active_sessions: HashMap<u32, ActiveSession>, pending_initiations: HashMap<u32, InitiatorState>, pending_responses: HashMap<u32, ResponderState>, }
63
64impl WireGuardProtocol {
65 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 pub fn public_key(&self) -> PublicKey25519 {
90 self.local_public_key
91 }
92
93 pub fn add_peer(&mut self, peer_info: PeerInfo) {
95 self.peers.insert(peer_info.public_key, peer_info);
96 }
97
98 pub fn remove_peer(&mut self, public_key: &PublicKey25519) {
100 self.peers.remove(public_key);
101
102 self.active_sessions
104 .retain(|_, session| session.peer_public_key != *public_key);
105 }
106
107 pub fn get_peer(&self, public_key: &PublicKey25519) -> Option<&PeerInfo> {
109 self.peers.get(public_key)
110 }
111
112 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 self.pending_initiations.insert(sender_id, initiator);
133
134 Ok(initiation)
135 }
136
137 pub fn process_initiation(&mut self, msg: &HandshakeInitiation) -> Result<HandshakeResponse> {
139 let mut responder = ResponderState::new(self.local_private_key, None);
141
142 let peer_public_key = responder.process_initiation(msg)?;
144
145 let peer_info = self
147 .peers
148 .get(&peer_public_key)
149 .ok_or_else(|| WireGuardError::ProtocolError("Unknown peer".to_string()))?;
150
151 let mut responder = ResponderState::new(self.local_private_key, peer_info.preshared_key);
153 let _peer_key = responder.process_initiation(msg)?; let response = responder.create_response(msg.sender)?;
157 let sender_id = response.sender;
158
159 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 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 pub fn process_response(&mut self, msg: &HandshakeResponse) -> Result<PublicKey25519> {
191 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 let peer_public_key = initiator.remote_static_public();
201
202 let keys = initiator.process_response(msg)?;
204
205 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 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 pub fn get_session(&self, sender_id: u32) -> Option<&ActiveSession> {
236 self.active_sessions.get(&sender_id)
237 }
238
239 pub fn get_session_mut(&mut self, sender_id: u32) -> Option<&mut ActiveSession> {
241 self.active_sessions.get_mut(&sender_id)
242 }
243
244 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 pub fn active_sessions(&self) -> &HashMap<u32, ActiveSession> {
264 &self.active_sessions
265 }
266
267 pub fn peers(&self) -> &HashMap<PublicKey25519, PeerInfo> {
271 &self.peers
272 }
273
274 pub fn cleanup(&mut self) {
278 let now = std::time::Instant::now();
279 let session_timeout = std::time::Duration::from_secs(180); let _handshake_timeout = std::time::Duration::from_secs(30); self.active_sessions
284 .retain(|_, session| now.duration_since(session.last_used) < session_timeout);
285
286 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 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 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 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 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 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 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}