public static bool PortExists(Protocol protocol, int port) { NET_FW_IP_PROTOCOL_ fwProtocol; switch (protocol) { case Protocol.UDP: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; case Protocol.TCP: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case Protocol.ANY: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY; break; default: throw new Exception("Protocol not supported."); } INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); foreach (INetFwOpenPort fwPort in firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts) { if ((fwPort.Protocol == fwProtocol) && (fwPort.Port == port)) { return(true); } } return(false); }
public static void AddPort(string name, Protocol protocol, int port, bool enable) { INetFwOpenPort portClass = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWOpenPort")); portClass.Name = name; portClass.Port = port; portClass.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; portClass.Enabled = enable; switch (protocol) { case Protocol.UDP: portClass.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; case Protocol.TCP: portClass.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case Protocol.ANY: portClass.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY; break; default: throw new Exception("Protocol not supported."); } INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(portClass); }
private void AddPortToFirewall(string name, int port) { try { Type TicfMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr"); INetFwMgr icfMgr = (INetFwMgr)Activator.CreateInstance(TicfMgr); // add a new port Type TportClass = Type.GetTypeFromProgID("HNetCfg.FWOpenPort"); INetFwOpenPort portClass = (INetFwOpenPort)Activator.CreateInstance(TportClass); // Get the current profile INetFwProfile profile = icfMgr.LocalPolicy.CurrentProfile; // Set the port properties portClass.Scope = NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_ALL; portClass.Enabled = true; portClass.Protocol = NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; // WoWs Info - 8605 portClass.Name = name; portClass.Port = port; // Add the port to the ICF Permissions List profile.GloballyOpenPorts.Add(portClass); } catch (Exception e) { MessageBox.Show(e.Message, Properties.strings.error_title, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.ExitThread(); } }
private static bool AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion) { string PROGID_AUTHORIZED_APPLICATION = System.Configuration.ConfigurationManager.AppSettings["PROGID_AUTHORIZED_APPLICATION"]; // 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; // Unauthorize notepad to connect to internet // Unauthorize wordpad / winword to connect to internet // Unauthorize each tempfile to connect to internet. auth.Enabled = false; INetFwMgr manager = GetFirewallManager(); try { manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); } catch (Exception ex) { return(false); } return(true); }
public void Run() { Output.WriteDebug("Testing if firewall is enabled"); Type netFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(netFwMgrType); bool firewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled; if (!firewallEnabled) { Output.WriteWarn("The windows firewall is disabled on the local machine"); exitCode = ExitCode.WARNING; return; } Output.WriteDebug("Testing if ssh port is opened"); CheckRule(SSHDFWRULENAME, 22); Output.WriteDebug("Testing prison firewall rules"); Prison.Prison[] prisonUsers = Prison.Prison.Load(); foreach (var prisonUser in prisonUsers) { string firewallRuleName = prisonUser.ID.ToString().TrimStart('0').Replace("-", ""); Output.WriteDebug(string.Format("Testing firewall for user {0}", firewallRuleName)); int firewallPort = prisonUser.Rules.UrlPortAccess; CheckRule(firewallRuleName, firewallPort); } }
private static void AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion) { Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION); INetFwAuthorizedApplication auth = Activator.CreateInstance(type) as INetFwAuthorizedApplication; if (auth != null) { auth.Name = title; } if (!File.Exists(applicationPath)) { return; } if (auth != null) { auth.ProcessImageFileName = applicationPath; auth.Scope = scope; auth.IpVersion = ipVersion; auth.Enabled = true; } INetFwMgr manager = GetFirewallManager(); try { manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); } catch { return; } }
public MainWindow() { InitializeComponent(); // Open the port in the firewall Type type = Type.GetTypeFromProgID("HNetCfg.FWOpenPort"); INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort; port.Port = 19283; port.Name = "Mayhem"; port.Enabled = true; Type netFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(netFwMgrType); INetFwOpenPorts ports = mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts; ports.Add(port); // Add the ACL string name = WindowsIdentity.GetCurrent().Name; SecurityIdentity sid = SecurityIdentity.SecurityIdentityFromName(name); string acl = "D:(A;;GA;;;" + sid + ")"; Debug.WriteLine(acl); SetHttpNamespaceAcl("http://+:19283/", acl); Close(); }
public static string InformacaoFirewall() { try { Type tpNetFirewall = Type.GetTypeFromProgID ("HNetCfg.FwMgr", false); INetFwMgr mgrInstance = (INetFwMgr)Activator .CreateInstance(tpNetFirewall); bool blnEnabled = mgrInstance.LocalPolicy .CurrentProfile.FirewallEnabled; mgrInstance = null; tpNetFirewall = null; if (blnEnabled) { return("Firewall ativo"); } return("Firewall inativo"); } catch (Exception e) { return(""); } }
public bool AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion) { // 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; auth.Enabled = true; INetFwMgr manager = GetFirewallManager(); try { manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); } catch (Exception ex) { return(false); } return(true); }
public static void RemovePort(Protocol protocol, int port) { NET_FW_IP_PROTOCOL_ fwProtocol; switch (protocol) { case Protocol.UDP: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; case Protocol.TCP: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case Protocol.ANY: fwProtocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY; break; default: throw new Exception("Protocol not supported."); } INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Remove(port, fwProtocol); }
public void EnableFW() { manager = GetFirewallManager(); bool isFirewallEnabled = manager.LocalPolicy.CurrentProfile.FirewallEnabled; if (isFirewallEnabled == false) manager.LocalPolicy.CurrentProfile.FirewallEnabled = true; }
public bool AddPort(ushort portNumber, String appName) { bool result = false; try { INetFwMgr fwMgr = (INetFwMgr)getInstance("INetFwMgr"); INetFwPolicy fwPolicy = fwMgr.LocalPolicy; INetFwProfile fwProfile = fwPolicy.CurrentProfile; INetFwOpenPorts ports = fwProfile.GloballyOpenPorts; INetFwOpenPort port = (INetFwOpenPort)getInstance("INetOpenPort"); port.Port = portNumber; /* port no */ port.Name = appName; /*name of the application using the port */ port.Enabled = true; /* enable the port */ /*other properties like Protocol, IP Version can also be set accordingly * now add this to the GloballyOpenPorts collection */ Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); ports = (INetFwOpenPorts)mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts; ports.Add(port); result = true; } catch (UnauthorizedAccessException ex) { result = false; } return(result); }
/* Checks if Windows Firewall is Enabled or not from a System Level */ public static bool FirewallStatus() { bool FirewallEnabled; if (DetectLinux.LinuxDetected()) { FirewallEnabled = false; } else { try { Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); FirewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled; } catch { FirewallEnabled = false; } } return(FirewallEnabled); }
/// <summary> /// Add port to windows firewall /// Reference: https://social.msdn.microsoft.com/Forums/vstudio/en-US/a3e390d1-4383-4f23-bad9-b725bef33499/add-firewall-rule-programatically?forum=wcf /// </summary> static void AddPortToFirewall(string name, int port) { try { Type TicfMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr"); INetFwMgr icfMgr = (INetFwMgr)Activator.CreateInstance(TicfMgr); // add a new port Type TportClass = Type.GetTypeFromProgID("HNetCfg.FWOpenPort"); INetFwOpenPort portClass = (INetFwOpenPort)Activator.CreateInstance(TportClass); // Get the current profile INetFwProfile profile = icfMgr.LocalPolicy.CurrentProfile; // Set the port properties portClass.Scope = NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_ALL; portClass.Enabled = true; portClass.Protocol = NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; // WoWs Info - 8605 portClass.Name = name; portClass.Port = port; // Add the port to the ICF Permissions List profile.GloballyOpenPorts.Add(portClass); } catch (Exception e) { Console.WriteLine("Failed to add port to firewall. This is the error message.\n"); Console.WriteLine(e.Message); Console.WriteLine("\nPlease feel free to open an issue to discuss this it with me."); Process.Start("https://github.com/HenryQuan/winserver"); } }
public static bool AuthorizeProgram(string title, string path, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipver) { Type type = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"); INetFwAuthorizedApplication authapp = Activator.CreateInstance(type) as INetFwAuthorizedApplication; authapp.Name = title; authapp.ProcessImageFileName = path; authapp.Scope = scope; authapp.IpVersion = ipver; authapp.Enabled = true; INetFwMgr mgr = WinFirewallManager(); try { mgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(authapp); } catch (Exception ex) { System.Diagnostics.Trace.Write(ex.Message); return(false); } return(true); }
/// /// Private Constructor. If this fails, HasFirewall will return /// false; /// private FirewallHelper() { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); // Assume failed. fwMgr = null; if (fwMgrType != null) { try { fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType); } // In all other circumnstances, fwMgr is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } }
protected internal void SetProfile() { INetFwMgr fwMgr = null; INetFwPolicy fwPolicy = null; try { fwMgr = GetInstance("INetFwMgr") as INetFwMgr; fwPolicy = fwMgr.LocalPolicy; fwProfile = fwPolicy.CurrentProfile; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (fwMgr != null) { fwMgr = null; } if (fwPolicy != null) { fwPolicy = null; } } }
/// <summary> /// 将应用程序添加到防火墙例外 /// </summary> /// <param name="name">应用程序名称</param> /// <param name="executablePath">应用程序可执行文件全路径</param> public static void NetFwAddApps(string name, string executablePath) { try { //创建firewall管理类的实例 INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication")); //在例外列表里,程序显示的名称 app.Name = name; //程序的路径及文件名 app.ProcessImageFileName = executablePath; //是否启用该规则 app.Enabled = true; //加入到防火墙的管理策略 netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app); bool exist = false; //加入到防火墙的管理策略 foreach (INetFwAuthorizedApplication mApp in netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) { if (app == mApp) { exist = true; break; } } if (!exist) { netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app); } } catch { } }
public Boolean FRcheck() { INetFwMgr manager = GetFirewallManager(); bool isFirewallEnabled = manager.LocalPolicy.CurrentProfile.FirewallEnabled; return(isFirewallEnabled); }
private Boolean FireWallEbbl() { Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); return(mgr.LocalPolicy.CurrentProfile.FirewallEnabled); }
/// <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 Firewall() { policyManager = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); manager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); profile = manager.LocalPolicy.CurrentProfile; openPorts = profile.GloballyOpenPorts; }
/// <summary> /// Adds an application with specified parameters to a XP SP2-compatible firewall exception list. /// </summary> /// <param name="name">Title of the rule</param> /// <param name="imageName">Full path of the image</param> /// <param name="strLocalSubnet">Space seperated network addresses permitted to access the application /// (e.g. "LocalSubnet", "*", "192.168.10.0/255.255.255.0")</param> /// <param name="enabled">If the exception rule should be enabled</param> /// <remarks> /// WARNING: This method does not inform the user that the firewall punchthrough is being added. Applications /// should always inform the user when adding punchthroughs to the firewall, for security reasons. /// </remarks> public static void AddAppToSP2Firewall(String name, String imageName, String strLocalSubnet, bool enabled) { // 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; // Checking got skipped since the entry gets update if exist and inserted if not // (No check necessary); Check if the entry already exists. "System.IO.FileNotFoundException" // will be thrown if entry doesn't exist. // fwAA = fwProfile.AuthorizedApplications.Item(imageName); // Instantiating the HNetCfg.NetFwAuthorizedApplication object INetFwAuthorizedApplication fwAA = (INetFwAuthorizedApplication)Activator.CreateInstance( Type.GetTypeFromCLSID(new Guid(INetFwAuthorizedApplicationGuid)), true); // Assigning values to the AuthorizedApplication to be added to the firewall permission list. // Make this entry Enabled/Disabled fwAA.Enabled = enabled; // The friendly name for this "Exception" rule fwAA.Name = name; // Whether only the local subnet can access this application or not fwAA.RemoteAddresses = strLocalSubnet; // The image name full path fwAA.ProcessImageFileName = imageName; // Adding AuthorizedApplication to the Exception List fwProfile.AuthorizedApplications.Add(fwAA); }
protected void setProfile() { INetFwMgr fwMgr = null; INetFwPolicy fwPolicy = null; try { fwMgr = GetInstance("INetFwMgr") as INetFwMgr; fwPolicy = fwMgr.LocalPolicy; fwProfile = fwPolicy.CurrentProfile; } catch (Exception ex) { logger.Error(ex.Message); } finally { logger.Info("Firewall: aggiunto profilo "); if (fwMgr != null) { fwMgr = null; } if (fwPolicy != null) { fwPolicy = null; } } }
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; } }
// 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); } }
public FW_ERROR_CODE Initialize() { if (m_FirewallProfile != null) { return(FW_ERROR_CODE.FW_ERR_INITIALIZED); } Type typFwMgr = null; INetFwMgr fwMgr = null; typFwMgr = Type.GetTypeFromCLSID(new Guid("{304CE942-6E39-40D8-943A-B913C40C9CD4}")); fwMgr = (INetFwMgr)Activator.CreateInstance(typFwMgr); if (fwMgr == null) { return(FW_ERROR_CODE.FW_ERR_CREATE_SETTING_MANAGER); } INetFwPolicy fwPolicy = fwMgr.LocalPolicy; if (fwPolicy == null) { return(FW_ERROR_CODE.FW_ERR_LOCAL_POLICY); } try { m_FirewallProfile = fwPolicy.GetProfileByType(fwMgr.CurrentProfileType); } catch { return(FW_ERROR_CODE.FW_ERR_PROFILE); } return(FW_ERROR_CODE.FW_NOERROR); }
public static void AddPortException(string name, int port, ProtocolType protocol) { //创建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; switch (protocol) { case ProtocolType.Tcp: objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; break; case ProtocolType.Udp: objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; break; } objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; objPort.Enabled = true; bool exist = netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Cast <INetFwOpenPort>() .Any(p => p.Equals(objPort)); if (!exist) { netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort); } }
/* Com refrences * using NATUPNPLib; * using NETCONLib; * using NetFwTypeLib; */ public static bool AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion) { Type type = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"); INetFwAuthorizedApplication auth = Activator.CreateInstance(type) as INetFwAuthorizedApplication; auth.Name = title; auth.ProcessImageFileName = applicationPath; auth.Scope = scope; auth.IpVersion = ipVersion; auth.Enabled = true; INetFwMgr manager = GetFirewallManager(); if (manager == null) { return(false); } if (!manager.LocalPolicy.CurrentProfile.FirewallEnabled) { manager.LocalPolicy.CurrentProfile.FirewallEnabled = true; } try { manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); } catch// (Exception ex) { // MessageBox.Show(ex.ToString()); return(false); } return(true); }
public static void AddApplicationToException(string name, string path) { //创建firewall管理类的实例 INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication")); //在例外列表里,程序显示的名称 app.Name = name; //程序的路径及文件名 app.ProcessImageFileName = path; //是否启用该规则 app.Enabled = true; ////加入到防火墙的管理策略 //netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app); bool exist = netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications .Cast <INetFwAuthorizedApplication>() .Any(a => a.ProcessImageFileName.Equals(app.ProcessImageFileName, StringComparison.OrdinalIgnoreCase)); if (!exist) { netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app); } }
//检测满足条件,开启所有访问 public void AllowOpenFW() { //判断系统属于xp还是win7 using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"Software\\Microsoft\\Windows NT\\CurrentVersion")) { var VersionName = rk.GetValue("ProductName").ToString(); if (VersionName.Contains("XP")) { // 创建firewall管理类的实例 ,删除添加程序到防火墙例外 INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove("禁用所有端口号"); } else { // 1. 创建实例,允许所有程序的连接。 INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); //启用或禁用<高级安全Windows防火墙> - 专有配置文件的出站连接 firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, NET_FW_ACTION_.NET_FW_ACTION_ALLOW); //启用或禁用<高级安全Windows防火墙> - 公用配置文件的出站连接 firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC, NET_FW_ACTION_.NET_FW_ACTION_ALLOW); // 2. 删除本程序的出站规则删除规则 firewallPolicy.Rules.Remove("禁用所有端口号"); //添加成功,显示成功标志 Console.WriteLine("启动成功"); } } }
public Firewall() { manager = GetFirewallManager(); if (manager != null) firewallOn = manager.LocalPolicy.CurrentProfile.FirewallEnabled; else firewallOn = false; }
public FirewallHelper() { Type netFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); mgr = null; if (netFwMgrType != null) { mgr = (INetFwMgr)Activator.CreateInstance(netFwMgrType); } }
public bool AddProgram(string title, string applicationPath) { bool result = false; INetFwAuthorizedApplication auth = _GetAuth(title, applicationPath); _fwMgr = _GetFirewallManager(); try { _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth); result = true; } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return result; }
public string GetByPort(int _port) { string portName = null; try { _fwMgr = _GetFirewallManager(); foreach (INetFwOpenPort port in _fwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts) { if (port.Port == _port) { portName = port.Name; break; } } } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return portName; }
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; }
public List<string> GetPortList() { List<string> aList = new List<string>(); try { _fwMgr = _GetFirewallManager(); foreach (INetFwOpenPort port in _fwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts) { aList.Add(port.Name + ":" + port.Port); } } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return aList; }
private bool _SetEnableFirewall(bool enable) { _fwMgr = _GetFirewallManager(); _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled = enable; return _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled; }
public string GetByProgramPath(string fileName) { string programName = null; try { _fwMgr = _GetFirewallManager(); foreach (INetFwAuthorizedApplication app in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) { if (fileName.ToLower().Equals(app.ProcessImageFileName.ToLower())) { programName = string.Format("{0}[{1}]", app.Name,app.ProcessImageFileName); break; } } } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return programName; }
public static void Initialize() { mgr = (INetFwMgr)Activator.CreateInstance(net_fw_mgr_type); policy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWPolicy2")); }
public NetFirewall() { m_NetFwMgr = GetFirewallManager(); }
public List<string> GetProgramList() { List<string> aList = new List<string>(); try { _fwMgr = _GetFirewallManager(); foreach (INetFwAuthorizedApplication app in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) { aList.Add(app.Name+":"+app.ProcessImageFileName); } } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return aList; }
public bool RemoveProgram(string applicationPath) { bool result = false; _fwMgr = _GetFirewallManager(); try { _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationPath); result = true; } catch (Exception ex) { MsgrLogger.WriteLog(ex.ToString()); } return result; }
/// <summary> /// Writes out various firewall configurations for the local firewall policy. /// </summary> /// <param name="manager">INetFwMgr object</param> private void DisplayFirewallProfile(INetFwMgr manager) { INetFwProfile profile = manager.LocalPolicy.CurrentProfile; /* * * Profile Information * */ Logger.Log(WindowsFirewall.LINE_HEADER); Logger.Log("Windows Firewall Report\n"); Logger.Log(string.Format(string.Format("\n\n{0}\n{1}", "Profile", WindowsFirewall.SHORT_LINE_HEADER))); Logger.Log(string.Format("Firewall Policy Type: {0}", this.GetPolicyType(profile))); Logger.Log(string.Format("Exceptions Not Allowed: {0}", profile.ExceptionsNotAllowed)); Logger.Log(string.Format("Notifications Disabled: {0}", profile.NotificationsDisabled)); Logger.Log(string.Format("Remote Administration Enabled: {0}", profile.RemoteAdminSettings.Enabled)); /* * * ICMP Settings * */ Logger.Log(string.Format("\n\n{0}\n{1}", "ICMP Settings", WindowsFirewall.SHORT_LINE_HEADER)); Logger.Log(string.Format("Allow Inbound Echo Request: {0}", profile.IcmpSettings.AllowInboundEchoRequest)); Logger.Log(string.Format("Allow Inbound Mask Request: {0}", profile.IcmpSettings.AllowInboundMaskRequest)); Logger.Log(string.Format("Allow Inbound Router Request: {0}", profile.IcmpSettings.AllowInboundRouterRequest)); Logger.Log(string.Format("Allow Inbound TimeStamp Request: {0}", profile.IcmpSettings.AllowInboundTimestampRequest)); Logger.Log(string.Format("Allow Outbound Destination Unreachable: {0}", profile.IcmpSettings.AllowOutboundDestinationUnreachable)); Logger.Log(string.Format("Allow Outbound Packet Too Big: {0}", profile.IcmpSettings.AllowOutboundPacketTooBig)); Logger.Log(string.Format("Allow Outbout Parameter Problem: {0}", profile.IcmpSettings.AllowOutboundParameterProblem)); Logger.Log(string.Format("Allow Outbound Source Quench: {0}", profile.IcmpSettings.AllowOutboundSourceQuench)); Logger.Log(string.Format("Allow Outbound Time Exceeded: {0}", profile.IcmpSettings.AllowOutboundTimeExceeded)); Logger.Log(string.Format("Allow Redirect: {0}", profile.IcmpSettings.AllowRedirect)); /* * * Port Information * */ Logger.Log(string.Format("\n\n{0}\n{1}", "Port Information", WindowsFirewall.SHORT_LINE_HEADER)); Logger.Log(string.Format("Globally Opened Ports: {0}", profile.GloballyOpenPorts.Count)); // Display detailed port information. foreach (INetFwOpenPort port in profile.GloballyOpenPorts) { Logger.Log(string.Format("\n\nPort Name: {0}", port.Name)); Logger.Log(string.Format("{0, 20}{1}", "Port Number: ", port.Port)); Logger.Log(string.Format("{0, 20}{1}", "Port Protocol: ", this.GetPortType(port))); Logger.Log(string.Format("{0, 20}{1}", "Port IP Version: ", this.GetIPVersion(port))); Logger.Log(string.Format("{0, 20}{1}", "Port Enabled: ", port.Enabled)); Logger.Log(string.Format("{0, 20}{1}", "Remote Addresses: ", port.RemoteAddresses)); } /* * * Service Information * */ Logger.Log(string.Format("\n\n{0}\n{1}", "Services Information", WindowsFirewall.SHORT_LINE_HEADER)); Logger.Log(string.Format("# of Services: {0}", profile.Services.Count)); // Display detailed service information. foreach (INetFwService service in profile.Services) { Logger.Log(string.Format("\n\nService Name: {0}", service.Name)); Logger.Log(string.Format("{0, 20}{1}", "Enabled: ", service.Enabled)); Logger.Log(string.Format("{0, 20}{1}", "Scope: ", this.GetServiceScope(service))); // Obtain all the port information the service is utilizing. foreach (INetFwOpenPort port in service.GloballyOpenPorts) { Logger.Log(string.Format("{0, 20}{1}", "Port Number: ", port.Port)); Logger.Log(string.Format("{0, 20}{1}", "Port Protocol: ", this.GetPortType(port))); Logger.Log(string.Format("{0, 20}{1}", "Port IP Version: ", this.GetIPVersion(port))); Logger.Log(string.Format("{0, 20}{1}", "Port Enabled: ", port.Enabled)); Logger.Log(string.Format("{0, 20}{1}", "Remote Addresses: ", port.RemoteAddresses)); } } /* * * Authorized Applications * */ Logger.Log(string.Format("\n\n{0}\n{1}", "Authorized Applications", WindowsFirewall.SHORT_LINE_HEADER)); Logger.Log(string.Format("# of Authorized Applications: {0}", profile.AuthorizedApplications.Count)); // Display detailed authorized application information. foreach (INetFwAuthorizedApplication application in profile.AuthorizedApplications) { Logger.Log(string.Format("\n\nApplication Name: {0}", application.Name)); Logger.Log(string.Format("{0, 20}{1}", "Enabled: ", application.Enabled)); Logger.Log(string.Format("{0, 20}{1}", "Remote Addresses: ", application.RemoteAddresses)); Logger.Log(string.Format("{0, 20}{1}", "File Path: ", application.ProcessImageFileName)); } }
public bool IsFirewallEnabled() { _fwMgr = _GetFirewallManager(); return _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled; }