windows_firewall 0.2.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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
use scopeguard::guard;
use std::convert::TryFrom;
use std::mem::ManuallyDrop;
use tracing::error;
use windows::core::{Interface, BSTR};
use windows::Win32::NetworkManagement::WindowsFirewall::{
    INetFwPolicy2, INetFwRule, INetFwRules, NetFwPolicy2, NET_FW_PROFILE_TYPE2,
};
use windows::Win32::System::Com::CoCreateInstance;
use windows::Win32::System::Ole::IEnumVARIANT;
use windows::Win32::System::Variant::VARIANT;

use crate::constants::DWCLSCONTEXT;
use crate::errors::{SetRuleError, WindowsFirewallError};
use crate::firewall_enums::ProfileFirewallWindows;
use crate::firewall_rule::{WindowsFirewallRule, WindowsFirewallRuleSettings};
use crate::utils::{
    hashset_to_bstr, hashset_to_variant, is_not_icmp, is_not_tcp_or_udp, with_com_initialized,
};
use crate::DirectionFirewallWindows;

/// 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_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;

        let fw_rules: INetFwRules = fw_policy.Rules()?;

        let rule_name = BSTR::from(name);
        let exist = 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 [`WindowsFirewallRule`].
///
/// # Arguments
///
/// * `name` - A string slice representing the name of the firewall rule to retrieve.
///
/// # Returns
///
/// This function returns a [`Result<WindowsFirewallRule, WindowsFirewallError>`](WindowsFirewallRule). 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 [`WindowsFirewallRule`] struct.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn get_rule(name: &str) -> Result<WindowsFirewallRule, WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;

        let fw_rules: INetFwRules = fw_policy.Rules()?;

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

/// 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 [`WindowsFirewallRule`] 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: &WindowsFirewallRule) -> Result<(), WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;
        let new_rule: INetFwRule = rule.try_into()?;

        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 [`WindowsFirewallRule`] 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: &WindowsFirewallRule) -> Result<bool, WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;

        let fw_rules: INetFwRules = fw_policy.Rules()?;

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

        if exist {
            return Ok(false);
        }

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

        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 [`WindowsFirewallRule`] 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_or_update(rule: &WindowsFirewallRule) -> Result<bool, WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;

        let rule_name = BSTR::from(rule.name());
        let fw_rule_result = 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()?;
        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 [`WindowsFirewallRuleSettings`]. 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 [`WindowsFirewallRuleSettings`] 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: &WindowsFirewallRuleSettings,
) -> Result<(), WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;

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

        update_inetfw_rule(&rule, settings)?;

        Ok(())
    })
}

unsafe fn update_inetfw_rule(
    rule: &INetFwRule,
    settings: &WindowsFirewallRuleSettings,
) -> Result<(), WindowsFirewallError> {
    if let Some(name) = &settings.name {
        rule.SetName(&BSTR::from(name))
            .map_err(SetRuleError::Name)?;
    }
    if let Some(direction) = settings.direction {
        rule.SetDirection(direction.into())
            .map_err(SetRuleError::Direction)?;
    }
    if let Some(enabled) = settings.enabled {
        rule.SetEnabled(enabled.into())
            .map_err(SetRuleError::Enabled)?;
    }
    if let Some(action) = settings.action {
        rule.SetAction(action.into())
            .map_err(SetRuleError::Action)?;
    }
    if let Some(description) = &settings.description {
        rule.SetDescription(&BSTR::from(description))
            .map_err(SetRuleError::Description)?;
    }
    if let Some(application_name) = &settings.application_name {
        rule.SetApplicationName(&BSTR::from(application_name))
            .map_err(SetRuleError::ApplicationName)?;
    }
    if let Some(service_name) = &settings.service_name {
        rule.SetServiceName(&BSTR::from(service_name))
            .map_err(SetRuleError::ServiceName)?;
    }
    if let Some(protocol) = settings.protocol {
        if is_not_tcp_or_udp(&protocol) {
            let _ = rule.SetLocalPorts(&BSTR::from(""));
            let _ = rule.SetRemotePorts(&BSTR::from(""));
        }
        if is_not_icmp(&protocol) {
            let _ = rule.SetIcmpTypesAndCodes(&BSTR::from(""));
        }
        rule.SetProtocol(protocol.into())
            .map_err(SetRuleError::Protocol)?;
    }
    if let Some(local_ports) = &settings.local_ports {
        rule.SetLocalPorts(&hashset_to_bstr(Some(local_ports)))
            .map_err(SetRuleError::LocalPorts)?;
    }
    if let Some(remote_ports) = &settings.remote_ports {
        rule.SetRemotePorts(&hashset_to_bstr(Some(remote_ports)))
            .map_err(SetRuleError::RemotePorts)?;
    }
    if let Some(local_addresses) = &settings.local_addresses {
        rule.SetLocalAddresses(&hashset_to_bstr(Some(local_addresses)))
            .map_err(SetRuleError::LocalAddresses)?;
    }
    if let Some(remote_addresses) = &settings.remote_addresses {
        rule.SetRemoteAddresses(&hashset_to_bstr(Some(remote_addresses)))
            .map_err(SetRuleError::RemoteAddresses)?;
    }
    if let Some(icmp_types_and_codes) = &settings.icmp_types_and_codes {
        rule.SetIcmpTypesAndCodes(&BSTR::from(icmp_types_and_codes))
            .map_err(SetRuleError::IcmpTypesAndCodes)?;
    }
    if let Some(edge_traversal) = settings.edge_traversal {
        rule.SetEdgeTraversal(edge_traversal.into())
            .map_err(SetRuleError::EdgeTraversal)?;
    }
    if let Some(grouping) = &settings.grouping {
        rule.SetGrouping(&BSTR::from(grouping))
            .map_err(SetRuleError::Grouping)?;
    }
    if let Some(interfaces) = &settings.interfaces {
        rule.SetInterfaces(&hashset_to_variant(interfaces)?)
            .map_err(SetRuleError::Interfaces)?;
    }
    if let Some(interface_types) = &settings.interface_types {
        rule.SetInterfaceTypes(&hashset_to_bstr(Some(interface_types)))
            .map_err(SetRuleError::InterfaceTypes)?;
    }
    if let Some(profiles) = settings.profiles {
        rule.SetProfiles(profiles.into())
            .map_err(SetRuleError::Profiles)?;
    }

    Ok(())
}

/// 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_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;

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

        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_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;

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

        Ok(())
    })
}

/// Retrieves all the firewall rules as a list of [`WindowsFirewallRule`] objects.
///
/// This function initializes COM, creates a firewall policy object, and enumerates through
/// all the firewall rules, converting them into [`WindowsFirewallRule`] structs and returning
/// them as a vector.
///
/// # Returns
///
/// This function returns a [`Result<Vec<WindowsFirewallRule>, WindowsFirewallError>`](WindowsFirewallRule). If the rules
/// are successfully retrieved, it returns `Ok(rules_list)`. In case of an error (e.g., COM initialization failure),
/// it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the firewall rules.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn list_rules() -> Result<Vec<WindowsFirewallRule>, WindowsFirewallError> {
    let mut rules_list = Vec::new();

    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        let fw_rules: INetFwRules = fw_policy.Rules()?;
        let rules_count = fw_rules.Count()?;

        let enumerator = fw_rules._NewEnum()?.cast::<IEnumVARIANT>()?;

        let mut variants: [VARIANT; 1] = Default::default();
        let mut pceltfetch: u32 = 0;

        for _ in 0..rules_count {
            let fetched = enumerator.Next(&mut variants, &mut pceltfetch);

            if fetched.is_err() {
                error!("Error while fetching rules");
                continue;
            };

            if let Some(variant) = variants.first() {
                let dispatch = variant.Anonymous.Anonymous.Anonymous.pdispVal.clone();

                let _dispatch_cleanup = guard(dispatch.clone(), |mut d| {
                    ManuallyDrop::drop(&mut d);
                });

                if let Some(dispatch) = dispatch.as_ref() {
                    let fw_rule = dispatch.cast::<INetFwRule>()?;

                    rules_list.push(fw_rule.try_into()?);
                }
            }
        }

        Ok(rules_list)
    })
}

/// Retrieves all incoming firewall rules as a list of [`WindowsFirewallRule`] objects.
///
/// This function filters the firewall rules to include only incoming rules.
/// It leverages [`list_rules()`] to get all rules and then applies a filter.
///
/// # Returns
///
/// This function returns a [`Result<Vec<WindowsFirewallRule>, WindowsFirewallError>`](WindowsFirewallRule).
/// If successful, it returns `Ok(incoming_rules)`, otherwise an error is returned.
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if [`list_rules()`] fails.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn list_incoming_rules() -> Result<Vec<WindowsFirewallRule>, WindowsFirewallError> {
    let all_rules = list_rules()?;
    let incoming_rules: Vec<WindowsFirewallRule> = all_rules
        .into_iter()
        .filter(|rule| *rule.direction() == DirectionFirewallWindows::In)
        .collect();

    Ok(incoming_rules)
}

/// Retrieves all outgoing firewall rules as a list of [`WindowsFirewallRule`] objects.
///
/// This function filters the firewall rules to include only outgoing rules.
/// It leverages [`list_rules()`] to get all rules and then applies a filter.
///
/// # Returns
///
/// This function returns a [`Result<Vec<WindowsFirewallRule>, WindowsFirewallError>`] .
/// If successful, it returns `Ok(outgoing_rules)`, otherwise an error is returned.
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if [`list_rules()`] fails.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn list_outgoing_rules() -> Result<Vec<WindowsFirewallRule>, WindowsFirewallError> {
    let all_rules = list_rules()?;
    let outgoing_rules: Vec<WindowsFirewallRule> = all_rules
        .into_iter()
        .filter(|rule| *rule.direction() == DirectionFirewallWindows::Out)
        .collect();

    Ok(outgoing_rules)
}

/// Retrieves the active firewall profile.
///
/// This function initializes COM, creates a firewall policy object, and retrieves the current
/// active firewall profile, returning it as a [`ProfileFirewallWindows`] object.
///
/// # Returns
///
/// This function returns a [`Result<ProfileFirewallWindows, WindowsFirewallError>`](ProfileFirewallWindows). If the active profile
/// is successfully retrieved, it returns [`Ok(profile)`](ProfileFirewallWindows). In case of an error (e.g., COM initialization failure),
/// it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the active profile.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn get_active_profile() -> Result<ProfileFirewallWindows, WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;

        let active_profile = ProfileFirewallWindows::try_from(fw_policy.CurrentProfileTypes()?)?;

        Ok(active_profile)
    })
}

/// Retrieves the current state of the firewall for the specified profile.
///
/// This function initializes COM, creates a firewall policy object, and checks if the firewall
/// is enabled or disabled for the given profile. It returns `true` if the firewall is enabled,
/// and `false` otherwise.
///
/// # Arguments
///
/// * `profile` - A [`ProfileFirewallWindows`] enum value representing the firewall profile
///   (such as public, private, or domain) for which the state should be retrieved.
///
/// # Returns
///
/// This function returns a [`Result<bool, WindowsFirewallError>`](WindowsFirewallError). If the firewall state is successfully
/// retrieved, it returns `Ok(true)` for enabled or `Ok(false)` for disabled. If there is an error (e.g.,
/// COM initialization failure or inability to retrieve the firewall state), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Fetching the firewall state.
///
/// # Security
///
/// This function does not require administrative privileges.
pub fn get_firewall_state(profile: ProfileFirewallWindows) -> Result<bool, WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;

        let enabled = fw_policy
            .get_FirewallEnabled(NET_FW_PROFILE_TYPE2(profile.into()))?
            .as_bool();

        Ok(enabled)
    })
}

/// Sets the firewall state (enabled or disabled) for the specified profile.
///
/// This function initializes COM, creates a firewall policy object, and enables or disables the firewall
/// for the given profile based on the provided state (`true` to enable, `false` to disable).
///
/// # Arguments
///
/// * `profile` - A [`ProfileFirewallWindows`] enum value representing the firewall profile
///   (such as public, private, or domain) for which the state should be set.
/// * `state` - A boolean value indicating the desired firewall state. `true` enables the firewall,
///   while `false` disables it.
///
/// # Returns
///
/// This function returns a [`Result<(), WindowsFirewallError>`](WindowsFirewallError). If the firewall state is successfully
/// set, it returns `Ok(())`. If there is an error (e.g., COM initialization failure or failure to set
/// the firewall state), it returns a [`WindowsFirewallError`].
///
/// # Errors
///
/// This function may return a [`WindowsFirewallError`] if there is a failure during:
/// - COM initialization [`WindowsFirewallError::CoInitializeExFailed`].
/// - Setting the firewall state.
///
/// # Security
///
/// ⚠️ This function requires **administrative privileges**.
pub fn set_firewall_state(
    profile: ProfileFirewallWindows,
    state: bool,
) -> Result<(), WindowsFirewallError> {
    with_com_initialized(|| unsafe {
        let fw_policy: INetFwPolicy2 = CoCreateInstance(&NetFwPolicy2, None, DWCLSCONTEXT)?;
        fw_policy.put_FirewallEnabled(NET_FW_PROFILE_TYPE2(profile.into()), state.into())?;
        Ok(())
    })
}