wfp 0.0.2

A Rust library for the Windows Filtering Platform (WFP) 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
478
479
//! Filter condition creation and management.

use std::ffi::OsStr;
use std::iter;
use std::os::windows::ffi::OsStrExt;
use std::sync::Arc;

use windows_sys::Win32::NetworkManagement::WindowsFilteringPlatform::{
    FWP_BYTE_BLOB, FWP_BYTE_BLOB_TYPE, FWP_MATCH_EQUAL, FWP_MATCH_GREATER,
    FWP_MATCH_GREATER_OR_EQUAL, FWP_MATCH_LESS, FWP_MATCH_LESS_OR_EQUAL, FWP_MATCH_RANGE,
    FWP_UINT8, FWP_UINT16, FWP_UINT32, FWP_UNICODE_STRING_TYPE, FWPM_CONDITION_ALE_APP_ID,
    FWPM_CONDITION_IP_LOCAL_ADDRESS, FWPM_CONDITION_IP_LOCAL_PORT, FWPM_CONDITION_IP_PROTOCOL,
    FWPM_CONDITION_IP_REMOTE_ADDRESS, FWPM_CONDITION_IP_REMOTE_PORT, FWPM_FILTER_CONDITION0,
};
use windows_sys::core::GUID;

/// Typed builder for port-based conditions.
///
/// This builder enforces that only valid port numbers (u16) can be used as values,
/// providing compile-time type safety for port-related filtering.
///
/// # Example
///
/// ```no_run
/// use wfp::{PortConditionBuilder, ConditionField, MatchType};
///
/// // Block traffic to port 80
/// let condition = PortConditionBuilder::remote()
///     .equal(80)
///     .build();
/// ```
#[derive(Clone)]
pub struct PortConditionBuilder<Value> {
    builder: ConditionBuilder,
    _pd: std::marker::PhantomData<Value>,
}

/// Type-state marker indicating the port value has not been set.
#[doc(hidden)]
pub struct PortConditionBuilderMissingValue;

/// Type-state marker indicating the port value has been set.
#[doc(hidden)]
pub struct PortConditionBuilderHasValue;

impl PortConditionBuilder<PortConditionBuilderMissingValue> {
    /// Creates a remote port condition.
    pub fn remote() -> Self {
        Self {
            builder: ConditionBuilder::default().field(ConditionField::RemotePort),
            _pd: std::marker::PhantomData,
        }
    }

    /// Creates a local port condition.
    pub fn local() -> Self {
        Self {
            builder: ConditionBuilder::default().field(ConditionField::LocalPort),
            _pd: std::marker::PhantomData,
        }
    }
}

impl<Value> PortConditionBuilder<Value> {
    /// Creates a condition that matches the exact port number.
    pub fn equal(self, port: u16) -> PortConditionBuilder<PortConditionBuilderHasValue> {
        PortConditionBuilder {
            builder: self.builder.match_type(MatchType::Equal).value_u16(port),
            _pd: std::marker::PhantomData,
        }
    }
}

impl PortConditionBuilder<PortConditionBuilderHasValue> {
    /// Builds the condition.
    ///
    /// This method is only available when a port value has been set with `equal()`.
    pub fn build(self) -> Condition {
        self.builder.build().expect("condition should be valid")
    }
}

/// Typed builder for protocol-based conditions.
///
/// This builder enforces that only valid protocol numbers (u32) can be used as values,
/// providing compile-time type safety for protocol-related filtering.
///
/// # Example
///
/// ```no_run
/// use wfp::{ProtocolConditionBuilder, MatchType};
///
/// // Block TCP traffic (protocol 6)
/// let tcp_condition = ProtocolConditionBuilder::tcp().build();
///
/// // Block UDP traffic (protocol 17)
/// let udp_condition = ProtocolConditionBuilder::udp().build();
/// ```
#[derive(Clone)]
pub struct ProtocolConditionBuilder {
    builder: ConditionBuilder,
}

impl ProtocolConditionBuilder {
    /// Creates a condition that matches TCP traffic (protocol 6).
    pub fn tcp() -> Self {
        Self::new().equal(6)
    }

    /// Creates a condition that matches UDP traffic (protocol 17).
    pub fn udp() -> Self {
        Self::new().equal(17)
    }

    /// Creates a condition that matches ICMP traffic (protocol 1).
    pub fn icmp() -> Self {
        Self::new().equal(1)
    }

    /// Creates a new protocol condition builder.
    fn new() -> Self {
        Self {
            builder: ConditionBuilder::default().field(ConditionField::Protocol),
        }
    }

    /// Creates a condition that matches the exact protocol number.
    fn equal(self, protocol: u8) -> Self {
        Self {
            builder: self.builder.match_type(MatchType::Equal).value_u8(protocol),
        }
    }

    /// Builds the condition.
    pub fn build(self) -> Condition {
        self.builder.build().expect("all values are set")
    }
}

impl Default for ProtocolConditionBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Typed builder for application ID conditions.
///
/// This builder enforces that only string paths can be used as values,
/// providing compile-time type safety for application-based filtering.
///
/// # Example
///
/// ```no_run
/// use wfp::AppIdConditionBuilder;
///
/// // Block traffic from a specific application
/// let app_condition = AppIdConditionBuilder::default()
///     .equal(r"C:\Program Files\MyApp\app.exe")
///     .build();
/// ```
pub struct AppIdConditionBuilder<Value> {
    builder: ConditionBuilder,
    _pd: std::marker::PhantomData<Value>,
}

/// Type-state marker indicating the app ID value has not been set.
#[doc(hidden)]
pub struct AppIdConditionBuilderMissingValue;

/// Type-state marker indicating the app ID value has been set.
#[doc(hidden)]
pub struct AppIdConditionBuilderHasValue;

impl AppIdConditionBuilder<AppIdConditionBuilderMissingValue> {
    /// Creates a new application ID condition builder.
    pub fn new() -> Self {
        Self {
            builder: ConditionBuilder::default().field(ConditionField::AppId),
            _pd: std::marker::PhantomData,
        }
    }
}

impl<Value> AppIdConditionBuilder<Value> {
    /// Creates a condition that matches the exact application path.
    pub fn equal(
        self,
        app_path: impl AsRef<OsStr>,
    ) -> AppIdConditionBuilder<AppIdConditionBuilderHasValue> {
        AppIdConditionBuilder {
            builder: self
                .builder
                .match_type(MatchType::Equal)
                .value_string(app_path),
            _pd: std::marker::PhantomData,
        }
    }
}

impl AppIdConditionBuilder<AppIdConditionBuilderHasValue> {
    /// Builds the condition.
    ///
    /// This method is only available when an application path has been set with `equal()`.
    pub fn build(self) -> Condition {
        self.builder.build().expect("condition should be valid")
    }
}

impl Default for AppIdConditionBuilder<AppIdConditionBuilderMissingValue> {
    fn default() -> Self {
        Self::new()
    }
}

/// Specifies how a condition value should be matched against network traffic.
///
/// These correspond to the [`FWP_MATCH_TYPE`] enumeration values.
///
/// [`FWP_MATCH_TYPE`]: https://docs.microsoft.com/en-us/windows/win32/api/fwptypes/ne-fwptypes-fwp_match_type
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatchType {
    /// The condition value must exactly match the network data.
    Equal = FWP_MATCH_EQUAL,
    /// The network data must be greater than the condition value.
    Greater = FWP_MATCH_GREATER,
    /// The network data must be less than the condition value.
    Less = FWP_MATCH_LESS,
    /// The network data must be greater than or equal to the condition value.
    GreaterOrEqual = FWP_MATCH_GREATER_OR_EQUAL,
    /// The network data must be less than or equal to the condition value.
    LessOrEqual = FWP_MATCH_LESS_OR_EQUAL,
    /// The network data must fall within a specified range.
    Range = FWP_MATCH_RANGE,
}

/// Represents different types of filter conditions that can be applied to network traffic.
///
/// Each condition type corresponds to a specific field in the network packet or connection
/// that can be inspected and matched against.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConditionField {
    /// Remote IP address of the connection.
    RemoteAddress,
    /// Local IP address of the connection.
    LocalAddress,
    /// Remote port number of the connection.
    RemotePort,
    /// Local port number of the connection.
    LocalPort,
    /// IP protocol (TCP, UDP, etc.).
    Protocol,
    /// Application ID (executable path).
    ///
    /// The lower-case fully qualified device path of the application.
    /// (For example, "\device\hardiskvolume1\program files\application.exe".)
    AppId,
}

impl ConditionField {
    /// Returns the Windows GUID identifier for this condition field.
    pub fn guid(&self) -> &GUID {
        match self {
            Self::RemoteAddress => &FWPM_CONDITION_IP_REMOTE_ADDRESS,
            Self::LocalAddress => &FWPM_CONDITION_IP_LOCAL_ADDRESS,
            Self::RemotePort => &FWPM_CONDITION_IP_REMOTE_PORT,
            Self::LocalPort => &FWPM_CONDITION_IP_LOCAL_PORT,
            Self::Protocol => &FWPM_CONDITION_IP_PROTOCOL,
            Self::AppId => &FWPM_CONDITION_ALE_APP_ID,
        }
    }
}

/// Builder for creating filter conditions.
///
/// Conditions specify criteria that network traffic must match for a filter to apply.
/// This builder provides a flexible way to construct conditions with appropriate
/// data types and match operations.
///
/// For type-safe alternatives, consider using the specialized builders:
/// - [`PortConditionBuilder`] for port-based conditions
/// - [`ProtocolConditionBuilder`] for protocol-based conditions
/// - [`AppIdConditionBuilder`] for application-based conditions
///
/// # Example
///
/// ```ignore
/// // Block traffic to port 80 (untyped approach)
/// let condition = ConditionBuilder::default()
///     .field(ConditionField::RemotePort)
///     .match_type(MatchType::Equal)
///     .value_u16(80)
///     .build()?;
/// ```
#[derive(Default, Clone)]
struct ConditionBuilder {
    field: Option<ConditionField>,
    match_type: Option<MatchType>,
    value: Option<Arc<ConditionValue>>,
}

/// Internal representation of condition values with their associated buffers.
#[derive(Clone)]
enum ConditionValue {
    UInt32(u32),
    UInt16(u16),
    UInt8(u8),
    String(Vec<u16>),
    ByteBlob { blob: FWP_BYTE_BLOB, _data: Vec<u8> },
}

impl ConditionBuilder {
    /// Sets the field that this condition will match against.
    pub fn field(mut self, field: ConditionField) -> Self {
        self.field = Some(field);
        self
    }

    /// Sets how the condition value should be matched.
    pub fn match_type(mut self, match_type: MatchType) -> Self {
        self.match_type = Some(match_type);
        self
    }

    /// Sets a 32-bit unsigned integer value for the condition.
    #[allow(dead_code)]
    pub fn value_u32(mut self, value: u32) -> Self {
        self.value = Some(ConditionValue::UInt32(value).into());
        self
    }

    /// Sets a 16-bit unsigned integer value for the condition.
    pub fn value_u16(mut self, value: u16) -> Self {
        self.value = Some(ConditionValue::UInt16(value).into());
        self
    }

    /// Sets a 8-bit unsigned integer value for the condition.
    pub fn value_u8(mut self, value: u8) -> Self {
        self.value = Some(ConditionValue::UInt8(value).into());
        self
    }

    /// Sets a string value for the condition.
    pub fn value_string(mut self, value: impl AsRef<OsStr>) -> Self {
        let wide_string: Vec<u16> = value
            .as_ref()
            .encode_wide()
            .chain(iter::once(0u16))
            .collect();
        self.value = Some(ConditionValue::String(wide_string).into());
        self
    }

    /// Sets a byte blob value for the condition.
    ///
    /// This is typically used for application IDs and other binary data that
    /// needs to be matched exactly. The data is copied into an internal buffer.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let app_id_data = b"\x01\x02\x03\x04"; // Example binary data
    /// let condition = ConditionBuilder::default()
    ///     .field(ConditionField::AppId)
    ///     .match_type(MatchType::Equal)
    ///     .value_byte_blob(app_id_data)
    ///     .build()?;
    /// ```
    #[allow(dead_code)]
    pub fn value_byte_blob(mut self, data: &[u8]) -> Self {
        let data = data.to_vec();
        self.value = Some(
            ConditionValue::ByteBlob {
                blob: FWP_BYTE_BLOB {
                    // SAFETY: The data is never mutated
                    data: data.as_ptr() as *mut _,
                    size: u32::try_from(data.len()).unwrap(),
                },
                _data: data,
            }
            .into(),
        );
        self
    }

    /// Builds the condition into the internal representation used by FilterBuilder.
    pub fn build(self) -> Option<Condition> {
        let field = self.field?;
        let match_type = self.match_type?;
        let value = self.value?;

        // SAFETY: This is a C struct
        let mut raw_condition: FWPM_FILTER_CONDITION0 = unsafe { std::mem::zeroed() };

        raw_condition.fieldKey = *field.guid();
        raw_condition.matchType = match_type as i32;

        match &*value {
            ConditionValue::UInt32(val) => {
                raw_condition.conditionValue.r#type = FWP_UINT32;
                raw_condition.conditionValue.Anonymous.uint32 = *val;
            }
            ConditionValue::UInt16(val) => {
                raw_condition.conditionValue.r#type = FWP_UINT16;
                raw_condition.conditionValue.Anonymous.uint16 = *val;
            }
            ConditionValue::UInt8(val) => {
                raw_condition.conditionValue.r#type = FWP_UINT8;
                raw_condition.conditionValue.Anonymous.uint8 = *val;
            }
            ConditionValue::String(wide_str) => {
                raw_condition.conditionValue.r#type = FWP_UNICODE_STRING_TYPE;
                // SAFETY: The data is never mutated, and is tied to the lifetime of Condition
                raw_condition.conditionValue.Anonymous.unicodeString = wide_str.as_ptr() as *mut _;
            }
            ConditionValue::ByteBlob { blob, _data: _ } => {
                raw_condition.conditionValue.r#type = FWP_BYTE_BLOB_TYPE;
                // SAFETY: The data is never mutated, and is tied to the lifetime of Condition
                raw_condition.conditionValue.Anonymous.byteBlob = blob as *const _ as *mut _;
            }
        }

        Some(Condition {
            raw_condition,
            _value: value,
        })
    }
}

/// Internal representation of a built condition.
///
/// This can be added to a [`FilterBuilder`](crate::FilterBuilder).
#[derive(Clone)]
pub struct Condition {
    raw_condition: FWPM_FILTER_CONDITION0,
    // This keeps underlying pointers and data valid
    _value: Arc<ConditionValue>,
}

impl Condition {
    /// Return the underlying FWPM_FILTER_CONDITION0 structure.
    pub(crate) fn raw_condition(&self) -> &FWPM_FILTER_CONDITION0 {
        &self.raw_condition
    }
}

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

    #[test]
    fn test_condition_port_remote() {
        let condition = PortConditionBuilder::remote().equal(80).build();

        assert_eq!(
            condition.raw_condition.fieldKey.data1,
            FWPM_CONDITION_IP_REMOTE_PORT.data1
        );
        assert_eq!(
            condition.raw_condition.fieldKey.data2,
            FWPM_CONDITION_IP_REMOTE_PORT.data2
        );
        assert_eq!(
            condition.raw_condition.fieldKey.data3,
            FWPM_CONDITION_IP_REMOTE_PORT.data3
        );
        assert_eq!(
            condition.raw_condition.fieldKey.data4,
            FWPM_CONDITION_IP_REMOTE_PORT.data4
        );

        assert_eq!(condition.raw_condition.matchType, FWP_MATCH_EQUAL);
        assert_eq!(
            unsafe { condition.raw_condition.conditionValue.Anonymous.uint16 },
            80
        );
    }
}