public FwErrorCode IsPortEnabled(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, ref bool bEnable) { if (_mFirewallProfile == null) { return(FwErrorCode.FwErrInitialized); } // Retrieve the open ports collection INetFwOpenPorts fwOpenPorts = _mFirewallProfile.GloballyOpenPorts; if (fwOpenPorts == null) { return(FwErrorCode.FwErrGlobalOpenPorts); } // Get the open port try { INetFwOpenPort fwOpenPort = fwOpenPorts.Item(nPortNumber, ipProtocol); bEnable = fwOpenPort?.Enabled == true; } catch (System.IO.FileNotFoundException) { bEnable = false; } return(FwErrorCode.FwNoerror); }
public bool IsPortEnabled(int port, NET_FW_IP_PROTOCOL_ ipProtocol) { DoDisposeCheck(); DoInitializationCheck(); bool result = false; // Retrieve the open ports collection INetFwOpenPorts firewallOpenPorts = mFirewallProfile.GloballyOpenPorts; if (firewallOpenPorts == null) { throw new FirewallException("Failed to get globally open ports."); } // Get the open port try { INetFwOpenPort firewallOpenPort = firewallOpenPorts.Item(port, ipProtocol); if (firewallOpenPort != null) { result = firewallOpenPort.Enabled; } } catch (Exception) { } return(result); }
// example: AddPort(true, "TCP Port", Int32.Parse(port.Text), NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP); public static bool AddPort(bool enabled, string name, int port, NET_FW_IP_PROTOCOL_ protocol) { // Add the port to the ICF Permissions List INetFwMgr mgr = null; try { mgr = (NetFwTypeLib.INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); } catch { // XPSP2 not installed return false; } try { INetFwProfile profile; INetFwOpenPort portClass = (NetFwTypeLib.INetFwOpenPort)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWOpenPort")); // Get the current profile profile = mgr.LocalPolicy.CurrentProfile; // Set the port properties portClass.Enabled = enabled; portClass.Name = name; portClass.Port = port; portClass.Protocol = protocol; // Add the port to the ICF Permissions List profile.GloballyOpenPorts.Add(portClass); return true; } catch { // Log the error or prompt the user return false; } }
public FW_ERROR_CODE IsPortEnabled(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, ref bool bEnable) { if (m_FirewallProfile == null) { return(FW_ERROR_CODE.FW_ERR_INITIALIZED); } // Retrieve the open ports collection INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) { return(FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS); } // Get the open port try { INetFwOpenPort FWOpenPort = FWOpenPorts.Item(nPortNumber, ipProtocol); if (FWOpenPort != null) { bEnable = FWOpenPort.Enabled; } else { bEnable = false; } } catch (FileNotFoundException) { bEnable = false; } return(FW_ERROR_CODE.FW_NOERROR); }
/// <summary> /// 添加防火墙例外端口 /// </summary> /// <param name="name">名称</param> /// <param name="port">端口</param> /// <param name="protocol">协议(TCP、UDP)</param> public static void NetFwAddPorts(string name, int port, NET_FW_IP_PROTOCOL_ protocol) { var serviceControllers = ServiceController.GetServices(); string fireWallServiceName; Version currentVersion = Environment.OSVersion.Version; if (currentVersion.Major == 5) { fireWallServiceName = "sharedaccess"; } else { fireWallServiceName = "mpssvc"; } var server = serviceControllers.FirstOrDefault(service => service.ServiceName.ToLower() == fireWallServiceName); if (server != null && server.Status == ServiceControllerStatus.Running) { //创建firewall管理类的实例 INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); INetFwOpenPort objPort = (INetFwOpenPort)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwOpenPort")); objPort.Name = name; objPort.Port = port; objPort.Protocol = protocol; objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; objPort.Enabled = true; //加入到防火墙的管理策略,若已存在会启用该规则 netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort); } }
public static void CreateRuleAllow(string ruleName, string ip, int port, NET_FW_IP_PROTOCOL_ protocol) { RemoveRule(ruleName); try { INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); inboundRule.Name = ruleName; inboundRule.Description = $"Allow inbound traffic from users over port {port}"; inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; inboundRule.Profiles = (int)NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL; inboundRule.Protocol = (int)protocol; //inboundRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; //inboundRule.Grouping = "@firewallapi.dll,-23255"; inboundRule.RemoteAddresses = ip; inboundRule.LocalPorts = port.ToString(); inboundRule.Enabled = true; firewallPolicy.Rules.Add(inboundRule); Logger.White($" [Firewall] Allow {(protocol == NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP ? "Tcp" : protocol == NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP ? "Udp" : "Unknown")} connection rule on port {port} has been registered in windows firewall."); firewallPolicy = null; inboundRule = null; } catch (Exception ex) { Logger.Exception(ex); } }
public bool RemovePort(int port, NET_FW_IP_PROTOCOL_ ipProtocol) { DoDisposeCheck(); DoInitializationCheck(); bool changed = false; if (IsPortEnabled(port, ipProtocol)) { // Retrieve the collection of globally open ports INetFwOpenPorts firewallOpenPorts = mFirewallProfile.GloballyOpenPorts; if (firewallOpenPorts == null) { throw new FirewallException("Failed to get globally open ports."); } try { firewallOpenPorts.Remove(port, ipProtocol); changed = true; } catch (Exception ex) { throw new FirewallException("Failed to remove port.", ex); } } return(changed); }
public static void AddFirewallRule(NET_FW_IP_PROTOCOL_ protocol, string remoteAddress, string port, string processPath) { if (!IsUserAdmin()) { MessageBox.Show("You need to run the application as administrator to use this feature.", "Admin rights required", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } INetFwPolicy2 fwPolicy2 = GetFwPolicy2(); var currentProfiles = fwPolicy2.CurrentProfileTypes; // New rule. INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); inboundRule.Enabled = true; inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; inboundRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; inboundRule.Protocol = (int)protocol; inboundRule.LocalPorts = port; inboundRule.RemoteAddresses = remoteAddress; inboundRule.ApplicationName = processPath; inboundRule.Name = RuleName; inboundRule.Profiles = currentProfiles; // Adding rule. fwPolicy2.Rules.Add(inboundRule); }
// example: RemovePort(Int32.Parse(port.Text), NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP); public static bool RemovePort(int port, NET_FW_IP_PROTOCOL_ protocol) { // Remove the port to the ICF Permissions List INetFwMgr mgr = null; try { mgr = (NetFwTypeLib.INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); } catch { // XPSP2 not installed return(false); } try { INetFwProfile profile; // Get the current profile profile = mgr.LocalPolicy.CurrentProfile; // Remove the port to the ICF Permissions List profile.GloballyOpenPorts.Remove(port, protocol); return(true); } catch { // Log the error or prompt the user return(false); } }
/// <summary> /// Creates a new port entry in the firewall collection. /// </summary> /// <param name="port">The port number.</param> /// <param name="name">The name of the port.</param> /// <param name="protocol">The protocol used.</param> /// <param name="scope">The scope of the control.</param> public void OpenFirewallPort(int port, string name, NET_FW_IP_PROTOCOL_ protocol, NET_FW_SCOPE_ scope) { // Set the current access profile. SetProfile(); // Get the current globall // open port profile control. INetFwOpenPorts openPorts = fwProfile.GloballyOpenPorts; // Create a new instance of the // open new port type. INetFwOpenPort openPort = (INetFwOpenPort)GetInstance("INetOpenPort"); // Assign the port specifications. openPort.Port = port; openPort.Name = name; openPort.Scope = scope; openPort.Protocol = protocol; // Add the new port to the // collection of ports. openPorts.Add(openPort); openPorts = null; }
public PortInfo(int portNumber) { imageFileName = null; ipVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4; this.portNumber = portNumber; localAddress = null; ipProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; }
public FW_ERROR_CODE AddPort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, string strRegisterName) { if (m_FirewallProfile == null) { return(FW_ERROR_CODE.FW_ERR_INITIALIZED); } bool bEnablePort = true; FW_ERROR_CODE nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FW_ERROR_CODE.FW_NOERROR) { return(nError); } // Only add the port, if it isn't added to the collection if (bEnablePort == false) { // Retrieve the collection of globally open ports INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) { return(FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS); } // Create an instance of an open port Type typeFwPort = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); var FWOpenPort = (INetFwOpenPort)Activator.CreateInstance(typeFwPort); if (FWOpenPort == null) { return(FW_ERROR_CODE.FW_ERR_CREATE_PORT_INSTANCE); } // Set the port number FWOpenPort.Port = nPortNumber; // Set the IP Protocol FWOpenPort.Protocol = ipProtocol; // Set the registered name FWOpenPort.Name = strRegisterName; try { FWOpenPorts.Add(FWOpenPort); } catch { return(FW_ERROR_CODE.FW_ERR_ADD_TO_COLLECTION); } } else { return(FW_ERROR_CODE.FW_ERR_SAME_PORT_EXIST); } return(FW_ERROR_CODE.FW_NOERROR); }
public TestFirewallRule(string name, string ports, NET_FW_IP_PROTOCOL_ protocol, NET_FW_RULE_DIRECTION_ direction, string appPath, string grouping) { this.Name = name; this.Ports = ports; this.Protocol = protocol; this.Direction = direction; this.ApplicationPath = appPath; this.Grouping = grouping; }
private bool _IsPortOpen(INetFwProfile profile) { NET_FW_IP_PROTOCOL_ protocol = _GetProtocol(); if (!profile.FirewallEnabled) { return(true); } return(profile.GloballyOpenPorts.Cast <INetFwOpenPort>().Any(p => p.Protocol == protocol && p.Port == _Port)); }
public static void RemovePortExceptionFromSP2Firewall(int port, NET_FW_IP_PROTOCOL_ protocol) { // Instantiating the HNetCfg.NetFwMgr object to get "LocalPolicy" and then "CurrentProfile" INetFwMgr fwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(INetFwMgrGuid)), true); INetFwPolicy fwPolicy = fwMgr.LocalPolicy; INetFwProfile fwProfile = fwPolicy.CurrentProfile; // Remove application from exception rule list fwProfile.GloballyOpenPorts.Remove(port, protocol); }
public static ProtocolPort Convert(NET_FW_IP_PROTOCOL_ item) { switch (item) { case NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP: return(ProtocolPort.Tcp); case NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP: return(ProtocolPort.Udp); default: return(ProtocolPort.Any); } }
private INetFwOpenPort GetPortObj(string portNumber, NET_FW_IP_PROTOCOL_ ipProtocol) { Type tpResult = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); INetFwOpenPort port = (INetFwOpenPort)Activator.CreateInstance(tpResult); port.Port = Int32.Parse(portNumber); // port number port.Name = appName; // name of the application using the port port.Enabled = true; // enable the port port.Protocol = ipProtocol; return(port); }
public FwErrorCode AddPort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, string strRegisterName) { if (_mFirewallProfile == null) { return(FwErrorCode.FwErrInitialized); } bool bEnablePort = true; FwErrorCode nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FwErrorCode.FwNoerror) { return(nError); } // Only add the port, if it isn't added to the collection if (bEnablePort == false) { // Retrieve the collection of globally open ports INetFwOpenPorts fwOpenPorts = _mFirewallProfile.GloballyOpenPorts; if (fwOpenPorts == null) { return(FwErrorCode.FwErrGlobalOpenPorts); } // Create an instance of an open port Type typeFwPort = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); var fwOpenPort = (INetFwOpenPort)Activator.CreateInstance(typeFwPort); // Set the port number fwOpenPort.Port = nPortNumber; // Set the IP Protocol fwOpenPort.Protocol = ipProtocol; // Set the registered name fwOpenPort.Name = strRegisterName; try { fwOpenPorts.Add(fwOpenPort); } catch { return(FwErrorCode.FwErrAddToCollection); } } else { return(FwErrorCode.FwErrSamePortExist); } return(FwErrorCode.FwNoerror); }
private void OpenPort(string name, int port, NET_FW_IP_PROTOCOL_ protocol, NET_FW_SCOPE_ scope) { if (openPorts.OfType <INetFwOpenPort>().Where(x => x.Name == name).Count() == 0) { INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwOpenPort")); openPort.Port = port; openPort.Protocol = protocol; openPort.Scope = scope; openPort.Name = name; openPorts.Add(openPort); } }
/// <summary> /// Removes the port entry from the firewall collection. /// </summary> /// <param name="port">The port number.</param> /// <param name="protocol">The protocol used.</param> public void CloseFirewallPort(int port, NET_FW_IP_PROTOCOL_ protocol) { // Set the current access profile. SetProfile(); // Get the current globall // open port profile control. INetFwOpenPorts openPorts = fwProfile.GloballyOpenPorts; // Remove the specified port from the collection. openPorts.Remove(port, protocol); openPorts = null; }
public bool AddPort(int port, NET_FW_IP_PROTOCOL_ ipProtocol, string registeredName) { DoDisposeCheck(); DoInitializationCheck(); if (string.IsNullOrEmpty(registeredName)) { ThrowHelper.ThrowArgumentNullException("registeredName"); } bool result = false; if (!IsPortEnabled(port, ipProtocol)) { // Retrieve the collection of globally open ports INetFwOpenPorts firewallOpenPorts = mFirewallProfile.GloballyOpenPorts; if (firewallOpenPorts == null) { throw new FirewallException("Failed to get globally open ports."); } // Create an instance of an open port Type firewallPortType = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); INetFwOpenPort firewallOpenPort = (INetFwOpenPort)Activator.CreateInstance(firewallPortType); if (firewallOpenPort == null) { throw new FirewallException("Failed to create port instance."); } // Set the port number firewallOpenPort.Port = port; // Set the IP Protocol firewallOpenPort.Protocol = ipProtocol; // Set the registered name firewallOpenPort.Name = registeredName; try { firewallOpenPorts.Add(firewallOpenPort); result = true; } catch (Exception ex) { throw new FirewallException("Failed to add port.", ex); } } return(result); }
public static void AddPortExceptionToSP2Firewall(string name, int port, NET_FW_IP_PROTOCOL_ protocol) { // Instantiating the HNetCfg.NetFwMgr object to get "LocalPolicy" and then "CurrentProfile" INetFwMgr fwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(INetFwMgrGuid)), true); INetFwPolicy fwPolicy = fwMgr.LocalPolicy; INetFwProfile fwProfile = fwPolicy.CurrentProfile; INetFwOpenPort fwOpenPort = (INetFwOpenPort)Activator.CreateInstance( Type.GetTypeFromCLSID(new Guid(INetFwOpenPortGuid)), true); fwOpenPort.Name = name; fwOpenPort.Port = port; fwOpenPort.Protocol = protocol; fwOpenPort.Enabled = true; fwProfile.GloballyOpenPorts.Add(fwOpenPort); }
private void CreateRuleOut(String RuleName, String Desc, NET_FW_IP_PROTOCOL_ Protocol, String RemotePorts, NET_FW_RULE_DIRECTION_ Direction, INetFwPolicy2 fwPolicy2) { Type typeFWRule = Type.GetTypeFromProgID("HNetCfg.FwRule", false); INetFwRule newRule = (INetFwRule)Activator.CreateInstance(typeFWRule); newRule.Name = RuleName; newRule.Description = Desc; newRule.Protocol = (int)Protocol; newRule.RemotePorts = RemotePorts; newRule.RemoteAddresses = txtRemoteAddress.Text.Replace(" ", "").Replace("\r\n", ","); newRule.Direction = Direction; newRule.Enabled = true; newRule.Grouping = "Elasticsearch"; //newRule.Profiles = fwPolicy2.CurrentProfileTypes; newRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; fwPolicy2.Rules.Add(newRule); }
/// <summary> /// Authorizes a program to receive incoming communications through Windows Firewall. If this fails (typically due to insufficient permission), the exception is returned. /// </summary> /// <param name="title">The title of the firewall rule/program.</param> /// <param name="path">Path to the executable that should be authorized.</param> /// <param name="remoteAddresses">Comma separated list of remote addresses to authorize, or "*" for all.</param> /// <param name="protocol">Internet protocol version.</param> /// <param name="networkProfiles">Internet protocol version.</param> /// <returns></returns> public static Exception AuthorizeProgram(string title , string path , string remoteAddresses = "*" , NET_FW_IP_PROTOCOL_ protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY , NET_FW_PROFILE_TYPE2_ networkProfiles = NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN | NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE) { try { INetFwPolicy2 fwPolicy2 = Create <INetFwPolicy2>("HNetCfg.FwPolicy2"); foreach (INetFwRule existingRule in fwPolicy2.Rules) { if (path.Equals(existingRule.ApplicationName, StringComparison.OrdinalIgnoreCase)) { if (existingRule.Protocol == (int)protocol && existingRule.Profiles == (int)networkProfiles && existingRule.Action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW && existingRule.Enabled) { if (existingRule.RemoteAddresses != remoteAddresses) { existingRule.RemoteAddresses = remoteAddresses; } return(null); } } } INetFwRule rule = Create <INetFwRule>("HNetCfg.FwRule"); rule.Name = title; rule.Description = "Allow incoming traffic to " + title; rule.ApplicationName = path; rule.Protocol = (int)protocol; rule.Enabled = true; rule.Grouping = title; rule.RemoteAddresses = remoteAddresses; rule.Profiles = (int)networkProfiles; rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; fwPolicy2.Rules.Add(rule); } catch (Exception ex) { return(ex); } return(null); }
public bool RemovePort(int portNo, bool isUDP) { bool result = false; INetFwMgr manager = _GetFirewallManager(); NET_FW_IP_PROTOCOL_ protocol = isUDP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; try { manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Remove(portNo, protocol); result = true; } catch (Exception ex) { Logger.error(ex.ToString()); } return(result); }
private FirewallRule GetDynamicPortRangeExceptionRule(string direction, string protocol, NET_FW_PROFILE_TYPE2_ fwProfile) { string ruleName = string.Format( CultureInfo.InvariantCulture, FabricNodeFirewallRules.DynamicPortRangeExceptionTemplate, this.NodeName, protocol, GetProfileFriendlyName(fwProfile), direction); NET_FW_IP_PROTOCOL_ fwProtocol = protocol == FabricNodeFirewallRules.ProtocolTcp ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; NET_FW_RULE_DIRECTION_ fwDirection = direction == FabricNodeFirewallRules.inDirection ? NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN : NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; return(GetRule(ruleName, null, this.DynamicPorts, fwProtocol, fwDirection, fwProfile)); }
public static void EnableInboundPort(NET_FW_IP_PROTOCOL_ protocol, int port, string description) { try { INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; firewallRule.Name = description; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; firewallRule.Protocol = (int)protocol; firewallRule.LocalPorts = port.ToString(); firewallRule.Enabled = true; firewallRule.InterfaceTypes = "All"; INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule); } catch (Exception) { } }
/// <summary> /// Open port in network windows firewall /// </summary> /// <param name="name"></param> /// <param name="portNo"></param> /// <param name="scope"></param> /// <param name="protocol"></param> /// <param name="ipVersion"></param> /// <returns></returns> public static bool GloballyOpenPort(string name, int portNo, NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol, NET_FW_IP_VERSION_ ipVersion) { INetFwMgr manager = GetFirewallManager(); try { // Check if port does not exists. bool exists = false; foreach (INetFwOpenPort openPort in manager.LocalPolicy.CurrentProfile.GloballyOpenPorts) { if (openPort.Name == name && openPort.Port == portNo) { exists = true; break; } } if (!exists) { // Create the type from prog id Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT); // Create instance that provides access to the properties of a port that has been opened in the firewall. INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort; // Set properties for port port.Name = name; port.Port = portNo; port.Scope = scope; port.Protocol = protocol; port.IpVersion = ipVersion; // Add open port to windows firewall manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port); } } catch (Exception ex) { return(false); } return(true); }
// WINDOWS防火墙添加例外端口,name端口名,portNum端口号,type端口类型 public static bool addFirewallPort(string name, int portNum, NET_FW_IP_PROTOCOL_ type) { try { // 创建端口接口实例 INetFwOpenPort port = createInstance <INetFwOpenPort>(Type.GetTypeFromProgID("HNetCfg.FwOpenPort")); port.Name = name; //端口名 port.Port = portNum; //端口号 port.Protocol = type; //协议类型 port.Enabled = true; //启用 // 创建firewall管理接口的实例 INetFwMgr netFwMgr = createInstance <INetFwMgr>(Type.GetTypeFromProgID("HNetCfg.FwMgr")); netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port); return(true); } catch { return(false); } }
// example: AddPort(true, "TCP Port", Int32.Parse(port.Text), NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP); public static bool AddPort(bool enabled, string name, int port, NET_FW_IP_PROTOCOL_ protocol) { // Add the port to the ICF Permissions List INetFwMgr mgr = null; try { mgr = (NetFwTypeLib.INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); } catch { // XPSP2 not installed return(false); } try { INetFwProfile profile; INetFwOpenPort portClass = (NetFwTypeLib.INetFwOpenPort)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWOpenPort")); // Get the current profile profile = mgr.LocalPolicy.CurrentProfile; // Set the port properties portClass.Enabled = enabled; portClass.Name = name; portClass.Port = port; portClass.Protocol = protocol; // Add the port to the ICF Permissions List profile.GloballyOpenPorts.Add(portClass); return(true); } catch { // Log the error or prompt the user return(false); } }
private static bool GloballyOpenPort(string title, int portNo, NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol/*, NET_FW_IP_VERSION_ ipVersion*/, INetFwMgr manager) { Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT); INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort; port.Name = title; port.Port = portNo; port.Scope = scope; port.Protocol = protocol; //port.IpVersion = ipVersion; try { manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port); } catch (Exception) { return false; } return true; }
private static void GloballyOpenPort(string title, int portNo, NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol, NET_FW_IP_VERSION_ ipVersion) { Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT); INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort; if (port != null) { port.Name = title; port.Port = portNo; port.Scope = scope; port.Protocol = protocol; port.IpVersion = ipVersion; } INetFwMgr manager = GetFirewallManager(); try { manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port); } catch { return; } }
public FW_ERROR_CODE RemovePort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol) { if (m_FirewallProfile == null) { return(FW_ERROR_CODE.FW_ERR_INITIALIZED); } bool bEnablePort = false; FW_ERROR_CODE nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FW_ERROR_CODE.FW_NOERROR) { return(nError); } // Only remove the port, if it is on the collection if (bEnablePort) { // Retrieve the collection of globally open ports INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) { return(FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS); } try { FWOpenPorts.Remove(nPortNumber, ipProtocol); } catch { return(FW_ERROR_CODE.FW_ERR_REMOVE_FROM_COLLECTION); } } return(FW_ERROR_CODE.FW_NOERROR); }
internal static bool AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope/*, NET_FW_IP_VERSION_ ipVersion*/, int port, NET_FW_IP_PROTOCOL_ protocol) { // Create the type from prog id Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION); INetFwAuthorizedApplication auth = Activator.CreateInstance(type) as INetFwAuthorizedApplication; auth.Name = title; auth.ProcessImageFileName = applicationPath; auth.Scope = scope; //auth.IpVersion = ipVersion; // Not implemented auth.Enabled = true; INetFwMgr manager = GetFirewallManager(); try { manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); } catch (Exception) { return false; } return GloballyOpenPort(title, port, scope, protocol, manager); }
/// <summary> /// Add a ports/protocol exception rule for all profiles for Vista or later firewall /// </summary> /// <param name="ruleName"></param> /// <param name="appPath"></param> /// <returns>false if the firewall type isn't available, true for successful completion.</returns> public static bool AddPortExceptionToVistaFirewall(string ruleName, string ports, NET_FW_IP_PROTOCOL_ protocol) { Type fwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2"); if (fwPolicy2Type == null) { return false; } INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)System.Activator.CreateInstance(fwPolicy2Type); INetFwRule fwRule = (INetFwRule)System.Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwRule")); fwRule.Name = ruleName; fwRule.Protocol = (int)protocol; fwRule.LocalPorts = ports; fwRule.Enabled = true; fwPolicy2.Rules.Add(fwRule); return true; }
public FW_ERROR_CODE AddPort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, string strRegisterName) { if (m_FirewallProfile == null) return FW_ERROR_CODE.FW_ERR_INITIALIZED; bool bEnablePort = true; FW_ERROR_CODE nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FW_ERROR_CODE.FW_NOERROR) return nError; // Only add the port, if it isn't added to the collection if (bEnablePort == false) { // Retrieve the collection of globally open ports INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) return FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS; // Create an instance of an open port Type typeFwPort = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); var FWOpenPort = (INetFwOpenPort) Activator.CreateInstance(typeFwPort); if (FWOpenPort == null) return FW_ERROR_CODE.FW_ERR_CREATE_PORT_INSTANCE; // Set the port number FWOpenPort.Port = nPortNumber; // Set the IP Protocol FWOpenPort.Protocol = ipProtocol; // Set the registered name FWOpenPort.Name = strRegisterName; try { FWOpenPorts.Add(FWOpenPort); } catch { return FW_ERROR_CODE.FW_ERR_ADD_TO_COLLECTION; } } else return FW_ERROR_CODE.FW_ERR_SAME_PORT_EXIST; return FW_ERROR_CODE.FW_NOERROR; }
public static void RemovePortExceptionFromSP2Firewall(int port, NET_FW_IP_PROTOCOL_ protocol) { // Instantiating the HNetCfg.NetFwMgr object to get "LocalPolicy" and then "CurrentProfile" INetFwMgr fwMgr = (INetFwMgr) Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(INetFwMgrGuid)), true); INetFwPolicy fwPolicy = fwMgr.LocalPolicy; INetFwProfile fwProfile = fwPolicy.CurrentProfile; // Remove application from exception rule list fwProfile.GloballyOpenPorts.Remove(port, protocol); }
public FW_ERROR_CODE IsPortEnabled(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, ref bool bEnable) { if (m_FirewallProfile == null) return FW_ERROR_CODE.FW_ERR_INITIALIZED; // Retrieve the open ports collection INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) return FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS; // Get the open port try { INetFwOpenPort FWOpenPort = FWOpenPorts.Item(nPortNumber, ipProtocol); if (FWOpenPort != null) bEnable = FWOpenPort.Enabled; else bEnable = false; } catch (FileNotFoundException) { bEnable = false; } return FW_ERROR_CODE.FW_NOERROR; }
public FW_ERROR_CODE RemovePort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol) { if (m_FirewallProfile == null) return FW_ERROR_CODE.FW_ERR_INITIALIZED; bool bEnablePort = false; FW_ERROR_CODE nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FW_ERROR_CODE.FW_NOERROR) return nError; // Only remove the port, if it is on the collection if (bEnablePort) { // Retrieve the collection of globally open ports INetFwOpenPorts FWOpenPorts = m_FirewallProfile.GloballyOpenPorts; if (FWOpenPorts == null) return FW_ERROR_CODE.FW_ERR_GLOBAL_OPEN_PORTS; try { FWOpenPorts.Remove(nPortNumber, ipProtocol); } catch { return FW_ERROR_CODE.FW_ERR_REMOVE_FROM_COLLECTION; } } return FW_ERROR_CODE.FW_NOERROR; }
private INetFwOpenPort GetPortObj(string portNumber, NET_FW_IP_PROTOCOL_ ipProtocol) { Type tpResult = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); INetFwOpenPort port = (INetFwOpenPort)Activator.CreateInstance(tpResult); port.Port = Int32.Parse(portNumber); // port number port.Name = appName; // name of the application using the port port.Enabled = true; // enable the port port.Protocol = ipProtocol; return port; }
public bool GloballyOpenPort(string title, int portNo, NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol, NET_FW_IP_VERSION_ ipVersion) { Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT); INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort; port.Name = title; port.Port = portNo; port.Scope = scope; port.Protocol = protocol; port.IpVersion = ipVersion; //INetFwMgr manager = GetFirewallManagerCached(); try { m_NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port); } catch (Exception ex) { throw ex; } return true; }
// example: RemovePort(Int32.Parse(port.Text), NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP); public static bool RemovePort(int port, NET_FW_IP_PROTOCOL_ protocol) { // Remove the port to the ICF Permissions List INetFwMgr mgr = null; try { mgr = (NetFwTypeLib.INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); } catch { // XPSP2 not installed return false; } try { INetFwProfile profile; // Get the current profile profile = mgr.LocalPolicy.CurrentProfile; // Remove the port to the ICF Permissions List profile.GloballyOpenPorts.Remove(port, protocol); return true; } catch { // Log the error or prompt the user return false; } }
/// /// Create authorization rule for a specific port /// /// To view app permissions from command line use: /// "netsh advfirewall firewall show rule name=udptool.vshost.exe" /// public void GrantPortAuthorization(string applicationFullPath, string usedPort, NET_FW_IP_PROTOCOL_ protocol) { ValidateFields(applicationFullPath); if (usedPort == null) throw new ArgumentNullException("usedPort"); if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot grant authorization, firewall is not enabled."); if (!AppAuthorizationsAllowed) throw new FirewallHelperException("Application exceptions are not allowed."); // Other properties like Protocol, IP Version can also be set accordingly // Now add this to the GloballyOpenPorts collection INetFwProfile profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT); profile.GloballyOpenPorts.Add(GetPortObj(usedPort, protocol)); profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD); profile.GloballyOpenPorts.Add(GetPortObj(usedPort, protocol)); profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_DOMAIN); profile.GloballyOpenPorts.Add(GetPortObj(usedPort, protocol)); }
public FwErrorCode AddPort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, string strRegisterName) { if (_mFirewallProfile == null) return FwErrorCode.FwErrInitialized; bool bEnablePort = true; FwErrorCode nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FwErrorCode.FwNoerror) return nError; // Only add the port, if it isn't added to the collection if (bEnablePort == false) { // Retrieve the collection of globally open ports INetFwOpenPorts fwOpenPorts = _mFirewallProfile.GloballyOpenPorts; if (fwOpenPorts == null) return FwErrorCode.FwErrGlobalOpenPorts; // Create an instance of an open port Type typeFwPort = Type.GetTypeFromCLSID(new Guid("{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}")); var fwOpenPort = (INetFwOpenPort)Activator.CreateInstance(typeFwPort); // Set the port number fwOpenPort.Port = nPortNumber; // Set the IP Protocol fwOpenPort.Protocol = ipProtocol; // Set the registered name fwOpenPort.Name = strRegisterName; try { fwOpenPorts.Add(fwOpenPort); } catch { return FwErrorCode.FwErrAddToCollection; } } else return FwErrorCode.FwErrSamePortExist; return FwErrorCode.FwNoerror; }
public FwErrorCode IsPortEnabled(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol, ref bool bEnable) { if (_mFirewallProfile == null) return FwErrorCode.FwErrInitialized; // Retrieve the open ports collection INetFwOpenPorts fwOpenPorts = _mFirewallProfile.GloballyOpenPorts; if (fwOpenPorts == null) return FwErrorCode.FwErrGlobalOpenPorts; // Get the open port try { INetFwOpenPort fwOpenPort = fwOpenPorts.Item(nPortNumber, ipProtocol); bEnable = fwOpenPort != null && fwOpenPort.Enabled; } catch (System.IO.FileNotFoundException) { bEnable = false; } return FwErrorCode.FwNoerror; }
/// /// Remove port authorization rules. /// public void RemovePortAuthorization(string applicationFullPath, string usedPort, NET_FW_IP_PROTOCOL_ protocol) { ValidateFields(applicationFullPath); if (usedPort == null) throw new ArgumentNullException("usedPort"); int port = Int32.Parse(usedPort); INetFwProfile profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT); profile.GloballyOpenPorts.Remove(port, protocol); profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD); profile.GloballyOpenPorts.Remove(port, protocol); profile = mgr.LocalPolicy.GetProfileByType(NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_DOMAIN); profile.GloballyOpenPorts.Remove(port, protocol); }
public FwErrorCode RemovePort(int nPortNumber, NET_FW_IP_PROTOCOL_ ipProtocol) { if (_mFirewallProfile == null) return FwErrorCode.FwErrInitialized; bool bEnablePort = false; FwErrorCode nError = IsPortEnabled(nPortNumber, ipProtocol, ref bEnablePort); if (nError != FwErrorCode.FwNoerror) return nError; // Only remove the port, if it is on the collection if (bEnablePort) { // Retrieve the collection of globally open ports INetFwOpenPorts fwOpenPorts = _mFirewallProfile.GloballyOpenPorts; if (fwOpenPorts == null) return FwErrorCode.FwErrGlobalOpenPorts; try { fwOpenPorts.Remove(nPortNumber, ipProtocol); } catch { return FwErrorCode.FwErrRemoveFromCollection; } } return FwErrorCode.FwNoerror; }