Skip to main content

WfpEngine

Struct WfpEngine 

Source
pub struct WfpEngine { /* private fields */ }
Expand description

WFP Engine session with RAII handle management

Opens a session to the Windows Filtering Platform on creation and automatically closes it on drop.

§Examples

use windows_wfp::WfpEngine;

let engine = WfpEngine::new()?;
// Use engine for filter operations
// Session automatically closed when engine goes out of scope

Implementations§

Source§

impl WfpEngine

Source

pub fn new() -> WfpResult<Self>

Open a new WFP engine session

Requires administrator privileges.

§Errors

Returns WfpError::EngineOpenFailed if:

  • Insufficient permissions (not running as admin)
  • WFP service not available
  • Session creation failed
§Examples
use windows_wfp::WfpEngine;

let engine = WfpEngine::new()?;
Examples found in repository?
examples/simple_block.rs (line 29)
24fn main() -> WfpResult<()> {
25    println!("windows-wfp - Simple Block Demo\n");
26
27    // Initialize WFP
28    println!("Opening WFP Engine...");
29    let engine = WfpEngine::new()?;
30    println!("Engine opened\n");
31
32    println!("Registering provider...");
33    initialize_wfp(&engine)?;
34    println!("Provider registered\n");
35
36    // Block notepad.exe outbound connections
37    println!("Adding block filter for notepad.exe...");
38    let notepad_rule = FilterRule::new("Block Notepad", Direction::Outbound, Action::Block)
39        .with_weight(FilterWeight::UserBlock)
40        .with_app_path(r"C:\Windows\System32\notepad.exe");
41
42    let filter_id = FilterBuilder::add_filter(&engine, &notepad_rule)?;
43    println!("Filter added (ID: {})\n", filter_id);
44
45    println!("Filter active for 10 seconds...");
46    println!("   (Try opening notepad.exe and accessing network)\n");
47
48    for i in (1..=10).rev() {
49        println!("   {} seconds remaining...", i);
50        thread::sleep(Duration::from_secs(1));
51    }
52
53    println!("\nRemoving filter...");
54    FilterBuilder::delete_filter(&engine, filter_id)?;
55    println!("Filter removed\n");
56
57    println!("Demo complete!");
58    Ok(())
59}
More examples
Hide additional examples
examples/list_filters.rs (line 19)
16fn main() -> WfpResult<()> {
17    println!("WFP Filter Enumeration\n");
18
19    let engine = WfpEngine::new()?;
20    let filters = FilterEnumerator::all(&engine)?;
21
22    println!(
23        "{:<10} {:<40} {:<15} {:<15} {:<60}",
24        "Filter ID", "Name", "Action", "Weight", "App Path"
25    );
26    println!("{:-<140}", "");
27
28    for filter in &filters {
29        let action = match filter.action {
30            FilterAction::Block => "BLOCK",
31            FilterAction::Permit => "PERMIT",
32            FilterAction::CalloutTerminating => "CALLOUT_TERM",
33            FilterAction::CalloutInspection => "CALLOUT_INSP",
34            FilterAction::CalloutUnknown => "CALLOUT_UNK",
35            FilterAction::Other(_) => "OTHER",
36        };
37
38        let name: String = if filter.name.chars().count() > 40 {
39            let truncated: String = filter.name.chars().take(37).collect();
40            format!("{}...", truncated)
41        } else {
42            filter.name.clone()
43        };
44
45        let app = filter
46            .app_path
47            .as_ref()
48            .map(|p| p.to_string_lossy().to_string())
49            .unwrap_or_default();
50
51        println!(
52            "{:<10} {:<40} {:<15} {:<15} {:<60}",
53            filter.id, name, action, filter.weight, app
54        );
55    }
56
57    println!("{:-<140}", "");
58    println!("\nTotal filters: {}", filters.len());
59
60    Ok(())
61}
examples/live_demo.rs (line 48)
32fn main() -> WfpResult<()> {
33    println!("windows-wfp - Live WFP Demo");
34    println!("================================\n");
35
36    // Check for admin privileges
37    if !is_elevated() {
38        eprintln!("ERROR: This demo requires Administrator privileges!");
39        eprintln!("   Please run: cargo run --example live_demo --release");
40        eprintln!("   from an Administrator command prompt.\n");
41        std::process::exit(1);
42    }
43
44    println!("Running with Administrator privileges\n");
45
46    // Step 1: Initialize WFP Engine
47    println!("Step 1: Opening WFP Engine session...");
48    let engine = WfpEngine::new()?;
49    println!("   Engine session opened\n");
50
51    // Step 2: Register Provider & Sublayer
52    println!("Step 2: Registering WFP provider & sublayer...");
53    initialize_wfp(&engine)?;
54    println!("   Provider & sublayer registered\n");
55
56    // Step 3: Subscribe to network events
57    println!("Step 3: Subscribing to network events...");
58    let event_subscription = WfpEventSubscription::new(&engine)?;
59    println!("   Event subscription active\n");
60
61    // Step 4: Add blocking filter for curl.exe
62    println!("Step 4: Adding block filter for curl.exe...");
63    let curl_path = find_curl_path();
64    println!("   Target: {}", curl_path.display());
65
66    let block_rule = FilterRule::new("Block curl.exe", Direction::Outbound, Action::Block)
67        .with_weight(FilterWeight::UserBlock)
68        .with_app_path(curl_path.clone());
69
70    let filter_id = FilterBuilder::add_filter(&engine, &block_rule)?;
71    println!("   Filter added (ID: {})\n", filter_id);
72
73    // Step 5: Monitor events
74    println!("Step 5: Monitoring network events...");
75    println!("   Press Ctrl+C to stop\n");
76    println!("TIP: In another terminal, run:");
77    println!("   > curl https://google.com");
78    println!("   You should see the connection BLOCKED below!\n");
79    println!("===================================================\n");
80
81    let start_time = std::time::Instant::now();
82    let mut event_count = 0;
83
84    loop {
85        match event_subscription.try_recv() {
86            Ok(event) => {
87                event_count += 1;
88                print_event(&event, event_count);
89            }
90            Err(std::sync::mpsc::TryRecvError::Empty) => {
91                thread::sleep(Duration::from_millis(100));
92            }
93            Err(std::sync::mpsc::TryRecvError::Disconnected) => {
94                println!("\nEvent channel disconnected!");
95                break;
96            }
97        }
98
99        // Auto-stop after 60 seconds for demo
100        if start_time.elapsed() > Duration::from_secs(60) {
101            println!("\nDemo timeout (60s) - stopping...");
102            break;
103        }
104    }
105
106    // Cleanup
107    println!("\nCleaning up...");
108    FilterBuilder::delete_filter(&engine, filter_id)?;
109    println!("   Filter removed");
110    drop(event_subscription);
111    println!("   Event subscription closed");
112    drop(engine);
113    println!("   Engine session closed\n");
114
115    println!("Demo complete! {} events captured.", event_count);
116    Ok(())
117}
Source

pub fn new_with_flags(flags: u32) -> WfpResult<Self>

Open a new WFP engine session with custom flags

§Arguments
  • flags - Session flags (e.g., FWPM_SESSION_FLAG_DYNAMIC for automatic cleanup)
§Errors

Returns WfpError::EngineOpenFailed if session creation fails.

Source

pub fn handle(&self) -> HANDLE

Get raw handle to WFP engine session

§Safety

The handle is only valid while this WfpEngine instance is alive. Do not close the handle manually - it will be closed automatically on drop.

Source

pub fn is_valid(&self) -> bool

Check if session is valid

Trait Implementations§

Source§

impl Debug for WfpEngine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for WfpEngine

Source§

fn drop(&mut self)

Automatically close WFP engine session when dropped

Source§

impl Send for WfpEngine

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.