コード例 #1
1
        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);
        }
コード例 #2
0
        /// <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);
        }
コード例 #3
0
        private static INetFwAuthorizedApplication GetAuthAppObj(string applicationFullPath, string appName)
        {
            // Get the type of HNetCfg.FwMgr, or null if an error occurred
            Type authApp = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);

            // Assume failed.
            INetFwAuthorizedApplication appInfo = null;

            if (authApp != null)
            {
                try
                {
                    appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authApp);
                }
                catch (Exception)
                {
                    // In all other circumnstances, appInfo is null.
                }
            }

            if (appInfo == null)
            {
                throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");
            }

            appInfo.Name = appName;
            appInfo.ProcessImageFileName = applicationFullPath;
            return(appInfo);
        }
コード例 #4
0
        //为防火墙添加出站规则
        public void handle(string name)
        {
            //目前不用
            if (name.Contains("XP"))
            {
                INetFwAuthorizedApplication Fwapp = (INetFwAuthorizedApplication)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"));
            }

            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);
                //创建出站规则来控制程序联网
                INetFwRule2 stopallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                stopallRule.Name        = "禁用所有端口号";
                stopallRule.Description = "关闭所有可用端口";
                stopallRule.Direction   = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
                stopallRule.Action      = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                stopallRule.Protocol    = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                stopallRule.Enabled     = true;
                stopallRule.RemotePorts = "1-65535";
                firewallPolicy.Rules.Add(stopallRule);
                //添加成功,显示成功标志
                Console.WriteLine("关闭成功");
            }
        }
コード例 #5
0
        /* 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);
        }
コード例 #6
0
        ///
        /// Opens the given ports on windows firewall. Also opens entirely the given application on the firewall.
        /// Please remember that you need administrative rights to use this function.
        ///
        /// The path of the application. Please include the ending \
        /// The name of the executable to open
        /// The ports that you wish to open individually
        public void openFirewall(string executableFilePath, string applicationName, int[] portsToOpen)
        {
            ///////////// Firewall Authorize Application ////////////
            try
            {
                setProfile();
                INetFwAuthorizedApplications apps = fwProfile.AuthorizedApplications;
                INetFwAuthorizedApplication  app  = (INetFwAuthorizedApplication)getInstance("INetAuthApp");
                app.Name = applicationName;
                app.ProcessImageFileName = executableFilePath;
                apps.Add(app);
                apps = null;

                //////////////// Open Needed Ports /////////////////
                INetFwOpenPorts openports = fwProfile.GloballyOpenPorts;
                foreach (int port in portsToOpen)
                {
                    INetFwOpenPort openport = (INetFwOpenPort)getInstance("INetOpenPort");
                    openport.Port     = port;
                    openport.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
                    openport.Name     = applicationName + " Operation Port (" + port.ToString() + ")";
                    openports.Add(openport);
                }
                openports = null;
            }
            catch (Exception)
            {
                // throw;
            }
            Console.WriteLine("Firewall : Open Ports");
        }
コード例 #7
0
        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;
            }
        }
コード例 #8
0
        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);
            }
        }
コード例 #9
0
        protected internal void OpenFirewall()
        {
            INetFwAuthorizedApplications authApps = null;
            INetFwAuthorizedApplication  authApp  = null;
            INetFwOpenPorts openPorts             = null;
            INetFwOpenPort  openPort = null;

            try {
                if (isAppFound(Application.ProductName + " Server") == false)
                {
                    SetProfile();
                    authApps     = fwProfile.AuthorizedApplications;
                    authApp      = GetInstance("INetAuthApp") as INetFwAuthorizedApplication;
                    authApp.Name = Application.ProductName + " Server";
                    authApp.ProcessImageFileName = Application.ExecutablePath;
                    authApps.Add(authApp);
                }
                if (isPortFound(portsSocket[0]) == false)
                {
                    SetProfile();
                    openPorts         = fwProfile.GloballyOpenPorts;
                    openPort          = GetInstance("INetOpenPort") as INetFwOpenPort;
                    openPort.Port     = portsSocket[0];
                    openPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                    openPort.Name     = portsName[0];
                    openPorts.Add(openPort);
                }
                if (isPortFound(portsSocket[1]) == false)
                {
                    SetProfile();
                    openPorts         = fwProfile.GloballyOpenPorts;
                    openPort          = GetInstance("INetOpenPort") as INetFwOpenPort;
                    openPort.Port     = portsSocket[1];
                    openPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                    openPort.Name     = portsName[1];
                    openPorts.Add(openPort);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
            finally {
                if (authApps != null)
                {
                    authApps = null;
                }
                if (authApp != null)
                {
                    authApp = null;
                }
                if (openPorts != null)
                {
                    openPorts = null;
                }
                if (openPort != null)
                {
                    openPort = null;
                }
            }
        }
コード例 #10
0
 /// <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 { }
 }
コード例 #11
0
        private INetFwAuthorizedApplication GetAuthAppObj(string applicationFullPath, string appName)
        {
            // Get the type of HNetCfg.FwMgr, or null if an error occurred
            Type authApp = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false);

            // Assume failed.
            INetFwAuthorizedApplication appInfo = null;

            if (authApp != null)
            {
                try
                {
                    appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authApp);
                }
                // In all other circumnstances, appInfo is null.
                catch (ArgumentException) { }
                catch (NotSupportedException) { }
                catch (System.Reflection.TargetInvocationException) { }
                catch (MissingMethodException) { }
                catch (MethodAccessException) { }
                catch (MemberAccessException) { }
                catch (InvalidComObjectException) { }
                catch (COMException) { }
                catch (TypeLoadException) { }
            }

            if (appInfo == null)
            {
                throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance.");
            }

            appInfo.Name = appName;
            appInfo.ProcessImageFileName = applicationFullPath;
            return(appInfo);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
        /// <summary>
        /// Creates a rule on the current firewall profile, if such a rule not allready exists. Does nothing if the firewall is not enabled.
        /// Adds the <see cref="ImagePath"/> to the authorized applications.
        /// </summary>
        public void OpenFirewall()
        {
            INetFwAuthorizedApplication authApp = null;
            var profile = GetCurrentProfile();

            if (!profile.FirewallEnabled)
            {
                Log.Info($"The current firewall profile is not enabled, so it's not required to create a firewall rule.");
                return;
            }

            try
            {
                if (!IsAppFound(AppName))
                {
                    Log.Debug($"Authorizing application {AppName} on the current firewall profile, image path for authorizing: " + ImagePath.FullName);
                    authApp         = (INetFwAuthorizedApplication)(Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("{EC9846B3-2762-4A6B-A214-6ACB603462D2}"))));
                    authApp.Name    = AppName;
                    authApp.Enabled = true;
                    authApp.ProcessImageFileName = ImagePath.FullName;
                    profile.AuthorizedApplications.Add(authApp);
                }

                Log.Warn($"Firewall is open for application {AppName}.");
            }
            finally
            {
                if (authApp != null)
                {
                    authApp = null;
                }
            }
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        public bool IsApplicationEnabled(string applicationFileNameWithPath)
        {
            DoDisposeCheck();
            DoInitializationCheck();
            if (string.IsNullOrEmpty(applicationFileNameWithPath))
            {
                ThrowHelper.ThrowArgumentNullException("applicationFileNameWithPath");
            }

            INetFwAuthorizedApplications firewallApps = mFirewallProfile.AuthorizedApplications;

            if (firewallApps == null)
            {
                throw new FirewallException("Failed to get authorized applications.");
            }

            bool result = false;

            try
            {
                INetFwAuthorizedApplication firewallApp = firewallApps.Item(applicationFileNameWithPath);
                // If FAILED, the application is not in the collection list
                if (firewallApp != null)
                {
                    result = firewallApp.Enabled;
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
コード例 #16
0
ファイル: Firewall.cs プロジェクト: uzbekdev1/main
        public FW_ERROR_CODE AddApplication(string strProcessImageFileName, string strRegisterName)
        {
            if (m_FirewallProfile == null)
            {
                return(FW_ERROR_CODE.FW_ERR_INITIALIZED);
            }

            if (strProcessImageFileName.Length == 0 || strRegisterName.Length == 0)
            {
                return(FW_ERROR_CODE.FW_ERR_INVALID_ARG);
            }

            // First of all, check the application is already authorized;
            bool          bAppEnable = true;
            FW_ERROR_CODE nError     = IsAppEnabled(strProcessImageFileName, ref bAppEnable);

            if (nError != FW_ERROR_CODE.FW_NOERROR)
            {
                return(nError);
            }

            // Only add the application if it isn't authorized
            if (bAppEnable == false)
            {
                // Retrieve the authorized application collection
                INetFwAuthorizedApplications FWApps = m_FirewallProfile.AuthorizedApplications;

                if (FWApps == null)
                {
                    return(FW_ERROR_CODE.FW_ERR_AUTH_APPLICATIONS);
                }

                // Create an instance of an authorized application
                Type typeFwApp = Type.GetTypeFromCLSID(new Guid("{EC9846B3-2762-4A6B-A214-6ACB603462D2}"));

                INetFwAuthorizedApplication FWApp = (INetFwAuthorizedApplication)Activator.CreateInstance(typeFwApp);
                if (FWApp == null)
                {
                    return(FW_ERROR_CODE.FW_ERR_CREATE_APP_INSTANCE);
                }

                // Set the process image file name
                FWApp.ProcessImageFileName = strProcessImageFileName;
                FWApp.Name = strRegisterName;

                try
                {
                    FWApps.Add(FWApp);
                }
                catch
                {
                    return(FW_ERROR_CODE.FW_ERR_ADD_TO_COLLECTION);
                }
            }

            return(FW_ERROR_CODE.FW_NOERROR);
        }
コード例 #17
0
        /// <summary>
        /// Apre tutte le porte sia TCP che UDP per un determinato Exe
        /// </summary>
        /// <param name="appName">Nome che comparira' nella regola del Firewall</param>
        /// <param name="exePath">Percorso alleseguibile da sbloccare sul Firewall</param>
        protected internal void OpenFirewallExe(string appName = "", string exePath = "")
        {
            INetFwAuthorizedApplications authApps = null;
            INetFwAuthorizedApplication  authApp  = null;
            INetFwOpenPorts openPorts             = null;
            INetFwOpenPort  openPort = null;

            if (appName == "")
            {
                appName = Application.ProductName;
            }
            if (exePath == "")
            {
                exePath = Application.ExecutablePath;
            }
            try
            {
                if (isAppFound(Application.ProductName) == false)
                {
                    SetProfile();
                    authApps                     = fwProfile.AuthorizedApplications;
                    authApp                      = GetInstance("INetAuthApp") as INetFwAuthorizedApplication;
                    authApp.Name                 = appName;
                    authApp.Scope                = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
                    authApp.IpVersion            = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
                    authApp.ProcessImageFileName = exePath;
                    authApps.Add(authApp);

                    logger.Info("Aggiunta regola generale per " + appName + ": " + exePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (authApps != null)
                {
                    authApps = null;
                }
                if (authApp != null)
                {
                    authApp = null;
                }
                if (openPorts != null)
                {
                    openPorts = null;
                }
                if (openPort != null)
                {
                    openPort = null;
                }
            }
        }
コード例 #18
0
ファイル: WindowsFirewall.cs プロジェクト: Kaibu/WindowsGSM
        public void AddRule()
        {
            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);
        }
コード例 #19
0
        private void _AddAppToFirewall(INetFwProfile profile)
        {
            INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance(
                Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp)));

            application.Name = _RuleName;
            application.ProcessImageFileName = _ExePath;
            application.Enabled = true;
            application.Scope   = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            profile.AuthorizedApplications.Add(application);
        }
コード例 #20
0
        public void FirewallOpenPort(int port, string protocol, string appName)
        {
            ///////////// Firewall Authorize Application ////////////
            String imageFilename = Utils.EmuleAdunanzAExeGetPath();

            setProfile();
            INetFwAuthorizedApplications apps = fwProfile.AuthorizedApplications;
            INetFwAuthorizedApplication  app  = (INetFwAuthorizedApplication)GetInstance("INetAuthApp");

            app.Name = appName;
            app.ProcessImageFileName = imageFilename;
            apps.Add(app);

            //////////////// Open Needed Ports /////////////////
            INetFwOpenPorts openports = fwProfile.GloballyOpenPorts;
            INetFwOpenPort  openport  = (INetFwOpenPort)GetInstance("INetOpenPort");

            openport.Port = port;
            try
            {
                if (protocol.ToLower() == "udp")
                {
                    openport.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
                }
                else if (protocol.ToLower() == "tcp")
                {
                    openport.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                }
                else
                {
                    openport.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
                }

                openport.Name = appName + " " + protocol;
                openports.Add(openport);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            finally
            {
                if (apps != null)
                {
                    apps = null;
                }
                if (openport != null)
                {
                    openport = null;
                }
                logger.Info("Firewall: aggiunta regola per {0} su porta {1}: {2}", appName, port, protocol);
            }
        } // openFirewall
コード例 #21
0
        public static void AddApplication(string name, string path)
        {
            INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"));

            application.Name = name;
            application.ProcessImageFileName = path;
            application.Enabled = true;

            INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));

            firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(application);
        }
コード例 #22
0
        protected internal void OpenFirewallPort(int port, string protocol, string appName)
        {
            INetFwAuthorizedApplications authApps = null;
            INetFwAuthorizedApplication  authApp  = null;
            INetFwOpenPorts openPorts             = null;
            INetFwOpenPort  openPort = null;

            try
            {
                if (isPortFound(port) == false)
                {
                    SetProfile();
                    openPorts     = fwProfile.GloballyOpenPorts;
                    openPort      = GetInstance("INetOpenPort") as INetFwOpenPort;
                    openPort.Port = port;
                    if (protocol.ToLower() == "udp")
                    {
                        openPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
                    }
                    else if (protocol.ToLower() == "tcp")
                    {
                        openPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                    }

                    openPort.Name = appName + " " + protocol.ToUpper();
                    openPorts.Add(openPort);
                    logger.Info("Firewall: Aggiunta regola per " + appName + ": " + protocol.ToUpper());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (authApps != null)
                {
                    authApps = null;
                }
                if (authApp != null)
                {
                    authApp = null;
                }
                if (openPorts != null)
                {
                    openPorts = null;
                }
                if (openPort != null)
                {
                    openPort = null;
                }
            }
        }
コード例 #23
0
 public static AuthorizeApp Convert(INetFwAuthorizedApplication item)
 {
     return(new AuthorizeApp
     {
         Enabled = item.Enabled,
         IpVersion = Convert(item.IpVersion),
         Name = item.Name,
         ProcessImageFileName = item.ProcessImageFileName,
         RemoteAddresses = item.RemoteAddresses,
         Scope = Convert(item.Scope)
     });
 }
コード例 #24
0
ファイル: Firewall.cs プロジェクト: fldash/Wargame-Reporter
        protected internal bool isAppFound(string appPath)
        {
            bool      boolResult = false;
            Type      progID     = null;
            INetFwMgr firewall   = null;
            INetFwAuthorizedApplications apps = null;
            INetFwAuthorizedApplication  app  = null;

            try
            {
                progID   = Type.GetTypeFromProgID("HNetCfg.FwMgr");
                firewall = Activator.CreateInstance(progID) as INetFwMgr;
                if (firewall.LocalPolicy.CurrentProfile.FirewallEnabled)
                {
                    apps = firewall.LocalPolicy.CurrentProfile.AuthorizedApplications;
                    IEnumerator appEnumerate = apps.GetEnumerator();
                    while ((appEnumerate.MoveNext()))
                    {
                        app = appEnumerate.Current as INetFwAuthorizedApplication;
                        if (app.ProcessImageFileName == appPath)
                        {
                            boolResult = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (progID != null)
                {
                    progID = null;
                }
                if (firewall != null)
                {
                    firewall = null;
                }
                if (apps != null)
                {
                    apps = null;
                }
                if (app != null)
                {
                    app = null;
                }
            }
            return(boolResult);
        }
コード例 #25
0
        public bool AddApplication(string applicationFileNameWithPath, string registeredName)
        {
            DoDisposeCheck();
            DoInitializationCheck();
            if (string.IsNullOrEmpty(applicationFileNameWithPath))
            {
                ThrowHelper.ThrowArgumentNullException("applicationFileNameWithPath");
            }
            if (string.IsNullOrEmpty(registeredName))
            {
                ThrowHelper.ThrowArgumentNullException("registeredName");
            }

            bool changed = false;

            // First of all, check the application is already authorized;
            if (!IsApplicationEnabled(applicationFileNameWithPath))
            {
                // Retrieve the authorized application collection
                INetFwAuthorizedApplications firewallApplications = mFirewallProfile.AuthorizedApplications;
                if (firewallApplications == null)
                {
                    throw new FirewallException("Failed to get authorized applications.");
                }

                // Create an instance of an authorized application
                Type firewallApplicationType = Type.GetTypeFromCLSID(new Guid("{EC9846B3-2762-4A6B-A214-6ACB603462D2}"));

                INetFwAuthorizedApplication firewallApplication = (INetFwAuthorizedApplication)Activator.CreateInstance(firewallApplicationType);
                if (firewallApplication == null)
                {
                    throw new FirewallException("Failed to authorize application.");
                }

                // Set the process image file name
                firewallApplication.ProcessImageFileName = applicationFileNameWithPath;
                firewallApplication.Name = registeredName;

                try
                {
                    firewallApplications.Add(firewallApplication);
                    changed = true;
                }
                catch (Exception)
                {
                    throw new FirewallException("Failed to authorize application.");
                }
            }

            return(changed);
        }
コード例 #26
0
        private INetFwAuthorizedApplication _GetAuth(string title, string applicationPath)
        {
            // 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     = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            auth.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
            auth.Enabled   = true;

            return(auth);
        }
コード例 #27
0
        internal void AddAuthorizedApplication(string strName,
                                               string processImageFileName,
                                               NetFwTypeLib.NET_FW_SCOPE_ Scope)
        {
            INetFwAuthorizedApplication authorizedApplication
                = (INetFwAuthorizedApplication)Activator
                  .CreateInstance(Type.GetTypeFromProgID(
                                      "HNetCfg.FwAuthorizedApplication"));

            authorizedApplication.Name    = strName;
            authorizedApplication.Scope   = Scope;
            authorizedApplication.Enabled = true;
            authorizedApplication.ProcessImageFileName = processImageFileName;
            firewallManager.LocalPolicy.CurrentProfile
            .AuthorizedApplications.Add(authorizedApplication);
        }
コード例 #28
0
        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
            try
            {
                INetFwMgr     mgr     = (INetFwMgr) new NetFwMgr();
                INetFwProfile profile = mgr.LocalPolicy.CurrentProfile;
                string        winDir  = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
                winDir = winDir.Substring(0, winDir.LastIndexOf(Path.DirectorySeparatorChar));

                INetFwAuthorizedApplication fwApp = (INetFwAuthorizedApplication) new NetFwAuthorizedApplication();
                fwApp.Name = "Media Center Extensibility Host";
                fwApp.ProcessImageFileName = winDir + @"\ehome\ehexthost.exe";
                fwApp.Enabled         = true;
                fwApp.IpVersion       = IPVersion.IPAny;
                fwApp.Scope           = Scope.Subnet;
                fwApp.RemoteAddresses = "*";

                profile.AuthorizedApplications.Add(fwApp);
            }
            catch (Exception ex)
            {
                throw new InstallException("Error during firewall registration of ehexthost.exe", ex);
            }

            try
            {
                INetFwMgr     mgr     = (INetFwMgr) new NetFwMgr();
                INetFwProfile profile = mgr.LocalPolicy.CurrentProfile;
                string        winDir  = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
                winDir = winDir.Substring(0, winDir.LastIndexOf(Path.DirectorySeparatorChar));

                INetFwAuthorizedApplication fwApp = (INetFwAuthorizedApplication) new NetFwAuthorizedApplication();
                fwApp.Name = "Media Center Media Status Aggregator Service";
                fwApp.ProcessImageFileName = winDir + @"\ehome\ehmsas.exe";
                fwApp.Enabled         = true;
                fwApp.IpVersion       = IPVersion.IPAny;
                fwApp.Scope           = Scope.Subnet;
                fwApp.RemoteAddresses = "*";

                profile.AuthorizedApplications.Add(fwApp);
            }
            catch (Exception ex)
            {
                throw new InstallException("Error during firewall registration of ehmsas.exe", ex);
            }
        }
コード例 #29
0
        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)
            {
                Logger.error(ex.ToString());
            }
            return(result);
        }
コード例 #30
0
        /// <summary>
        /// アプリケーションを指定してファイアウォールを通過させる。
        /// </summary>
        /// <param name="title"></param>
        /// <param name="filePath"></param>
        static public void AuthorizeApplication(string title, string filePath)
        {
            try
            {
                Type type = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication");
                INetFwAuthorizedApplication fwAuth = (INetFwAuthorizedApplication)Activator.CreateInstance(type);
                fwAuth.Name = title;
                fwAuth.ProcessImageFileName = Path.GetFullPath(filePath);
                fwAuth.Scope     = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
                fwAuth.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
                fwAuth.Enabled   = true;

                INetFwMgr manager = GetFirewallManager();
                manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(fwAuth);
            }
            catch (System.Exception)
            {
            }
        }