Firewall settings C#

Walter Grimm | Q-Auditors 1 Reputation point
2022-02-22T08:21:15.13+00:00

I have checked the web and ran multiple test to update windows firewall settings. there are samples with powershell, but I would like to use code C# to manipulate the firewall rules.

After hours I could not come up with a solution to UPDATE a firewall setting (I can enumerate them in C#, some articles show how to add or delete them)

BUT - I cannot find any way to UPDATE the existing rules , especially to disable/enable roles.

Can anybody please help me with this,

thanx

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,842 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 84,471 Reputation points
    2022-02-22T09:12:23.707+00:00

    This test works for me on Windows 10 21H1

    I list the rules and disable a random existing one on my PC ("Microsoft Office Outlook" Inbound) (I checked the result with wf.msc)

    Must be Admin (requireAdministrator in Manifest) to update a Rule

    Guid CLSID_NetFwPolicy2 = new Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD");
    Type NetFwPolicy2Type = Type.GetTypeFromCLSID(CLSID_NetFwPolicy2, true);
    object NetFwPolicy2 = Activator.CreateInstance(NetFwPolicy2Type);
    INetFwPolicy2 pNetFwPolicy2 = (INetFwPolicy2)NetFwPolicy2;
    
    INetFwRules pFwRules;
    hr = pNetFwPolicy2.get_Rules(out pFwRules);
    int nRuleCount = 0;
    hr = pFwRules.get_Count(out nRuleCount);
    
    IntPtr pEnumerator;
    hr = pFwRules.get__NewEnum(out pEnumerator);
    IEnumerator pEnum = Marshal.GetObjectForIUnknown(pEnumerator) as IEnumerator;
    int nIndex = 1;
    while (pEnum.MoveNext())
    {
        INetFwRule pNetFwRule = (INetFwRule)pEnum.Current;
        string sRuleName;
        hr = pNetFwRule.get_Name(out sRuleName);
        bool bEnabled = false;
        hr = pNetFwRule.get_Enabled(out bEnabled);
        NET_FW_RULE_DIRECTION nDirection;
        hr = pNetFwRule.get_Direction(out nDirection);
        Console.WriteLine("Rule : {0} - Direction : {1} - Enabled : {2}", sRuleName, nDirection.ToString(), bEnabled.ToString());
        if (sRuleName == "Microsoft Office Outlook")
        {                    
            if (nDirection == NET_FW_RULE_DIRECTION.NET_FW_RULE_DIR_IN)
            {
                // Must be Admin
                hr = pNetFwRule.put_Enabled(false);
                if (hr == HRESULT.S_OK)
                {
                    Console.WriteLine("\n\t *** Rule : {0} (inbound) has been disabled\n", sRuleName);
                }
            }
        }
        nIndex++;               
    }
    

    Declarations :

        public enum HRESULT : int                                                                                                                                                                                                                         
        {                                                                                                                                                                                                                                                
            S_OK = 0,                                                                                                                                                                                                                                    
            S_FALSE = 1,                                                                                                                                                                                                                                 
            E_NOINTERFACE = unchecked((int)0x80004002),                                                                                                                                                                                                  
            E_NOTIMPL = unchecked((int)0x80004001),                                                                                                                                                                                                      
            E_FAIL = unchecked((int)0x80004005)                                                                                                                                                                                                          
        }                                                                                                                                                                                                                                                
    
        public enum NET_FW_PROFILE_TYPE2 : int                                                                                                                                                                                                           
        {                                                                                                                                                                                                                                                
            NET_FW_PROFILE2_DOMAIN = 0x1,                                                                                                                                                                                                                
            NET_FW_PROFILE2_PRIVATE = 0x2,                                                                                                                                                                                                               
            NET_FW_PROFILE2_PUBLIC = 0x4,                                                                                                                                                                                                                
            NET_FW_PROFILE2_ALL = 0x7fffffff                                                                                                                                                                                                             
        }                                                                                                                                                                                                                                                
    
        public enum NET_FW_IP_PROTOCOL : int                                                                                                                                                                                                             
        {                                                                                                                                                                                                                                                
            NET_FW_IP_PROTOCOL_TCP = 6,                                                                                                                                                                                                                  
            NET_FW_IP_PROTOCOL_UDP = 17,                                                                                                                                                                                                                 
            NET_FW_IP_PROTOCOL_ANY = 256                                                                                                                                                                                                                 
        }                                                                                                                                                                                                                                                
    
        public enum NET_FW_RULE_DIRECTION                                                                                                                                                                                                                
        {                                                                                                                                                                                                                                                
            NET_FW_RULE_DIR_IN = 1,                                                                                                                                                                                                                      
            NET_FW_RULE_DIR_OUT = (NET_FW_RULE_DIR_IN + 1),                                                                                                                                                                                              
            NET_FW_RULE_DIR_MAX = (NET_FW_RULE_DIR_OUT + 1)                                                                                                                                                                                              
        }                                                                                                                                                                                                                                                
    
        public enum NET_FW_ACTION                                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                
            NET_FW_ACTION_BLOCK = 0,                                                                                                                                                                                                                     
            NET_FW_ACTION_ALLOW = (NET_FW_ACTION_BLOCK + 1),                                                                                                                                                                                             
            NET_FW_ACTION_MAX = (NET_FW_ACTION_ALLOW + 1)                                                                                                                                                                                                
        }                                                                                                                                                                                                                                                
    
        public enum NET_FW_MODIFY_STATE                                                                                                                                                                                                                  
        {                                                                                                                                                                                                                                                
            NET_FW_MODIFY_STATE_OK = 0,                                                                                                                                                                                                                  
            NET_FW_MODIFY_STATE_GP_OVERRIDE = (NET_FW_MODIFY_STATE_OK + 1),                                                                                                                                                                              
            NET_FW_MODIFY_STATE_INBOUND_BLOCKED = (NET_FW_MODIFY_STATE_GP_OVERRIDE + 1)                                                                                                                                                                  
        }                                                                                                                                                                                                                                                
    
        [ComImport]                                                                                                                                                                                                                                      
        [Guid("9C4C6277-5027-441E-AFAE-CA1F542DA009")]                                                                                                                                                                                                   
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]                                                                                                                                                                                            
        public interface INetFwRules                                                                                                                                                                                                                     
        {                                                                                                                                                                                                                                                
            #region <IDispatch>                                                                                                                                                                                                                          
            int GetTypeInfoCount();                                                                                                                                                                                                                      
            [return: MarshalAs(UnmanagedType.Interface)]                                                                                                                                                                                                 
            IntPtr GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid);                                                                                                                                
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames,                                                                                           
                [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);                                                                                                                                     
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT Invoke(int dispIdMember, [In] ref Guid riid, [In, MarshalAs(UnmanagedType.U4)] int lcid, [In, MarshalAs(UnmanagedType.U4)] int dwFlags,                                                                                              
                [Out, In] System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, [Out] out object pVarResult, [Out, In] System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo, [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] pArgErr);
            #endregion                                                                                                                                                                                                                                   
    
            HRESULT get_Count(out int count);                                                                                                                                                                                                            
            HRESULT Add(INetFwRule rule);                                                                                                                                                                                                                
            HRESULT Remove(StringBuilder name);                                                                                                                                                                                                          
            HRESULT Item(string name, out INetFwRule rule);                                                                                                                                                                                              
            //HRESULT get__NewEnum([MarshalAs(UnmanagedType.IUnknown)] out object newEnum);                                                                                                                                                              
            HRESULT get__NewEnum(out IntPtr newEnum);                                                                                                                                                                                                    
        }                                                                                                                                                                                                                                                
    
        [ComImport]                                                                                                                                                                                                                                      
        [Guid("8267BBE3-F890-491C-B7B6-2DB1EF0E5D2B")]                                                                                                                                                                                                   
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]                                                                                                                                                                                            
        public interface INetFwServiceRestriction                                                                                                                                                                                                        
        {                                                                                                                                                                                                                                                
            #region <IDispatch>                                                                                                                                                                                                                          
            int GetTypeInfoCount();                                                                                                                                                                                                                      
            [return: MarshalAs(UnmanagedType.Interface)]                                                                                                                                                                                                 
            IntPtr GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid);                                                                                                                                
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames,                                                                                           
                [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);                                                                                                                                     
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT Invoke(int dispIdMember, [In] ref Guid riid, [In, MarshalAs(UnmanagedType.U4)] int lcid, [In, MarshalAs(UnmanagedType.U4)] int dwFlags,                                                                                              
                [Out, In] System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, [Out] out object pVarResult, [Out, In] System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo, [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] pArgErr);
            #endregion                                                                                                                                                                                                                                   
    
            HRESULT RestrictService(string serviceName, string appName, [MarshalAs(UnmanagedType.VariantBool)] bool restrictService, [MarshalAs(UnmanagedType.VariantBool)] bool serviceSidRestricted);                                                  
            HRESULT ServiceRestricted(string serviceName, string appName, [MarshalAs(UnmanagedType.VariantBool)] out bool serviceRestricted);                                                                                                            
            HRESULT get_Rules(out INetFwRules rules);                                                                                                                                                                                                    
        }                                                                                                                                                                                                                                                
    
        [ComImport]                                                                                                                                                                                                                                      
        [Guid("AF230D27-BABA-4E42-ACED-F524F22CFCE2")]                                                                                                                                                                                                   
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]                                                                                                                                                                                            
        public interface INetFwRule                                                                                                                                                                                                                      
        {                                                                                                                                                                                                                                                
            #region <IDispatch>                                                                                                                                                                                                                          
            int GetTypeInfoCount();                                                                                                                                                                                                                      
            [return: MarshalAs(UnmanagedType.Interface)]                                                                                                                                                                                                 
            IntPtr GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid);                                                                                                                                
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames,                                                                                           
                [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);                                                                                                                                     
            [PreserveSig]                                                                                                                                                                                                                                
            HRESULT Invoke(int dispIdMember, [In] ref Guid riid, [In, MarshalAs(UnmanagedType.U4)] int lcid, [In, MarshalAs(UnmanagedType.U4)] int dwFlags,                                                                                              
                [Out, In] System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, [Out] out object pVarResult, [Out, In] System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo, [Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] pArgErr);
            #endregion                                                                                                                                                                                                                                   
    
            HRESULT get_Name(out string name);                                                                                                                                                                                                           
            HRESULT put_Name(string name);                                                                                                                                                                                                               
            HRESULT get_Description(out string desc);                                                                                                                                                                                                    
            HRESULT put_Description(string desc);                                                                                                                                                                                                        
            HRESULT get_ApplicationName(out string imageFileName);                                                                                                                                                                                       
            HRESULT put_ApplicationName(string imageFileName);                                                                                                                                                                                           
            HRESULT get_ServiceName(out string serviceName);                                                                                                                                                                                             
            HRESULT put_ServiceName(string serviceName);                                                                                                                                                                                                 
            HRESULT get_Protocol(out NET_FW_IP_PROTOCOL protocol);                                                                                                                                                                                       
            HRESULT put_Protocol(NET_FW_IP_PROTOCOL protocol);                                                                                                                                                                                           
            HRESULT get_LocalPorts(out string portNumbers);                                                                                                                                                                                              
            HRESULT put_LocalPorts(string portNumbers);                                                                                                                                                                                                  
            HRESULT get_RemotePorts(out string portNumbers);                                                                                                                                                                                             
            HRESULT put_RemotePorts(string portNumbers);                                                                                                                                                                                                 
            HRESULT get_LocalAddresses(out string localAddrs);                                                                                                                                                                                           
            HRESULT put_LocalAddresses(string localAddrs);                                                                                                                                                                                               
            HRESULT get_RemoteAddresses(out string remoteAddrs);                                                                                                                                                                                         
            HRESULT put_RemoteAddresses(string remoteAddrs);                                                                                                                                                                                             
            HRESULT get_IcmpTypesAndCodes(out string icmpTypesAndCodes);                                                                                                                                                                                 
            HRESULT put_IcmpTypesAndCodes(string icmpTypesAndCodes);                                                                                                                                                                                     
            HRESULT get_Direction(out NET_FW_RULE_DIRECTION remoteAddrs);                                                                                                                                                                                
            HRESULT put_Direction(NET_FW_RULE_DIRECTION remoteAddrs);                                                                                                                                                                                    
    
            // VARIANT                                                                                                                                                                                                                                   
            HRESULT get_Interfaces(out IntPtr interfaces);                                                                                                                                                                                               
            HRESULT put_Interfaces(IntPtr interfaces);                                                                                                                                                                      
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.