如何在.NET Standard 2.0中实现支持Linux的防火墙规则(替换NetFwTypeLib)
跨平台防火墙规则实现方案
问题背景
当前使用NetFwTypeLib COM引用编写的防火墙规则添加代码仅支持Windows系统,具体代码如下:
public static bool AddRule(FirewallRule rule){ INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; firewallRule.Description = rule.RuleDescription; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; firewallRule.Enabled = true; firewallRule.ApplicationName = rule.ApplicationPath; firewallRule.RemoteAddresses = "LocalSubnet"; firewallRule.InterfaceTypes = "All"; firewallRule.Name = rule.RuleName; switch (rule.Protocol) { case FirewallRule.ProtocolType.TCP: firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case FirewallRule.ProtocolType.UDP: firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; default: throw new ArgumentOutOfRangeException("rule", "The Protocol property of the firewall rule contains an invalid value!"); } INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule); return true; }
需要替换为可同时兼容Windows和Linux系统的实现方案。
解决方案
方案一:使用跨平台防火墙管理库
可以借助封装了Windows和Linux(iptables/nftables)防火墙操作的.NET跨平台库FirewallManager,无需手动处理平台差异。
- 安装NuGet包
dotnet add package FirewallManager
- 改写规则添加代码
using FirewallManager; public static bool AddRule(FirewallRule rule) { var firewall = Firewall.GetActiveFirewall(); var newRule = new FirewallRuleOptions { Name = rule.RuleName, Description = rule.RuleDescription, Direction = rule.Direction == FirewallRule.Direction.In ? FirewallDirection.Inbound : FirewallDirection.Outbound, Action = FirewallAction.Allow, ApplicationPath = rule.ApplicationPath, RemoteAddresses = "LocalSubnet", Protocol = rule.Protocol switch { FirewallRule.ProtocolType.TCP => FirewallProtocol.Tcp, FirewallRule.ProtocolType.UDP => FirewallProtocol.Udp, _ => throw new ArgumentOutOfRangeException(nameof(rule), "无效的协议类型") }, Enabled = true }; firewall.AddRule(newRule); return true; }
方案二:手动分平台实现
若不想依赖第三方库,可通过.NET的平台检测API,分别实现Windows和Linux的防火墙操作逻辑。
1. 抽象防火墙操作接口
public interface IFirewallService { bool AddRule(FirewallRule rule); }
2. Windows平台实现(复用原有逻辑)
public class WindowsFirewallService : IFirewallService { public bool AddRule(FirewallRule rule) { INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; firewallRule.Description = rule.RuleDescription; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; firewallRule.Enabled = true; firewallRule.ApplicationName = rule.ApplicationPath; firewallRule.RemoteAddresses = "LocalSubnet"; firewallRule.InterfaceTypes = "All"; firewallRule.Name = rule.RuleName; switch (rule.Protocol) { case FirewallRule.ProtocolType.TCP: firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case FirewallRule.ProtocolType.UDP: firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; default: throw new ArgumentOutOfRangeException(nameof(rule), "防火墙规则的协议属性值无效!"); } INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule); return true; } }
3. Linux平台实现(调用系统命令)
Linux下需执行iptables或nftables命令添加规则,注意需要root权限:
public class LinuxFirewallService : IFirewallService { public bool AddRule(FirewallRule rule) { string protocol = rule.Protocol switch { FirewallRule.ProtocolType.TCP => "tcp", FirewallRule.ProtocolType.UDP => "udp", _ => throw new ArgumentOutOfRangeException(nameof(rule), "无效的协议类型") }; // 构造iptables规则命令(若系统使用nftables需调整命令格式) string command = $"iptables -A INPUT -p {protocol} -s 192.168.0.0/16 -j ACCEPT -m comment --comment \"{rule.RuleName}: {rule.RuleDescription}\""; // 若需基于应用路径匹配,可使用进程PID匹配:-m owner --pid-owner $(pidof {Path.GetFileName(rule.ApplicationPath)}) // 注意:pidof可能返回多个PID,需额外处理 ProcessStartInfo psi = new ProcessStartInfo("/bin/bash", $"-c \"{command}\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; using var process = Process.Start(psi); process.WaitForExit(); return process.ExitCode == 0; } }
4. 平台适配工厂
public static class FirewallServiceFactory { public static IFirewallService GetFirewallService() { if (OperatingSystem.IsWindows()) { return new WindowsFirewallService(); } else if (OperatingSystem.IsLinux()) { return new LinuxFirewallService(); } else { throw new PlatformNotSupportedException("当前平台不支持防火墙规则操作"); } } }
5. 使用方式
var firewallService = FirewallServiceFactory.GetFirewallService(); firewallService.AddRule(yourFirewallRule);
注意事项
- Linux环境下操作防火墙必须拥有root权限,运行应用时需确保权限充足。
- Linux不同发行版可能使用
iptables或nftables,需根据目标系统调整命令逻辑。 - Linux防火墙规则通常基于端口或进程匹配,而非Windows式的应用路径匹配,需根据实际需求转换规则逻辑。
内容的提问来源于stack exchange,提问作者Aditya Dalai
相关产品推荐
相关产品推荐

