-
Notifications
You must be signed in to change notification settings - Fork 805
Feature: Firewall app #3383
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BornToBeRoot
wants to merge
22
commits into
main
Choose a base branch
from
feature/firewall-app-base
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feature: Firewall app #3383
Changes from 3 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
ff7024e
Feature: Firewall app
BornToBeRoot c3bccb0
Update Source/NETworkManager.Models/Firewall/FirewallRule.cs
BornToBeRoot 7cf2ffd
Fix XML doc comments for Id/Name properties in FirewallRule.cs
Copilot 0ea864c
Feature: Add translation
BornToBeRoot ff78d29
Feature: Add translation and export
BornToBeRoot 271346e
Merge branch 'main' into feature/firewall-app-base
BornToBeRoot 7058281
Feature: Add network profile to networkinterfaceview
BornToBeRoot 2252908
Docs: #3383
BornToBeRoot e5d3ae4
Merge branch 'main' into feature/firewall-app-base
BornToBeRoot e04039e
Merge branch 'main' into feature/firewall-app-base
BornToBeRoot 77d086b
Chore: Hide firewall settings/profile
BornToBeRoot 0761db4
Chore: Refactor the UI
BornToBeRoot ad07dc6
Feature: UI & Copy data
BornToBeRoot 57a2863
Chore: UI redesign
BornToBeRoot d90969f
Docs: Discovery Protocol
BornToBeRoot 00ed305
Update package.json
BornToBeRoot aacad1a
Update yarn.lock
BornToBeRoot 70b404e
Feature: Enable/Disable/Delete Firewall rule
BornToBeRoot a144800
Feature: Open Hosts File Editor
BornToBeRoot b92a304
Feature: Firewall add / edit firewall rule
BornToBeRoot fa13f29
Chore: Adjust strings
BornToBeRoot 6761e73
Feature: Firewall edit/del + docs
BornToBeRoot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,220 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using SMA = System.Management.Automation; | ||
| using System.Threading.Tasks; | ||
| using log4net; | ||
|
|
||
| namespace NETworkManager.Models.Firewall; | ||
|
|
||
| /// <summary> | ||
| /// Represents a firewall configuration and management class that provides functionalities | ||
| /// for applying and managing firewall rules based on a specified profile. | ||
| /// </summary> | ||
| public class Firewall | ||
| { | ||
| #region Variables | ||
|
|
||
| /// <summary> | ||
| /// The Logger. | ||
| /// </summary> | ||
| private static readonly ILog Log = LogManager.GetLogger(typeof(Firewall)); | ||
|
|
||
| private const string RuleIdentifier = "NETworkManager_"; | ||
|
|
||
| #endregion | ||
|
|
||
| #region Methods | ||
|
|
||
| /// <summary> | ||
| /// Reads all Windows Firewall rules whose display name starts with <see cref="RuleIdentifier"/> | ||
| /// and maps them to <see cref="FirewallRule"/> objects. | ||
| /// </summary> | ||
| /// <returns>A task that resolves to the list of matching firewall rules.</returns> | ||
| public static async Task<List<FirewallRule>> GetRulesAsync() | ||
| { | ||
| return await Task.Run(() => | ||
| { | ||
| var rules = new List<FirewallRule>(); | ||
|
|
||
| using var ps = SMA.PowerShell.Create(); | ||
|
|
||
| ps.AddScript($@" | ||
| Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process | ||
| Import-Module NetSecurity -ErrorAction Stop | ||
| Get-NetFirewallRule -DisplayName '{RuleIdentifier}*' | ForEach-Object {{ | ||
| $rule = $_ | ||
| $portFilter = $rule | Get-NetFirewallPortFilter | ||
| $appFilter = $rule | Get-NetFirewallApplicationFilter | ||
| [PSCustomObject]@{{ | ||
| Id = $rule.ID | ||
| DisplayName = $rule.DisplayName | ||
| Enabled = ($rule.Enabled -eq 'True') | ||
| Description = $rule.Description | ||
| Direction = [string]$rule.Direction | ||
| Action = [string]$rule.Action | ||
| Protocol = $portFilter.Protocol | ||
| LocalPort = ($portFilter.LocalPort -join ',') | ||
| RemotePort = ($portFilter.RemotePort -join ',') | ||
| Profile = [string]$rule.Profile | ||
| InterfaceType = [string]$rule.InterfaceType | ||
| Program = $appFilter.Program | ||
| }} | ||
| }}"); | ||
|
|
||
| var results = ps.Invoke(); | ||
|
|
||
| if (ps.Streams.Error.Count > 0) | ||
| { | ||
| foreach (var error in ps.Streams.Error) | ||
| Log.Warn($"PowerShell error: {error}"); | ||
| } | ||
|
|
||
| foreach (var result in results) | ||
| { | ||
| try | ||
| { | ||
| var rule = new FirewallRule | ||
| { | ||
| Id = result.Properties["Id"]?.Value?.ToString() ?? string.Empty, | ||
| IsEnabled = result.Properties["Enabled"]?.Value as bool? == true, | ||
| Name = result.Properties["DisplayName"]?.Value?.ToString() ?? string.Empty, | ||
| Description = result.Properties["Description"]?.Value?.ToString() ?? string.Empty, | ||
| Direction = ParseDirection(result.Properties["Direction"]?.Value?.ToString()), | ||
| Action = ParseAction(result.Properties["Action"]?.Value?.ToString()), | ||
| Protocol = ParseProtocol(result.Properties["Protocol"]?.Value?.ToString()), | ||
| LocalPorts = ParsePorts(result.Properties["LocalPort"]?.Value?.ToString()), | ||
| RemotePorts = ParsePorts(result.Properties["RemotePort"]?.Value?.ToString()), | ||
| NetworkProfiles = ParseProfile(result.Properties["Profile"]?.Value?.ToString()), | ||
| InterfaceType = ParseInterfaceType(result.Properties["InterfaceType"]?.Value?.ToString()), | ||
| }; | ||
|
|
||
| var program = result.Properties["Program"]?.Value as string; | ||
|
|
||
| if (!string.IsNullOrWhiteSpace(program) && !program.Equals("Any", StringComparison.OrdinalIgnoreCase)) | ||
| rule.Program = new FirewallRuleProgram(program); | ||
|
|
||
| rules.Add(rule); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Log.Warn($"Failed to parse firewall rule: {ex.Message}"); | ||
| } | ||
| } | ||
|
|
||
| return rules; | ||
| }); | ||
| } | ||
|
|
||
| /// <summary>Parses a PowerShell direction string to <see cref="FirewallRuleDirection"/>.</summary> | ||
| private static FirewallRuleDirection ParseDirection(string value) | ||
| { | ||
| return value switch | ||
| { | ||
| "Outbound" => FirewallRuleDirection.Outbound, | ||
| _ => FirewallRuleDirection.Inbound, | ||
| }; | ||
| } | ||
|
|
||
| /// <summary>Parses a PowerShell action string to <see cref="FirewallRuleAction"/>.</summary> | ||
| private static FirewallRuleAction ParseAction(string value) | ||
| { | ||
| return value switch | ||
| { | ||
| "Allow" => FirewallRuleAction.Allow, | ||
| _ => FirewallRuleAction.Block, | ||
| }; | ||
| } | ||
|
|
||
| /// <summary>Parses a PowerShell protocol string to <see cref="FirewallProtocol"/>.</summary> | ||
| private static FirewallProtocol ParseProtocol(string value) | ||
| { | ||
| if (string.IsNullOrWhiteSpace(value) || value.Equals("Any", StringComparison.OrdinalIgnoreCase)) | ||
| return FirewallProtocol.Any; | ||
|
|
||
| return value.ToUpperInvariant() switch | ||
| { | ||
| "TCP" => FirewallProtocol.TCP, | ||
| "UDP" => FirewallProtocol.UDP, | ||
| "ICMPV4" => FirewallProtocol.ICMPv4, | ||
| "ICMPV6" => FirewallProtocol.ICMPv6, | ||
| "GRE" => FirewallProtocol.GRE, | ||
| "L2TP" => FirewallProtocol.L2TP, | ||
| _ => int.TryParse(value, out var proto) ? (FirewallProtocol)proto : FirewallProtocol.Any, | ||
| }; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Parses a comma-separated port string (e.g. <c>"80,443,8080-8090"</c>) to a list of | ||
| /// <see cref="FirewallPortSpecification"/> objects. Returns an empty list for <c>Any</c> or blank input. | ||
| /// </summary> | ||
| private static List<FirewallPortSpecification> ParsePorts(string value) | ||
| { | ||
| var list = new List<FirewallPortSpecification>(); | ||
|
|
||
| if (string.IsNullOrWhiteSpace(value) || value.Equals("Any", StringComparison.OrdinalIgnoreCase)) | ||
| return list; | ||
|
|
||
| foreach (var token in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) | ||
| { | ||
| var dashIndex = token.IndexOf('-'); | ||
|
|
||
| if (dashIndex > 0 && | ||
| int.TryParse(token[..dashIndex], out var start) && | ||
| int.TryParse(token[(dashIndex + 1)..], out var end)) | ||
| { | ||
| list.Add(new FirewallPortSpecification(start, end)); | ||
| } | ||
| else if (int.TryParse(token, out var port)) | ||
| { | ||
| list.Add(new FirewallPortSpecification(port)); | ||
| } | ||
| } | ||
|
|
||
| return list; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Parses a PowerShell profile string (e.g. <c>"Domain, Private"</c>) to a three-element boolean array | ||
| /// in the order Domain, Private, Public. | ||
| /// </summary> | ||
| private static bool[] ParseProfile(string value) | ||
| { | ||
| var profiles = new bool[3]; | ||
|
|
||
| if (string.IsNullOrWhiteSpace(value)) | ||
| return profiles; | ||
|
|
||
| if (value.Equals("Any", StringComparison.OrdinalIgnoreCase) || | ||
| value.Equals("All", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| profiles[0] = profiles[1] = profiles[2] = true; | ||
| return profiles; | ||
| } | ||
|
|
||
| foreach (var token in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) | ||
| { | ||
| switch (token) | ||
| { | ||
| case "Domain": profiles[0] = true; break; | ||
| case "Private": profiles[1] = true; break; | ||
| case "Public": profiles[2] = true; break; | ||
| } | ||
| } | ||
|
|
||
| return profiles; | ||
| } | ||
|
|
||
| /// <summary>Parses a PowerShell interface-type string to <see cref="FirewallInterfaceType"/>.</summary> | ||
| private static FirewallInterfaceType ParseInterfaceType(string value) | ||
| { | ||
| return value switch | ||
| { | ||
| "Wired" => FirewallInterfaceType.Wired, | ||
| "Wireless" => FirewallInterfaceType.Wireless, | ||
| "RemoteAccess" => FirewallInterfaceType.RemoteAccess, | ||
| _ => FirewallInterfaceType.Any, | ||
| }; | ||
| } | ||
| #endregion | ||
| } | ||
27 changes: 27 additions & 0 deletions
27
Source/NETworkManager.Models/Firewall/FirewallInterfaceType.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| namespace NETworkManager.Models.Firewall; | ||
|
|
||
| /// <summary> | ||
| /// Defines the types of network interfaces that can be used in firewall rules. | ||
| /// </summary> | ||
| public enum FirewallInterfaceType | ||
| { | ||
| /// <summary> | ||
| /// Any interface type. | ||
| /// </summary> | ||
| Any = -1, | ||
|
|
||
| /// <summary> | ||
| /// Wired interface types, e.g. Ethernet. | ||
| /// </summary> | ||
| Wired, | ||
|
|
||
| /// <summary> | ||
| /// Wireless interface types, e.g. Wi-Fi. | ||
| /// </summary> | ||
| Wireless, | ||
|
|
||
| /// <summary> | ||
| /// Remote interface types, e.g. VPN, L2TP, OpenVPN, etc. | ||
| /// </summary> | ||
| RemoteAccess | ||
| } |
17 changes: 17 additions & 0 deletions
17
Source/NETworkManager.Models/Firewall/FirewallPortLocation.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| namespace NETworkManager.Models.Firewall; | ||
|
|
||
| /// <summary> | ||
| /// Ports of local host or remote host. | ||
| /// </summary> | ||
| public enum FirewallPortLocation | ||
| { | ||
| /// <summary> | ||
| /// Ports of local host. | ||
| /// </summary> | ||
| LocalPorts, | ||
|
|
||
| /// <summary> | ||
| /// Ports of remote host. | ||
| /// </summary> | ||
| RemotePorts | ||
| } |
66 changes: 66 additions & 0 deletions
66
Source/NETworkManager.Models/Firewall/FirewallPortSpecification.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| // ReSharper disable MemberCanBePrivate.Global | ||
| // Needed for serialization. | ||
| namespace NETworkManager.Models.Firewall; | ||
|
|
||
| /// <summary> | ||
| /// Represents a specification for defining and validating firewall ports. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This class is used to encapsulate rules and configurations for | ||
| /// managing firewall port restrictions or allowances. It provides | ||
| /// properties and methods to define a range of acceptable ports or | ||
| /// individual port specifications. | ||
| /// </remarks> | ||
| public class FirewallPortSpecification | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the start point or initial value of a process, range, or operation. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The <c>Start</c> property typically represents the beginning state or position for sequential | ||
| /// processing or iteration. The exact usage of this property may vary depending on the context of | ||
| /// the class or object it belongs to. | ||
| /// </remarks> | ||
| public int Start { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the endpoint or final state of a process, range, or operation. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This property typically represents the termination position, time, or value | ||
| /// in a sequence, operation, or any bounded context. Its specific meaning may vary | ||
| /// depending on the context in which it is used. | ||
| /// </remarks> | ||
| public int End { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// For serializing. | ||
| /// </summary> | ||
| public FirewallPortSpecification() | ||
| { | ||
| Start = -1; | ||
| End = -1; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Represents the specification for a firewall port, detailing its configuration | ||
| /// and rules for inbound or outbound network traffic. | ||
| /// </summary> | ||
| public FirewallPortSpecification(int start, int end = -1) | ||
| { | ||
| Start = start; | ||
| End = end; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Returns a string that represents the current object. | ||
| /// </summary> | ||
| /// <returns>A string that represents the current instance of the object.</returns> | ||
| public override string ToString() | ||
| { | ||
| if (Start is 0) | ||
| return string.Empty; | ||
|
|
||
| return End is -1 or 0 ? $"{Start}" : $"{Start}-{End}"; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In
GetRulesAsync, the PowerShell script capturesId = $rule.ID, butEnable/Disable/Remove-NetFirewallRule -Nameexpects the rule’s internal Name (GUID) fromGet-NetFirewallRule.Get-NetFirewallRuleexposesName/DisplayName—IDis typically not present—sorule.Idmay end up empty and all subsequent enable/disable/delete operations will fail. Capture$rule.Name(or whatever property you later pass to-Name) and keepFirewallRule.Idaligned with that identifier.