windows_firewall 0.7.0

A crate for managing Windows Firewall rules and settings.
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
use std::convert::TryFrom;
use windows::Win32::NetworkManagement::WindowsFirewall::{INetFwRule, INetFwRules};
use windows::core::BSTR;

use crate::errors::{SetRuleError, WindowsFirewallError};
use crate::firewall_rule::{Direction, FirewallRule, FirewallRuleUpdate};
use crate::utils::{hashset_to_bstr, hashset_to_variant, with_policy};

/// Checks if a firewall rule with the given name exists.
///
/// This function initializes COM, creates a firewall policy object, and checks if a rule
/// with the specified name exists in the Windows Firewall rules list.
///
/// # Arguments
///
/// * `name` - A string slice representing the name of the firewall rule to check.
///
/// # Returns
///
/// This function returns a [`Result<bool, WindowsFirewallError>`](WindowsFirewallError). If the rule exists, it returns `Ok(true)`,
/// otherwise it returns `Ok(false)`. In case of an error (e.g., COM initialization failure or issue
/// with firewall policy), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] in case of failures during COM initialization
/// or while interacting with the firewall policy object.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn rule_exists(name: &str) -> Result<bool, WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(name);
        let exist = unsafe { fw_rules.Item(&rule_name).is_ok() };
        Ok(exist)
    })
}

/// Retrieves the firewall rule with the specified name.
///
/// This function initializes COM, creates a firewall policy object, and attempts to retrieve
/// the firewall rule with the given name. If successful, it returns the rule as a [`FirewallRule`].
///
/// # Arguments
///
/// * `name` - A string slice representing the name of the firewall rule to retrieve.
///
/// # Returns
///
/// This function returns a [`Result<FirewallRule, WindowsFirewallError>`](FirewallRule). If the rule is found and
/// successfully converted, it returns `Ok(rule)`. In case of any error (e.g., COM initialization failure,
/// rule not found, or failure during conversion), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the firewall rule (e.g., rule not found).
/// - Converting the rule into the [`FirewallRule`] struct.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn get_rule(name: &str) -> Result<FirewallRule, WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(name);
        let rule = unsafe { fw_rules.Item(&rule_name) };
        FirewallRule::try_from(rule?)
    })
}

/// Enables or disables an existing firewall rule.
///
/// This function initializes COM, retrieves the firewall policy object,
/// and sets the enabled state of the specified firewall rule.
///
/// # Arguments
///
/// * `rule_name` - A string slice representing the name of the firewall rule to modify.
/// * `enabled` - A boolean indicating whether to enable (`true`) or disable (`false`) the rule.
///
/// # Returns
///
/// This function returns a [`Result<(), WindowsFirewallError>`](WindowsFirewallError). If the rule is updated successfully,
/// it returns `Ok(())`. If an error occurs (e.g., COM initialization failure, rule not found),
/// it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the rule.
/// - Enabling or disabling the rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn enable_rule(rule_name: &str, enabled: bool) -> Result<(), WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(rule_name);
        let rule = unsafe { fw_rules.Item(&rule_name) }?;

        unsafe {
            rule.SetEnabled(enabled.into())
                .map_err(SetRuleError::Enabled)
        }?;

        Ok(())
    })
}

/// Removes the specified firewall rule from the system.
///
/// This function initializes COM, creates a firewall policy object, and removes the firewall rule
/// with the given name from the list of active rules.
///
/// # Arguments
///
/// * `rule_name` - A string slice representing the name of the firewall rule to remove.
///
/// # Returns
///
/// This function returns a [`Result<(), WindowsFirewallError>`](WindowsFirewallError). If the rule is removed successfully,
/// it returns `Ok(())`. In case of an error (e.g., COM initialization failure, rule not found),
/// it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Removing the rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn remove_rule(rule_name: &str) -> Result<(), WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(rule_name);
        unsafe { fw_rules.Remove(&rule_name) }?;

        Ok(())
    })
}

/// Adds a new firewall rule to the system.
///
/// This function initializes COM, creates a firewall policy object, and adds a new rule
/// to the Windows Firewall. The provided rule is converted into an `INetFwRule` object
/// and added to the existing rules list.
///
/// # Arguments
///
/// * `rule` - A [`FirewallRule`] struct representing the firewall rule to add.
///
/// # Returns
///
/// This function returns a [`Result<(), WindowsFirewallError>`](WindowsFirewallError). If the rule is added successfully,
/// it returns `Ok(())`. In case of an error (e.g., COM initialization failure or failure to add rule),
/// it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Adding the firewall rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn add_rule(rule: &FirewallRule) -> Result<(), WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;
        let new_rule: INetFwRule = rule.try_into()?;

        unsafe { fw_rules.Add(&new_rule) }?;

        Ok(())
    })
}

/// Adds a new firewall rule to the system only if a rule with the same name doesn't exist.
///
/// This function first checks if a rule with the given name exists, and if not,
/// adds the new rule to the Windows Firewall.
///
/// # Arguments
///
/// * `rule` - A [`FirewallRule`] struct representing the firewall rule to add.
///
/// # Returns
///
/// This function returns a [`Result<bool, WindowsFirewallError>`](WindowsFirewallError). If the rule is added successfully,
/// it returns `Ok(true)`. If the rule already exists, it returns `Ok(false)`. In case of an error
/// (e.g., COM initialization failure or failure to add rule), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Checking if the rule exists.
/// - Adding the firewall rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn add_rule_if_not_exists(rule: &FirewallRule) -> Result<bool, WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(rule.name());
        let exist = unsafe { fw_rules.Item(&rule_name) }.is_ok();

        if exist {
            return Ok(false);
        }

        let new_rule: INetFwRule = rule.try_into()?;

        unsafe { fw_rules.Add(&new_rule) }?;

        Ok(true)
    })
}

/// Adds a new firewall rule to the system or updates an existing rule with the same name.
///
/// This function first checks if a rule with the given name exists. If it does, the function updates
/// the existing rule with the new settings. If the rule does not exist, it adds a new rule to the
/// Windows Firewall.
///
/// # Arguments
///
/// * `rule` - A [`FirewallRule`] struct representing the firewall rule to add or update.
///
/// # Returns
///
/// This function returns a [`Result<bool, WindowsFirewallError>`](WindowsFirewallError). If the rule is added
/// successfully, it returns `Ok(true)`. If the rule already exists and was updated, it returns `Ok(false)`.
/// In case of an error (e.g., COM initialization failure, failure to add or update the rule), it returns a
/// [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the existing rule or adding the new rule.
/// - Updating the firewall rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn add_rule_or_update(rule: &FirewallRule) -> Result<bool, WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(rule.name());
        let fw_rule_result = unsafe { fw_rules.Item(&rule_name) };

        if let Ok(existing_rule) = fw_rule_result {
            let settings = rule.clone().into();
            update_inetfw_rule(&existing_rule, &settings)?;
            return Ok(false);
        }

        let new_rule: INetFwRule = rule.try_into()?;
        unsafe { fw_rules.Add(&new_rule) }?;

        Ok(true)
    })
}

/// Updates an existing firewall rule with new settings.
///
/// This function initializes COM, creates a firewall policy object, and updates the specified rule
/// with new settings provided in the [`FirewallRuleUpdate`]. The function updates various
/// properties of the rule, such as direction, action, name, and more.
///
/// # Arguments
///
/// * `rule_name` - A string slice representing the name of the firewall rule to update.
/// * `settings` - A [`FirewallRuleUpdate`] struct containing the updated settings for the rule.
///
/// # Returns
///
/// This function returns a [`Result<(), WindowsFirewallError>`](WindowsFirewallError). If the rule is updated successfully,
/// it returns `Ok(())`. In case of an error (e.g., COM initialization failure, rule not found, or failure
/// to update the rule), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the rule.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn update_rule(
    rule_name: &str,
    settings: &FirewallRuleUpdate,
) -> Result<(), WindowsFirewallError> {
    with_policy(|fw_policy| {
        let fw_rules: INetFwRules = unsafe { fw_policy.Rules() }?;

        let rule_name = BSTR::from(rule_name);
        let rule = unsafe { fw_rules.Item(&rule_name) }?;

        update_inetfw_rule(&rule, settings)?;

        Ok(())
    })
}

fn update_inetfw_rule(
    rule: &INetFwRule,
    settings: &FirewallRuleUpdate,
) -> Result<(), WindowsFirewallError> {
    if let Some(name) = &settings.name {
        unsafe { rule.SetName(&BSTR::from(name)).map_err(SetRuleError::Name) }?;
    }
    if let Some(direction) = settings.direction {
        if direction != Direction::In && (unsafe { rule.EdgeTraversal() }?.as_bool()) {
            unsafe {
                rule.SetEdgeTraversal(false.into())
                    .map_err(SetRuleError::EdgeTraversal)
            }?;
        }

        unsafe {
            rule.SetDirection(direction.into())
                .map_err(SetRuleError::Direction)
        }?;
    }
    if let Some(enabled) = settings.enabled {
        unsafe {
            rule.SetEnabled(enabled.into())
                .map_err(SetRuleError::Enabled)
        }?;
    }
    if let Some(action) = settings.action {
        unsafe { rule.SetAction(action.into()).map_err(SetRuleError::Action) }?;
    }
    if let Some(description) = &settings.description {
        unsafe {
            rule.SetDescription(&BSTR::from(description))
                .map_err(SetRuleError::Description)
        }?;
    }
    if let Some(application_name) = &settings.application_name {
        unsafe {
            rule.SetApplicationName(&BSTR::from(application_name))
                .map_err(SetRuleError::ApplicationName)
        }?;
    }
    if let Some(service_name) = &settings.service_name {
        unsafe {
            rule.SetServiceName(&BSTR::from(service_name))
                .map_err(SetRuleError::ServiceName)
        }?;
    }
    if let Some(protocol) = settings.protocol {
        if !protocol.is_tcp_or_udp() {
            let _ = unsafe { rule.SetLocalPorts(&BSTR::from("")) };
            let _ = unsafe { rule.SetRemotePorts(&BSTR::from("")) };
        }
        if !protocol.is_icmp() {
            let _ = unsafe { rule.SetIcmpTypesAndCodes(&BSTR::from("")) };
        }
        unsafe {
            rule.SetProtocol(protocol.into())
                .map_err(SetRuleError::Protocol)
        }?;
    }
    if let Some(local_ports) = &settings.local_ports {
        unsafe {
            rule.SetLocalPorts(&hashset_to_bstr(Some(local_ports)))
                .map_err(SetRuleError::LocalPorts)
        }?;
    }
    if let Some(remote_ports) = &settings.remote_ports {
        unsafe {
            rule.SetRemotePorts(&hashset_to_bstr(Some(remote_ports)))
                .map_err(SetRuleError::RemotePorts)
        }?;
    }
    if let Some(local_addresses) = &settings.local_addresses {
        unsafe {
            rule.SetLocalAddresses(&hashset_to_bstr(Some(local_addresses)))
                .map_err(SetRuleError::LocalAddresses)
        }?;
    }
    if let Some(remote_addresses) = &settings.remote_addresses {
        unsafe {
            rule.SetRemoteAddresses(&hashset_to_bstr(Some(remote_addresses)))
                .map_err(SetRuleError::RemoteAddresses)
        }?;
    }
    if let Some(icmp_types_and_codes) = &settings.icmp_types_and_codes {
        unsafe {
            rule.SetIcmpTypesAndCodes(&BSTR::from(icmp_types_and_codes))
                .map_err(SetRuleError::IcmpTypesAndCodes)
        }?;
    }
    if let Some(edge_traversal) = settings.edge_traversal {
        unsafe {
            rule.SetEdgeTraversal(edge_traversal.into())
                .map_err(SetRuleError::EdgeTraversal)
        }?;
    }
    if let Some(grouping) = &settings.grouping {
        unsafe {
            rule.SetGrouping(&BSTR::from(grouping))
                .map_err(SetRuleError::Grouping)
        }?;
    }
    if let Some(interfaces) = &settings.interfaces {
        unsafe {
            rule.SetInterfaces(&hashset_to_variant(interfaces)?)
                .map_err(SetRuleError::Interfaces)
        }?;
    }
    if let Some(interface_types) = &settings.interface_types {
        unsafe {
            rule.SetInterfaceTypes(&hashset_to_bstr(Some(interface_types)))
                .map_err(SetRuleError::InterfaceType)
        }?;
    }
    if let Some(profiles) = settings.profiles {
        unsafe {
            rule.SetProfiles(profiles.into())
                .map_err(SetRuleError::Profiles)
        }?;
    }

    Ok(())
}