Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.40/5 (2 votes)
See more:
hi.I have this code for filtering in firewall, but dont action on packets !! help me please
{
    class IpPacketFilter
    {
        [DllImport("iphlpapi.dll", EntryPoint = "PfBindInterfaceToIPAddress")]
        public static extern int PfBindInterfaceToIPAddress(IntPtr Interface_handle, PFADDRESSTYPE pfatType, ref int ip_address);
          [DllImport("iphlpapi.dll", EntryPoint = "PfCreateInterface")]
        public static extern int PfCreateInterface(int dwName, PFFORWARD_ACTION inAction, PFFORWARD_ACTION outAction, bool UseLog, bool MustBeUnique, ref IntPtr ppInterface); 
        //////    //// 
        [DllImport("iphlpapi.dll", EntryPoint = "PfAddFiltersToInterface")] 
        public static extern int PfAddFiltersToInterface( 
            IntPtr interface_handle,          
            int cInFilters,               
            [MarshalAsAttribute(UnmanagedType.Struct)]     
            ref PPF_FILTER_DESCRIPTOR pfiltIn,        
            int cOutFilters,                        
            [MarshalAsAttribute(UnmanagedType.Struct)]     
            ref PPF_FILTER_DESCRIPTOR pfiltOut,            
            [MarshalAsAttribute(UnmanagedType.Struct)]     
            ref PPF_FILTER_DESCRIPTOR pfHandle        
            );
    } 
    public unsafe struct PPF_FILTER_DESCRIPTOR
    {  
        public FILTER_FLAGS dwFilterFlags;
        public int dwRule;
        public PFADDRESSTYPE pfatType;
        public int* SrcAddr;
        public int* SrcMask; 
        public int* DstAddr;  
        public int* DstMask;
        public PROTOCOL dwProtocol;
        public int fLateBound; 
        public int wSrcPort;   
        public int wDstPort;  
        public int wSrcPortHighRange; 
        public int wDstPortHighRange;
    }
    public enum PFFORWARD_ACTION : int
    {  
        PF_ACTION_FORWARD = 0,  
        PF_ACTION_DROP
    }
    public enum PFADDRESSTYPE : int
    {    
        PF_IPV4, 
        PF_IPV6
    }
    public  enum PROTOCOL : int
    {    
        ANY = 0x00,  
        ICMP = 0x01, 
        TCP = 0x06,   
        UDP = 0x11
    }
    public  enum FILTER_FLAGS : int
    {  
        FD_FLAGS = 0x1
    }
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Net;

namespace ConsoleApplication1
{
    
    class Program
    {
        internal const int FALSE = 0;
        internal const int TRUE = 1;
        static void Main(string[] args)
        {
            string[] hostsToBlock = new string[2]; 
            hostsToBlock[0] = "192.168.0.2,255.255.255.0,0";  
            //blocks all traffic on any port to/from 67.77.87.97   
            hostsToBlock[1] = "0.0.0.0,0.0.0.0,29000";   
            //blocks all traffic on port 29000, in and out   
            StartPacketFilter(hostsToBlock);
            Console.ReadLine();
           
         }
        internal static int lIpFromString(string sIpAddress) 
        { 
            int lIp = 0;
            try 
            {
                string[] octets = sIpAddress.Split(new string[] { "." }, StringSplitOptions.None);
                if (octets.Length != 4)   
                    return 0;
                for (int i = 0; i < 4; i++)   
                    lIp |= (int.Parse(octets[i]) << (i * 8));
            } 
            catch 
            { 
            }
            return lIp;
        }
        internal static string[] GetLocalIpAddresses()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            string[] localIpAddresses = new string[host.AddressList.Length];
            for (int i = 0; i < host.AddressList.Length; i++) 
            { 
                localIpAddresses[i] = host.AddressList[i].ToString();
            }
                 return localIpAddresses; 
        }
        internal static bool StartPacketFilter(string[] hosts)
        {  
            string[] localIpAddresses = GetLocalIpAddresses();
            //Console.WriteLine(localIpAddresses);
            if (localIpAddresses == null)
                return false; 
            foreach (string localAddress in localIpAddresses)
            {
               
                int result; 
                IntPtr interfaceHandle = new IntPtr();   
                //convert the string IP to an unsigned int for p/invoke
                int lLocalIp = lIpFromString(localAddress);
                 //create a filter interface in the tcp/ip stack 
                result = IpPacketFilter.PfCreateInterface(0, PFFORWARD_ACTION.PF_ACTION_FORWARD, PFFORWARD_ACTION.PF_ACTION_FORWARD, false, true, ref interfaceHandle);
                if (result != 0)
                    return false; 
                //bind interface to an ip address 
                result = IpPacketFilter.PfBindInterfaceToIPAddress(interfaceHandle, PFADDRESSTYPE.PF_IPV4, ref lLocalIp);    
                if (result != 0)
                    return false; 
                foreach (string targetHost in hosts)   
                {        
                    ////IntPtr filterHandle = new IntPtr();  
                    string[] hostDetail = targetHost.Split(new string[] { "," }, StringSplitOptions.None);
                   
                    if (hostDetail != null && hostDetail.Length == 3)  
                    {       
                        //build the filter structure  
                        PPF_FILTER_DESCRIPTOR filter = new PPF_FILTER_DESCRIPTOR();   
                        filter.dwFilterFlags = FILTER_FLAGS.FD_FLAGS; 
                        filter.dwRule = FALSE;             
                        filter.pfatType = PFADDRESSTYPE.PF_IPV4;     
                        filter.dwProtocol = PROTOCOL.TCP;        
                        int iSrcAddr = lLocalIp;              
                        int iSrcMask = lIpFromString("255.255.255.0");
                        filter.wSrcPort = 0;  
                        filter.wSrcPortHighRange = 0;         
                        int iDstAddr = lIpFromString(hostDetail[0]);    
                        int iDstMask = lIpFromString(hostDetail[1]); 
                        filter.wDstPort = int.Parse(hostDetail[2]);       
                        filter.wDstPortHighRange = int.Parse(hostDetail[2]); 
 
                        unsafe          
                        {         
                            filter.SrcAddr = &iSrcAddr;   
                            filter.DstAddr = &iDstAddr;    
                            filter.SrcMask = &iSrcMask; 
                            filter.DstMask = &iDstMask;  
                        }             
                        // add filter to interface (both inbound and outbound)   
                        result = IpPacketFilter.PfAddFiltersToInterface(interfaceHandle, 1, ref filter, 1, ref filter, ref filter);
                        
                        if (result != 0) 
                            return false;
                        
                    }
                  
                }
                
            }
           
            return true;
        }
    }
}
Posted
Updated 31-Jul-11 7:36am
v2
Comments
Herman<T>.Instance 31-Jul-11 15:50pm    
what is your problem?
walterhevedeich 31-Jul-11 20:23pm    
Describe your issue in more detail.

You should check the result of StartPacketFilter. My guess is (if your symptom is that nothing is being filtered) is that one of your native calls is being given the wrong argument, and your filter just isn't being registered.
 
Share this answer
 
Comments
elham65_tansa 4-Aug-11 10:15am    
I've looked at all the functions and the output is no problem
And all applications will run without error but it does not filter?
However, the drop in value against the defualt action we will drop the data.
But why, when I forward it to the desired IP does not drop?
elham65_tansa 20-Aug-11 4:53am    
please help me , i need this code!!!!!!!
lotfaan age mishe yeki in firewall o be manam ye tozih bede shadidan niazmandam !!! mamnon misham
salar_0007@yahoo.com
 
Share this answer
 
I've used this code
However, IP will have to drop it forward?
pleas help me
i need it.
 
Share this answer
 
Comments
salar_master 3-Aug-11 18:28pm    
elham65_tansa : slm , age mishe mikhastam piadesazi in firewallo baram tozih bedid mamnon misham bem javab bedid kheili niaz daram !! salar_0007@yahoo.com mamnon
elham65_tansa 4-Aug-11 10:19am    
salam baraie neveshtan yek firewall bayad az API haie windows estefade kard ke yek seri tavabe hastand ke dar dakhel filehaie DLL neveshte shodan
baraye in proje az yek DLL be esme iphlpapi estefade mikonim .va tavabe morde nazaremono to yeki az class haie proje be kar mibarim va khode file DLLro to proje import mikonim
salar_master 4-Aug-11 19:03pm    
merc azinke javab dadid vali azatoon mikham age lotf konid ye time ee ke online hastid begid ke betoonam soaalamo bishtar beporsam man vaghean vaghtam kame vase in proje !!
mamnon misham age ye komaki dar in rastaa konid!!
salar_0007 in yhoo id mane! ba tashakor az shoma doste aziz.
salar_master 6-Aug-11 5:13am    
montazere javabe shoma hastaam?!!!! plzzzzz

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900