windows-wfp 0.2.1

Safe Rust wrapper for the Windows Filtering Platform (WFP) kernel-level firewall API
Documentation
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! WFP Network Event Subscription (Learning Mode)
//!
//! Subscribes to WFP network events to monitor blocked connections.
//! Used for learning mode where blocked traffic is logged for auto-whitelisting.

use crate::engine::WfpEngine;
use crate::errors::{WfpError, WfpResult};
use std::ffi::{c_void, OsString};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, SystemTime};
use windows::core::GUID;
use windows::Win32::Foundation::{ERROR_SUCCESS, FILETIME, HANDLE};
use windows::Win32::NetworkManagement::WindowsFilteringPlatform::{
    FwpmNetEventSubscribe0, FwpmNetEventUnsubscribe0, FWPM_NET_EVENT1, FWPM_NET_EVENT_CALLBACK0,
    FWPM_NET_EVENT_SUBSCRIPTION0,
};

/// Network event from WFP
///
/// Represents a network event captured by the Windows Filtering Platform.
/// Used in learning mode to identify applications that were blocked.
#[derive(Debug, Clone)]
pub struct NetworkEvent {
    /// When the event occurred
    pub timestamp: SystemTime,

    /// Type of event (Classify Drop, Classify Allow, etc.)
    pub event_type: NetworkEventType,

    /// Application path that triggered the event (if available)
    pub app_path: Option<PathBuf>,

    /// IP protocol (TCP=6, UDP=17, etc.)
    pub protocol: u8,

    /// Local IP address
    pub local_addr: Option<IpAddr>,

    /// Remote IP address
    pub remote_addr: Option<IpAddr>,

    /// Local port
    pub local_port: u16,

    /// Remote port
    pub remote_port: u16,

    /// Filter ID that triggered the event (for CLASSIFY_DROP)
    pub filter_id: Option<u64>,

    /// Layer ID where event occurred
    pub layer_id: Option<u16>,
}

/// Type of network event
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum NetworkEventType {
    /// Connection was blocked by a filter
    ClassifyDrop = 3,

    /// Connection was allowed by a filter (Win8+)
    ClassifyAllow = 6,

    /// App container capability drop (Win8+)
    CapabilityDrop = 7,

    /// Other event type
    Other(u32),
}

impl From<u32> for NetworkEventType {
    fn from(value: u32) -> Self {
        match value {
            3 => NetworkEventType::ClassifyDrop,
            6 => NetworkEventType::ClassifyAllow,
            7 => NetworkEventType::CapabilityDrop,
            other => NetworkEventType::Other(other),
        }
    }
}

impl std::fmt::Display for NetworkEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NetworkEventType::ClassifyDrop => write!(f, "ClassifyDrop"),
            NetworkEventType::ClassifyAllow => write!(f, "ClassifyAllow"),
            NetworkEventType::CapabilityDrop => write!(f, "CapabilityDrop"),
            NetworkEventType::Other(n) => write!(f, "Other({})", n),
        }
    }
}

/// WFP Event Subscription Handle
///
/// RAII wrapper for WFP event subscription. Automatically unsubscribes on drop.
/// Events are delivered via an mpsc channel for thread-safe processing.
pub struct WfpEventSubscription {
    engine: *const WfpEngine,
    subscription_handle: HANDLE,
    _callback: Box<FWPM_NET_EVENT_CALLBACK0>, // Keep callback alive
    receiver: mpsc::Receiver<NetworkEvent>,
    /// Raw pointer to the boxed `Sender<NetworkEvent>` used as the WFP callback context.
    /// Must be freed after `FwpmNetEventUnsubscribe0` to avoid a memory leak.
    sender_context: *mut c_void,
}

impl WfpEventSubscription {
    /// Subscribe to WFP network events
    ///
    /// Creates a new event subscription that monitors network events.
    /// Events are delivered via the returned receiver channel.
    ///
    /// # Errors
    ///
    /// Returns error if subscription fails (permissions, invalid engine, etc.)
    pub fn new(engine: &WfpEngine) -> WfpResult<Self> {
        let (sender, receiver) = mpsc::channel();

        // Box the channel sender so it has a stable address for the context pointer
        let sender_box = Box::new(sender);
        let context = Box::into_raw(sender_box) as *mut c_void;

        // Create the callback function
        let callback: FWPM_NET_EVENT_CALLBACK0 = Some(event_callback);

        // Create subscription for all events
        let subscription = FWPM_NET_EVENT_SUBSCRIPTION0 {
            enumTemplate: std::ptr::null_mut(), // Subscribe to all events
            flags: 0,
            sessionKey: GUID::zeroed(),
        };

        let mut subscription_handle = HANDLE::default();

        unsafe {
            let result = FwpmNetEventSubscribe0(
                engine.handle(),
                &subscription,
                callback,
                Some(context as *const c_void),
                &mut subscription_handle,
            );

            if result != ERROR_SUCCESS.0 {
                // Clean up the boxed sender on error
                drop(Box::from_raw(context as *mut mpsc::Sender<NetworkEvent>));
                return Err(WfpError::Other(format!(
                    "Failed to subscribe to WFP events: error code {}",
                    result
                )));
            }
        }

        Ok(Self {
            engine: engine as *const WfpEngine,
            subscription_handle,
            _callback: Box::new(callback), // Keep callback alive to prevent GC
            receiver,
            sender_context: context,
        })
    }

    /// Try to receive a network event (non-blocking)
    pub fn try_recv(&self) -> Result<NetworkEvent, mpsc::TryRecvError> {
        self.receiver.try_recv()
    }

    /// Receive a network event (blocking)
    pub fn recv(&self) -> Result<NetworkEvent, mpsc::RecvError> {
        self.receiver.recv()
    }

    /// Get an iterator over pending events
    pub fn iter(&self) -> mpsc::Iter<'_, NetworkEvent> {
        self.receiver.iter()
    }
}

impl Drop for WfpEventSubscription {
    fn drop(&mut self) {
        if !self.subscription_handle.is_invalid() && !self.engine.is_null() {
            unsafe {
                // Unsubscribe first so no more callbacks can fire before we free the context
                let _ = FwpmNetEventUnsubscribe0((*self.engine).handle(), self.subscription_handle);
            }
        }
        // Free the boxed Sender that was passed as the WFP callback context.
        // Safe to do now because WfpmNetEventUnsubscribe0 guarantees no further callbacks.
        if !self.sender_context.is_null() {
            unsafe {
                drop(Box::from_raw(
                    self.sender_context as *mut mpsc::Sender<NetworkEvent>,
                ));
            }
        }
    }
}

/// Native callback function invoked by WFP (runs on WFP worker thread)
///
/// # Safety
///
/// This function receives raw pointers from WFP and must carefully:
/// - Validate the event pointer is not null
/// - Parse the FWPM_NET_EVENT1 structure
/// - Send the parsed event to the channel without blocking
unsafe extern "system" fn event_callback(context: *mut c_void, event_ptr: *const FWPM_NET_EVENT1) {
    // Validate pointers
    if context.is_null() || event_ptr.is_null() {
        return;
    }

    // Recover the sender from the context
    let sender = &*(context as *const mpsc::Sender<NetworkEvent>);

    // Parse the event
    let event = &*event_ptr;
    if let Some(network_event) = parse_network_event(event) {
        // Send to channel (non-blocking - drops event if channel is full)
        let _ = sender.send(network_event);
    }
}

/// Parse FWPM_NET_EVENT1 into NetworkEvent
///
/// # Safety
///
/// The event pointer must be valid and point to a complete FWPM_NET_EVENT1 structure.
unsafe fn parse_network_event(event: &FWPM_NET_EVENT1) -> Option<NetworkEvent> {
    let header = &event.header;
    let event_type = NetworkEventType::from(event.r#type.0 as u32);

    // Parse timestamp (FILETIME to SystemTime)
    let timestamp = filetime_to_systemtime(&header.timeStamp);

    // Parse application path (wide string) - appId.data is *mut u8, need to cast
    let app_path = if !header.appId.data.is_null() {
        parse_wide_string(header.appId.data as *const u16).map(PathBuf::from)
    } else {
        None
    };

    // Parse IP addresses based on IP version (ipVersion: 0=V4, 1=V6)
    let (local_addr, remote_addr) = if header.ipVersion.0 == 0 {
        // IPv4
        unsafe {
            let local = parse_ipv4_union(&header.Anonymous1);
            let remote = parse_ipv4_union_remote(&header.Anonymous2);
            (local, remote)
        }
    } else if header.ipVersion.0 == 1 {
        // IPv6
        unsafe {
            let local = parse_ipv6_union(&header.Anonymous1);
            let remote = parse_ipv6_union_remote(&header.Anonymous2);
            (local, remote)
        }
    } else {
        (None, None)
    };

    // Parse filter ID and layer ID for CLASSIFY_DROP events
    let (filter_id, layer_id) = if event_type == NetworkEventType::ClassifyDrop {
        unsafe {
            if !event.Anonymous.classifyDrop.is_null() {
                let drop_info = &*event.Anonymous.classifyDrop;
                (Some(drop_info.filterId), Some(drop_info.layerId))
            } else {
                (None, None)
            }
        }
    } else {
        (None, None)
    };

    Some(NetworkEvent {
        timestamp,
        event_type,
        app_path,
        protocol: header.ipProtocol,
        local_addr,
        remote_addr,
        local_port: header.localPort,
        remote_port: header.remotePort,
        filter_id,
        layer_id,
    })
}

/// Convert FILETIME to SystemTime
fn filetime_to_systemtime(ft: &FILETIME) -> SystemTime {
    // FILETIME is 100-nanosecond intervals since January 1, 1601 (UTC)
    // SystemTime is based on UNIX_EPOCH (January 1, 1970)

    // Difference between Windows epoch (1601) and UNIX epoch (1970) in 100-ns intervals
    const WINDOWS_TO_UNIX_EPOCH: u64 = 116444736000000000;

    let intervals = ((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64);

    if intervals >= WINDOWS_TO_UNIX_EPOCH {
        let unix_intervals = intervals - WINDOWS_TO_UNIX_EPOCH;
        let secs = unix_intervals / 10_000_000;
        let nanos = ((unix_intervals % 10_000_000) * 100) as u32;

        SystemTime::UNIX_EPOCH + Duration::new(secs, nanos)
    } else {
        SystemTime::UNIX_EPOCH
    }
}

/// Parse wide string (null-terminated UTF-16)
unsafe fn parse_wide_string(ptr: *const u16) -> Option<OsString> {
    if ptr.is_null() {
        return None;
    }

    // Find the null terminator
    let mut len = 0;
    while *ptr.add(len) != 0 {
        len += 1;
    }

    if len == 0 {
        return None;
    }

    // Convert to OsString
    let slice = std::slice::from_raw_parts(ptr, len);
    Some(OsString::from_wide(slice))
}

/// Parse IPv4 address from union (reads first 4 bytes as u32) - HEADER1_0 version
unsafe fn parse_ipv4_union(
    addr_union: &windows::Win32::NetworkManagement::WindowsFilteringPlatform::FWPM_NET_EVENT_HEADER1_0,
) -> Option<IpAddr> {
    // Union contains localAddrV4 as u32
    let addr_u32 = addr_union.localAddrV4;
    let bytes = addr_u32.to_ne_bytes();
    Some(IpAddr::V4(Ipv4Addr::from(bytes)))
}

/// Parse IPv6 address from union (reads 16-byte array) - HEADER1_0 version
unsafe fn parse_ipv6_union(
    addr_union: &windows::Win32::NetworkManagement::WindowsFilteringPlatform::FWPM_NET_EVENT_HEADER1_0,
) -> Option<IpAddr> {
    // Union contains localAddrV6 as byte[16]
    let bytes = addr_union.localAddrV6.byteArray16;
    Some(IpAddr::V6(Ipv6Addr::from(bytes)))
}

/// Parse IPv4 address from remote union (HEADER1_1 version)
unsafe fn parse_ipv4_union_remote(
    addr_union: &windows::Win32::NetworkManagement::WindowsFilteringPlatform::FWPM_NET_EVENT_HEADER1_1,
) -> Option<IpAddr> {
    let addr_u32 = addr_union.remoteAddrV4;
    let bytes = addr_u32.to_ne_bytes();
    Some(IpAddr::V4(Ipv4Addr::from(bytes)))
}

/// Parse IPv6 address from remote union (HEADER1_1 version)
unsafe fn parse_ipv6_union_remote(
    addr_union: &windows::Win32::NetworkManagement::WindowsFilteringPlatform::FWPM_NET_EVENT_HEADER1_1,
) -> Option<IpAddr> {
    let bytes = addr_union.remoteAddrV6.byteArray16;
    Some(IpAddr::V6(Ipv6Addr::from(bytes)))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_event_type_conversion() {
        assert_eq!(NetworkEventType::from(3), NetworkEventType::ClassifyDrop);
        assert_eq!(NetworkEventType::from(6), NetworkEventType::ClassifyAllow);
        assert_eq!(NetworkEventType::from(7), NetworkEventType::CapabilityDrop);
        assert_eq!(NetworkEventType::from(99), NetworkEventType::Other(99));
    }

    #[test]
    fn test_event_type_boundaries() {
        assert_eq!(NetworkEventType::from(0), NetworkEventType::Other(0));
        assert_eq!(NetworkEventType::from(2), NetworkEventType::Other(2));
        assert_eq!(NetworkEventType::from(4), NetworkEventType::Other(4));
        assert_eq!(NetworkEventType::from(5), NetworkEventType::Other(5));
        assert_eq!(NetworkEventType::from(8), NetworkEventType::Other(8));
    }

    #[test]
    fn test_filetime_to_systemtime_unix_epoch() {
        // FILETIME for Unix epoch (Jan 1, 1970) = 116444736000000000
        let intervals: u64 = 116444736000000000;
        let ft = FILETIME {
            dwLowDateTime: intervals as u32,
            dwHighDateTime: (intervals >> 32) as u32,
        };
        let result = filetime_to_systemtime(&ft);
        assert_eq!(result, SystemTime::UNIX_EPOCH);
    }

    #[test]
    fn test_filetime_to_systemtime_before_unix_epoch() {
        let ft = FILETIME {
            dwLowDateTime: 0,
            dwHighDateTime: 0,
        };
        assert_eq!(filetime_to_systemtime(&ft), SystemTime::UNIX_EPOCH);
    }

    #[test]
    fn test_filetime_to_systemtime_known_date() {
        // Jan 1, 2000 = 125911584000000000 intervals from Windows epoch
        let intervals: u64 = 125911584000000000;
        let ft = FILETIME {
            dwLowDateTime: intervals as u32,
            dwHighDateTime: (intervals >> 32) as u32,
        };
        let result = filetime_to_systemtime(&ft);
        let duration = result.duration_since(SystemTime::UNIX_EPOCH).unwrap();
        assert_eq!(duration.as_secs(), 946684800); // Jan 1, 2000
    }

    #[test]
    fn test_network_event_struct_creation() {
        let event = NetworkEvent {
            timestamp: SystemTime::UNIX_EPOCH,
            event_type: NetworkEventType::ClassifyDrop,
            app_path: Some(PathBuf::from(r"C:\test.exe")),
            protocol: 6,
            local_addr: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            remote_addr: Some(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))),
            local_port: 12345,
            remote_port: 443,
            filter_id: Some(42),
            layer_id: Some(1),
        };

        assert_eq!(event.event_type, NetworkEventType::ClassifyDrop);
        assert_eq!(event.protocol, 6);
        assert_eq!(event.local_port, 12345);
        assert_eq!(event.remote_port, 443);
        assert!(event.app_path.is_some());
    }

    #[test]
    fn test_network_event_clone() {
        let event = NetworkEvent {
            timestamp: SystemTime::UNIX_EPOCH,
            event_type: NetworkEventType::ClassifyAllow,
            app_path: None,
            protocol: 17,
            local_addr: None,
            remote_addr: None,
            local_port: 0,
            remote_port: 0,
            filter_id: None,
            layer_id: None,
        };

        let cloned = event.clone();
        assert_eq!(cloned.event_type, NetworkEventType::ClassifyAllow);
        assert_eq!(cloned.protocol, 17);
        assert!(cloned.app_path.is_none());
    }

    #[test]
    fn test_network_event_type_display() {
        assert_eq!(NetworkEventType::ClassifyDrop.to_string(), "ClassifyDrop");
        assert_eq!(NetworkEventType::ClassifyAllow.to_string(), "ClassifyAllow");
        assert_eq!(NetworkEventType::CapabilityDrop.to_string(), "CapabilityDrop");
        assert_eq!(NetworkEventType::Other(42).to_string(), "Other(42)");
    }
}