在Vista中编程控制防火墙设定(C#)

 
     在编程控制防火墙前先要有个前提,就是你必须是管理员权限, 这样本例的程序才能用"Run as administrator"的方式运行,并成功修改. 如果你本身就是用Administrator这个用户登录的话,直接运行就行了. 建议最好在这个用户下来调试程序.
     本程序只是个初始的例子,里面的功能只开发了一部分,各位有兴趣的话可以继续深入运用. 像Vista的防火墙就比较Bt,除了基本设定外,在"Control Panel\Administrative Tools\Windows Firewall with Advanced Security" 还有高级设定,好像用程序都可控制.
    FireWallManager 程序主要功能有
      1. public void FireWallTrigger( bool enable )  //开关防火墙. 貌似在Vista里面有问题,XP sp2好像可以. 但是用INetFwPolicy2.set_FirewallEnabled的方法的话,Vista也能搞定.
      2.  public void FireWallService( string name, bool enable )  //开关防火墙服务程序,一般里面的 File and Printer Sharing 服务比较有用.
      3.  public bool AddPort( string portName, int portNumber, string protocol )   // 开启一个端口.
      4.  public bool RemovePort( int portNumber, string protocol )          //删除开启的端口
      5.  public bool AddAplication( string discriptionName, string fileName )   //开启放行应用程序
      6.  public bool RemoveApplication( string fileName )         // 关闭放行的应用程序.

里面还有个 protected Object getInstance( String typeName ) 本来是用CLSID来实例化那些接口的,后来发现ProgID其实更简单,不需要查,里面有个规律,只需把接口的INet删掉就是ProgID了. 如 INetFwOpenPort port = ( INetFwOpenPort )Activator.CreateInstance( Type.GetTypeFromProgID( "HNetCfg.FwOpenPort" ) ); 中 INetFwOpenPort 与 FwOpenPort.
     首先,创建一个Console程序,在程序中添加引用,在COM对象中找到"NetFwTypeLib" ,添加即可. 防火墙主要是靠这个对象操作的. 貌似不止Vista, Xp也是一样的。核心程序如下:
using System;
using System.Collections.Generic;
using System.Text;
using NetFwTypeLib;

namespace FirewallManager
{
    
class FwManager
    
{
        
private INetFwMgr NetFwMgr;
        
private INetFwProfile NetFwProfile;
        
private INetFwPolicy2 NetFwPolicy2;  //this interface contains lots of usefull functions.

        
public FwManager()
        
{
            
//Create Com Object
            
//Type NetFwMgrType = Type.GetTypeFromCLSID( new Guid( "{304CE942-6E39-40D8-943A-B913C40C9CD4}" ) );
            Type NetFwMgrType = Type.GetTypeFromProgID( "HNetCfg.FwMgr" );
            
object NetFwMgrObject = Activator.CreateInstance( NetFwMgrType );
            NetFwMgr 
= ( INetFwMgr )NetFwMgrObject;
            NetFwProfile 
= NetFwMgr.LocalPolicy.CurrentProfile;

            Type NetFwPolicy2Type 
= Type.GetTypeFromProgID( "HNetCfg.FwPolicy2" );
            
object NetFwPolicy2Object = System.Activator.CreateInstance( NetFwPolicy2Type );
            NetFwPolicy2 
= ( INetFwPolicy2 )NetFwPolicy2Object;
        }


        
public void ShowInfo()
        
{
            
switch( NetFwProfile.Type )
            
{
                
case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_DOMAIN:
                    Console.WriteLine( 
"Network Profile Type1: " + "Domain" );
                    
break;
                
case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD:
                    Console.WriteLine( 
"Network Profile Type1: " + "Standard" );
                    
break;
                
case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_CURRENT:
                    Console.WriteLine( 
"Network Profile Type1: " + "Current" );
                    
break;
                
case NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_TYPE_MAX:
                    Console.WriteLine( 
"Network Profile Type1: " + "Max" );
                    
break;
            }

            
switch( ( NET_FW_PROFILE_TYPE2_ )NetFwPolicy2.CurrentProfileTypes )
            
{
                
case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN:
                    Console.WriteLine( 
"Network Profile Type2: " + "Domain" );
                    
break;
                
case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE:
                    Console.WriteLine( 
"Network Profile Type2: " + "Private" );
                    
break;
                
case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC:
                    Console.WriteLine( 
"Network Profile Type2: " + "Public" );
                    
break;
                
case NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_ALL:
                    Console.WriteLine( 
"Network Profile Type2: " + "All" );
                    
break;
            }

            Console.WriteLine( 
"Firewall Enabled: " + NetFwProfile.FirewallEnabled );
            Console.WriteLine( 
"Exceptions Not Allowed: " + NetFwProfile.ExceptionsNotAllowed );
            Console.WriteLine( 
"Notifications Disabled: " + NetFwProfile.NotificationsDisabled );
            
//Console.WriteLine("UnicastResponsestoMulticastBroadcastDisabled: " + NetFwProfile.UnicastResponsestoMulticastBroadcastDisabled);
            
//Remote Admin
            INetFwRemoteAdminSettings RASettings = NetFwProfile.RemoteAdminSettings;
            Console.WriteLine( 
"Remote Administration Enabled: " + RASettings.Enabled );
            
switch( RASettings.IpVersion )
            
{
                
case NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4:
                    Console.WriteLine( 
"Remote Administration IP Version: V4" );
                    
break;
                
case NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V6:
                    Console.WriteLine( 
"Remote Administration IP Version: V6" );
                    
break;
                
case NET_FW_IP_VERSION_.NET_FW_IP_VERSION_MAX:
                    Console.WriteLine( 
"Remote Administration IP Version: MAX" );
                    
break;
                
case NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY:
                    Console.WriteLine( 
"Remote Administration IP Version: ANY" );
                    
break;
            }

            
switch( RASettings.Scope )
            
{
                
case NET_FW_SCOPE_.NET_FW_SCOPE_ALL:
                    Console.WriteLine( 
"Remote Administration Scope: ALL" );
                    
break;
                
case NET_FW_SCOPE_.NET_FW_SCOPE_CUSTOM:
                    Console.WriteLine( 
"Remote Administration Scope: Custom" );
                    
break;
                
case NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET:
                    Console.WriteLine( 
"Remote Administration Scope: Local Subnet" );
                    
break;
                
case NET_FW_SCOPE_.NET_FW_SCOPE_MAX:
                    Console.WriteLine( 
"Remote Administration Scope: MAX" );
                    
break;
            }

            
// ICMP
            INetFwIcmpSettings icmpSettings = NetFwProfile.IcmpSettings;
            Console.WriteLine( 
"ICMP Settings:" );
            Console.WriteLine( 
"  AllowOutboundDestinationUnreachable: " + icmpSettings.AllowOutboundDestinationUnreachable );
            Console.WriteLine( 
"  AllowOutboundSourceQuench:           " + icmpSettings.AllowOutboundSourceQuench );
            Console.WriteLine( 
"  AllowRedirect:                       " + icmpSettings.AllowRedirect );
            Console.WriteLine( 
"  AllowInboundEchoRequest:             " + icmpSettings.AllowInboundEchoRequest );
            Console.WriteLine( 
"  AllowInboundRouterRequest:           " + icmpSettings.AllowInboundRouterRequest );
            Console.WriteLine( 
"  AllowOutboundTimeExceeded:           " + icmpSettings.AllowOutboundTimeExceeded );
            Console.WriteLine( 
"  AllowOutboundParameterProblem:       " + icmpSettings.AllowOutboundParameterProblem );
            Console.WriteLine( 
"  AllowInboundTimestampRequest:        " + icmpSettings.AllowInboundTimestampRequest );
            Console.WriteLine( 
"  AllowInboundMaskRequest:             " + icmpSettings.AllowInboundMaskRequest );
            
// Gloabal Open ports
            foreach( INetFwOpenPort port in NetFwProfile.GloballyOpenPorts )
            
{
                Console.WriteLine( 
"Open port: " + port.Name + ":" + port.Port + "" + port.Protocol + " " + port.Enabled );
            }

            
// Services
            foreach( INetFwService serv in NetFwProfile.Services )
            
{
                Console.WriteLine( 
"Service: " + serv.Name + "" + serv.Enabled );
            }

            
// Autorised Applications
            foreach( INetFwAuthorizedApplication app in NetFwProfile.AuthorizedApplications )
            
{
                Console.WriteLine( 
"AuthorizedApplication: " + app.Name + "" + app.Enabled );
            }

            Console.WriteLine();
        }


        
public void FireWallTrigger( bool enable )
        
{
            
try
            
{
                NetFwProfile.FirewallEnabled 
= enable;
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

            
//try
            
//{
            
//    NetFwPolicy2.set_FirewallEnabled( NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, enable );
            
//}
            
//catch( Exception e )
            
//{
            
//    Console.WriteLine( e.Message );
            
//}
            Console.WriteLine( "FireWall Enabled: " + NetFwProfile.FirewallEnabled );
        }


        
public bool FireWallState()
        
{
            
return NetFwProfile.FirewallEnabled;
        }


        
public void FireWallService( string name, bool enable )
        
{
            
try
            
{
                
foreach( INetFwService serv in NetFwProfile.Services )
                
{
                    
if( serv.Name.ToUpper() == name.ToUpper() )
                    
{
                        serv.Enabled 
= enable;
                        Console.WriteLine( 
"Service: " + serv.Name + "" + serv.Enabled );
                        
return;
                    }

                }

                Console.WriteLine( 
"The service '{0}' does not exist!", name );
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

        }


        
private NET_FW_IP_PROTOCOL_ GetProtocol( string protocol )
        
{
            NET_FW_IP_PROTOCOL_ prot;
            
if( protocol.ToUpper() == "TCP" )
                prot 
= NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            
else if( protocol.ToUpper() == "UDP" )
                prot 
= NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
            
else
                prot 
= NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            
return prot;
        }


        
public bool AddPort( string portName, int portNumber, string protocol )
        
{
            
try
            
{
                INetFwOpenPort port 
= ( INetFwOpenPort )Activator.CreateInstance( 
                    Type.GetTypeFromProgID( 
"HNetCfg.FwOpenPort" ) 
                    );
                port.Name 
= portName;
                port.Port 
= portNumber;
                port.Protocol 
= GetProtocol( protocol );
                port.Enabled 
= true;               
                NetFwProfile.GloballyOpenPorts.Add( port );
                
return true;
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

            
return false;
        }


        
public bool RemovePort( int portNumber, string protocol )
        
{
            
try
            
{
                NetFwProfile.GloballyOpenPorts.Remove( portNumber, GetProtocol( protocol ) );
                
return true;
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

            
return false;
        }


        
public bool AddAplication( string discriptionName, string fileName )
        
{
            
try
            
{
                INetFwAuthorizedApplication app 
= ( INetFwAuthorizedApplication )Activator.CreateInstance( 
                    Type.GetTypeFromProgID( 
"HNetCfg.FwAuthorizedApplication" ) 
                    );
                app.Name 
= discriptionName;
                app.ProcessImageFileName 
= fileName;
                app.Enabled 
= true;
                NetFwProfile.AuthorizedApplications.Add( app );
                
return true;
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

            
return false;
        }


        
public bool RemoveApplication( string fileName )
        
{
            
try
            
{
                NetFwProfile.AuthorizedApplications.Remove( fileName );
                
return true;
            }

            
catch( Exception e )
            
{
                Console.WriteLine( e.Message );
            }

            
return false;
        }


        
protected Object getInstance( String typeName )
        
{
            
if( typeName == "INetFwMgr" )
            
{
                Type type 
= Type.GetTypeFromCLSID( new Guid( "{304CE942-6E39-40D8-943A-B913C40C9CD4}" ) );
                
return Activator.CreateInstance( type );
            }

            
else if( typeName == "INetAuthApp" )
            
{
                Type type 
= Type.GetTypeFromCLSID( new Guid( "{EC9846B3-2762-4A6B-A214-6ACB603462D2}" ) );
                
return Activator.CreateInstance( type );
            }

            
else if( typeName == "INetOpenPort" )
            
{
                Type type 
= Type.GetTypeFromCLSID( new Guid( "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}" ) );
                
return Activator.CreateInstance( type );
            }

            
else
                
return null;
        }

    }

}
程序代码如下:
https://files.cnblogs.com/phytan/FirewallManager.rar

最后,再给一个更简单的操作防火墙的方法,其实Vista中用netsh这个命令行程序就可以操作防火墙了。

netsh firewall set service all enable  就可以开启所有服务,很简单。
netsh firewall add portopening TCP 12345 "Testaddport"  可以开启一个12345的TCP端口。
还有 netsh advfirewall 等,可以操作更多选项。

参考:
http://danielw.blog.de/2007/01/06/windows_firewall_configuration~1521163
http://www.codeproject.com/useritems/enable_disable_firewall.asp
http://www.codeproject.com/vb/net/WinNetConn.asp
http://www.codeproject.com/useritems/FirewallSetupAction.asp
http://www.codeproject.com/w2k/WinXPSP2Firewall.asp
http://msdn2.microsoft.com/en-us/library/aa365309.aspx
http://www.cnblogs.com/appleseeker/archive/2007/07/10/812907.html

原文地址:https://www.cnblogs.com/4kapple/p/1228318.html