private CreateFirewallRuleDto CreateFirewallRule() { var createFirewallRule = new CreateFirewallRuleDto { Direction = (cboxDirection.SelectedItem as DirectionItem).Direction, Ips = lboxIpAddresses.Items.OfType <IPModel>() .Select(m => new IpDto { From = m.From, IpOrSubnet = m.IpOrSubnet, SubnetMask = m.SubnetMask, To = m.To }) .ToArray(), Name = tboxRuleName.Text, Ports = tboxPorts.Text ?? "", Profile = (cboxProfile.SelectedItem as ProfileItem).Profile, ProgramPath = tboxProgramPath.Text ?? "", CreateRuleEnabled = cboxCreateEnabled.Checked }; if (cboxProtocol.SelectedItem is ProtocolItem item) { createFirewallRule.Protocol = item.Protocol; } return(createFirewallRule); }
public FirewallRuleDto CreateFirewallRule(CreateFirewallRuleDto rule) { var(parseOk, ips, proto, ports) = ParseRuleData(rule); if (parseOk) { if (Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")) is INetFwRule3 fwRule) { fwRule.Name = rule.Name; fwRule.Enabled = rule.CreateRuleEnabled; fwRule.InterfaceTypes = "All"; fwRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; fwRule.Direction = (NET_FW_RULE_DIRECTION_)rule.Direction; fwRule.Profiles = (int)rule.Profile; if (!string.IsNullOrEmpty(ips)) { fwRule.RemoteAddresses = ips; } if (proto != null) { fwRule.Protocol = proto.Value; fwRule.RemotePorts = ports; } if (!string.IsNullOrEmpty(rule.ProgramPath)) { fwRule.ApplicationName = rule.ProgramPath; } firewallPolicy.Rules.Add(fwRule); var firewallRuleDto = new FirewallRuleDto { FwRule = fwRule, Profile = rule.Profile, Direction = rule.Direction, Name = rule.Name, ProgramPath = rule.ProgramPath }; UpdateRulesGroup(rule.Profile, rule.Direction, firewallRuleDto); return(firewallRuleDto); } } return(null); }
private (bool, string, int?, string) ParseRuleData(CreateFirewallRuleDto rule) { (bool, string, int?, string)invalid = (false, null, null, null); if (rule == null) { return(invalid); } if (string.IsNullOrEmpty(rule.Name)) { return(invalid); } if (string.IsNullOrEmpty(rule.ProgramPath) && rule.Ips?.Length == 0 && rule.Protocol == null && string.IsNullOrEmpty(rule.Ports)) { return(invalid); } var proto = rule.Protocol == null ? null : (int?)rule.Protocol; var(portsOk, ports) = ParsePorts(rule.Ports); var(ipsOk, ips) = ParseIps(rule.Ips); if (proto is null) { portsOk = true; ports = null; } return(ipsOk && portsOk ? (true, ips, proto, ports) : invalid); }