1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#[allow(unused_imports)]
use chrono::Utc;
#[allow(unused_imports)]
use relay_core_api::flow::{Flow, FlowUpdate, Layer, NetworkInfo, TransportProtocol, UdpLayer};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::net::UdpSocket;
use tokio::sync::RwLock;
use tokio::sync::mpsc::Sender;
use uuid::Uuid;
#[cfg(target_os = "linux")]
use crate::capture::linux_tproxy::LinuxTproxy;
use std::sync::atomic::{AtomicUsize, Ordering};
/// Key for UDP session (5-tuple)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UdpSessionKey {
pub src_ip: IpAddr,
pub src_port: u16,
pub dst_ip: IpAddr,
pub dst_port: u16,
// Protocol is implicitly UDP
}
impl UdpSessionKey {
pub fn new(src: SocketAddr, dst: SocketAddr) -> Self {
Self {
src_ip: src.ip(),
src_port: src.port(),
dst_ip: dst.ip(),
dst_port: dst.port(),
}
}
}
/// UDP Session Metadata
#[derive(Debug, Clone)]
pub struct UdpSession {
pub flow_id: Uuid,
pub key: UdpSessionKey,
pub created_at: Instant,
pub last_activity: Arc<RwLock<Instant>>,
pub packet_count: Arc<AtomicUsize>,
pub bytes_transferred: Arc<AtomicUsize>,
#[cfg(target_os = "linux")]
pub upstream_socket: Option<Arc<UdpSocket>>, // Bound to src, connected to dst
#[cfg(target_os = "linux")]
pub downstream_socket: Option<Arc<UdpSocket>>, // Bound to dst, connected to src
}
/// Manager for tracking active UDP sessions
pub struct UdpSessionManager {
sessions: RwLock<HashMap<UdpSessionKey, UdpSession>>,
idle_timeout: Duration,
}
impl UdpSessionManager {
pub fn new(idle_timeout: Duration) -> Self {
Self {
sessions: RwLock::new(HashMap::new()),
idle_timeout,
}
}
/// Get existing session or create new one
/// Returns (session, is_new)
pub async fn get_or_create_session(
&self,
src: SocketAddr,
dst: SocketAddr,
) -> std::io::Result<(UdpSession, bool)> {
let key = UdpSessionKey::new(src, dst);
// Fast path: read lock
{
let sessions = self.sessions.read().await;
if let Some(session) = sessions.get(&key) {
let mut last = session.last_activity.write().await;
*last = Instant::now();
session.packet_count.fetch_add(1, Ordering::Relaxed);
return Ok((session.clone(), false));
}
}
// Slow path: write lock
let mut sessions = self.sessions.write().await;
// Check again
if let Some(session) = sessions.get(&key) {
let mut last = session.last_activity.write().await;
*last = Instant::now();
session.packet_count.fetch_add(1, Ordering::Relaxed);
return Ok((session.clone(), false));
}
#[cfg(target_os = "linux")]
let (upstream, downstream) = {
// Create upstream socket: Bound to src, connect to dst
let up = LinuxTproxy::create_transparent_udp_socket(src)?;
up.connect(dst).await?;
// Create downstream socket: Bound to dst, connect to src
let down = LinuxTproxy::create_transparent_udp_socket(dst)?;
down.connect(src).await?;
(Some(Arc::new(up)), Some(Arc::new(down)))
};
// Create new session
let session = UdpSession {
flow_id: Uuid::new_v4(),
key: key.clone(),
created_at: Instant::now(),
last_activity: Arc::new(RwLock::new(Instant::now())),
packet_count: Arc::new(AtomicUsize::new(1)),
bytes_transferred: Arc::new(AtomicUsize::new(0)),
#[cfg(target_os = "linux")]
upstream_socket: upstream,
#[cfg(target_os = "linux")]
downstream_socket: downstream,
};
// Spawn reverse proxy task (B -> A)
#[cfg(target_os = "linux")]
if let (Some(up), Some(down)) = (&session.upstream_socket, &session.downstream_socket) {
let up_clone = up.clone();
let down_clone = down.clone();
let last_activity = session.last_activity.clone();
let bytes_transferred = session.bytes_transferred.clone();
tokio::spawn(async move {
let mut buf = [0u8; 65535];
loop {
// Read from upstream (response from Server B)
match up_clone.recv(&mut buf).await {
Ok(n) => {
// Update activity
if let Ok(mut last) = last_activity.try_write() {
*last = Instant::now();
}
bytes_transferred.fetch_add(n, Ordering::Relaxed);
// Send to downstream (to Client A)
if let Err(e) = down_clone.send(&buf[..n]).await {
tracing::debug!("UDP downstream send error: {}", e);
break;
}
}
Err(e) => {
tracing::debug!("UDP upstream recv error: {}", e);
break;
}
}
}
});
}
sessions.insert(key, session.clone());
Ok((session, true))
}
/// Clean up idle sessions
pub async fn cleanup_idle_sessions(&self) -> Vec<Uuid> {
let mut sessions = self.sessions.write().await;
let now = Instant::now();
let mut removed_ids = Vec::new();
let mut keys_to_remove = Vec::new();
// Identify idle sessions
for (key, session) in sessions.iter() {
let last = *session.last_activity.read().await;
if now.duration_since(last) > self.idle_timeout {
removed_ids.push(session.flow_id);
keys_to_remove.push(key.clone());
}
}
// Remove them
for key in keys_to_remove {
sessions.remove(&key);
}
removed_ids
}
}
/// UDP Proxy capable of handling multiple sessions
pub struct UdpProxy {
socket: Arc<UdpSocket>,
session_manager: Arc<UdpSessionManager>,
remote_addr: Option<SocketAddr>,
}
impl UdpProxy {
pub fn new(socket: UdpSocket, idle_timeout: Duration) -> Self {
Self {
socket: Arc::new(socket),
session_manager: Arc::new(UdpSessionManager::new(idle_timeout)),
remote_addr: None,
}
}
pub fn with_remote(mut self, addr: SocketAddr) -> Self {
self.remote_addr = Some(addr);
self
}
/// Run the proxy loop
pub async fn run(&self, on_flow: Sender<FlowUpdate>) -> crate::error::Result<()> {
let mut buf = [0u8; 65535];
#[cfg(target_os = "linux")]
{
// Enable TPROXY on socket
LinuxTproxy::enable_tproxy(&self.socket)?;
loop {
// Use recv_original_dst
let (len, src_addr, orig_dst) =
match LinuxTproxy::recv_original_dst(&self.socket, &mut buf).await {
Ok(res) => res,
Err(e) => {
tracing::error!("UDP TPROXY recv error: {}", e);
continue;
}
};
if let Some(dst_addr) = orig_dst {
match self
.session_manager
.get_or_create_session(src_addr, dst_addr)
.await
{
Ok((session, is_new)) => {
if is_new {
// Create initial flow
let flow = Flow {
id: session.flow_id,
start_time: Utc::now(),
end_time: None,
network: NetworkInfo {
client_ip: src_addr.ip().to_string(),
client_port: src_addr.port(),
server_ip: dst_addr.ip().to_string(),
server_port: dst_addr.port(),
protocol: TransportProtocol::UDP,
tls: false,
tls_version: None,
sni: None,
},
layer: Layer::Udp(UdpLayer {
payload_size: len,
packet_count: 1,
}),
tags: vec![],
meta: HashMap::new(),
resilience_trace: None,
rule_variables: HashMap::new(),
matched_rules: vec![],
};
if on_flow.try_send(FlowUpdate::Full(Box::new(flow))).is_err() {
crate::metrics::inc_flows_dropped();
}
}
// Forward packet logic (A -> B)
// Using upstream socket bound to src_addr
if let Some(upstream) = &session.upstream_socket {
if let Err(e) = upstream.send(&buf[..len]).await {
tracing::debug!("UDP upstream send error: {}", e);
} else {
session.bytes_transferred.fetch_add(len, Ordering::Relaxed);
}
}
}
Err(e) => {
tracing::warn!("Failed to create UDP session: {}", e);
}
}
}
}
}
#[cfg(not(target_os = "linux"))]
{
let remote_addr = match self.remote_addr {
Some(addr) => addr,
None => {
tracing::warn!(
"UDP proxy started without remote_addr on non-Linux; no forwarding"
);
loop {
match self.socket.recv_from(&mut buf).await {
Ok((_len, _src_addr)) => {}
Err(e) => {
tracing::error!("UDP drain recv error: {}", e);
continue;
}
}
}
}
};
let sm = self.session_manager.clone();
let sock = self.socket.clone();
let flow_tx = on_flow;
loop {
let (len, src_addr) = match sock.recv_from(&mut buf).await {
Ok(res) => res,
Err(e) => {
tracing::error!("UDP recv error: {}", e);
continue;
}
};
let (session, is_new) = match sm.get_or_create_session(src_addr, remote_addr).await
{
Ok(res) => res,
Err(e) => {
tracing::warn!("Failed to create UDP session: {}", e);
continue;
}
};
if is_new {
let flow = Flow {
id: session.flow_id,
start_time: Utc::now(),
end_time: None,
network: NetworkInfo {
client_ip: src_addr.ip().to_string(),
client_port: src_addr.port(),
server_ip: remote_addr.ip().to_string(),
server_port: remote_addr.port(),
protocol: TransportProtocol::UDP,
tls: false,
tls_version: None,
sni: None,
},
layer: Layer::Udp(UdpLayer {
payload_size: len,
packet_count: 1,
}),
tags: vec![],
meta: HashMap::new(),
resilience_trace: None,
rule_variables: HashMap::new(),
matched_rules: vec![],
};
let _ = flow_tx.try_send(FlowUpdate::Full(Box::new(flow)));
let sock_clone = sock.clone();
let bytes = session.bytes_transferred.clone();
let last = session.last_activity.clone();
tokio::spawn(async move {
let mut rbuf = [0u8; 65535];
loop {
match sock_clone.recv_from(&mut rbuf).await {
Ok((n, addr)) => {
if addr == remote_addr {
let _ = sock_clone.send_to(&rbuf[..n], src_addr).await;
bytes.fetch_add(n, Ordering::Relaxed);
if let Ok(mut la) = last.try_write() {
*la = Instant::now();
}
}
}
Err(e) => {
tracing::debug!(
"UDP reverse recv error for {}: {}",
session.flow_id,
e
);
break;
}
}
}
});
}
match sock.send_to(&buf[..len], remote_addr).await {
Ok(_) => {
session.bytes_transferred.fetch_add(len, Ordering::Relaxed);
}
Err(e) => {
tracing::debug!("UDP send_to {} error: {}", remote_addr, e);
}
}
}
}
}
}