NextPVR Forums
  • ______
  • Home
  • New Posts
  • Wiki
  • Members
  • Help
  • Search
  • Register
  • Login
  • Home
  • Wiki
  • Members
  • Help
  • Search
NextPVR Forums Public Developers v
« Previous 1 … 5 6 7 8 9 … 93 Next »
Any ideas about programming for Windows Firewall?

 
  • 0 Vote(s) - 0 Average
Any ideas about programming for Windows Firewall?
bgowland
Offline

Posting Freak

West Yorkshire, UK
Posts: 4,583
Threads: 384
Joined: Dec 2004
#1
2014-01-24, 08:58 PM
I'm trying to work out a way to add inbound port rules to Windows Firewall. It seems there are 2 APIs - the one introduced with XP SP2 and the "advanced" API added in Vista.

It seems rules created with the XP API approach would be valid for Vista and later but it is recommended to use the advanced API. One problem is the MS code samples for the XP API are in C++ and I'd rather use C# - another problem is the samples for the advanced can't be built in VS2010 on my XP machine because they need to reference a system dll (or a version of it) which only comes with Vista and later.

I thought about just using a shell to execute the netsh CLI using "netsh firewall" or "netsh advfirewall" commands depending on OS version but I've never been keen on executing a command-line program from within a .NET program.

Any thoughts / ideas gratefully received.

Cheers,
Brian
mvallevand
Online

Posting Freak

Ontario Canada
Posts: 52,766
Threads: 954
Joined: May 2006
#2
2014-01-24, 10:39 PM
I've used the NSIS installer to do this for me.

Martin
bgowland
Offline

Posting Freak

West Yorkshire, UK
Posts: 4,583
Threads: 384
Joined: Dec 2004
#3
2014-01-24, 11:12 PM
I was thinking of dynamic manipulation of firewall rules rather than at installation time. The problem comes if a user changes their preferred port(s) for a program but forgets to change the firewall rule(s).
whurlston
Offline

Posting Freak

Posts: 7,885
Threads: 102
Joined: Nov 2006
#4
2014-04-10, 05:26 AM
I missed this thread completely until now. If you are still looking:

Add Reference -> Browse ->
  • XP: C:\windows\system32\Hnetcfg.dll
  • Vista+: c:\windows\system32\FirewallApi.dll


Add Reference -> COM -> Type Libraries -> NetFwTypeLib


Reference: http://msdn.microsoft.com/en-us/library/...s.85).aspx

Sample using INetFwPolicy2 (Vista/Server2008+):

Here is the code I use on my web servers to download the list of IP addresses from blockreport.net and add them to a block list firewall rule (up to 10,000 ips per rule) with clearing the old rules first:

Code:
using NetFwTypeLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace BlockReport.Net
{
    class Program
    {
        static void Main(string[] args)
        {
            // Max number of IP addresses per firewall rule
            int batchCount = 10000;

            List<string> excluded = new List<string>(new string[] {
                // Add a list of addresses to exclude here because you don't ever want to block your own IPs. You can use CIDR notation
                "127.0.0.1",
                "192.168.1.0/24"
            });

            GzipEnabledWebClient wc = new GzipEnabledWebClient();
            string html = wc.DownloadString("http://www.blockreport.net/iplist.php");
            List<string> ipAddresses = new List<string>();
            MatchCollection matches = Regex.Matches(html,
@"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
            foreach (Match match in matches)
            {
                // This part is required because "074.126.45.13" (0 padded addresses) will cause an error.
                string[] parts = match.Value.Split('.');
                string address = string.Format("{0}.{1}.{2}.{3}", int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), int.Parse(parts[3]));
                
                // Add the address if it does not exist already or is not in the excluded list.
                if (!excluded.Contains(address) && !ipAddresses.Contains(address)) ipAddresses.Add(address);
            }
            ClearExisting();
            Create(ipAddresses, batchCount);
        }

        static void ClearExisting()
        {
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
            foreach (INetFwRule rule in firewallPolicy.Rules)
            {
                if (rule.Grouping == "BlockReport.net")
                {
                    string[] t = rule.RemoteAddresses.Split(',');
                    firewallPolicy.Rules.Remove(rule.Name);
                }
            }
        }

        static void Create(List<string> ipAddresses, int batchCount)
        {
            int batchNum = 1;
            List<string> ipBatch = new List<string>();
            while (ipAddresses.Count > 0)
            {
                while (ipBatch.Count < batchCount && ipAddresses.Count > 0)
                {
                    ipBatch.Add(ipAddresses[0]);
                    ipAddresses.RemoveAt(0);
                }

                INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
                INetFwRule newRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
                newRule.Name = string.Format("BlockReport.net IP List #{0:00}", batchNum);
                newRule.Description = "Block inbound traffic from from IP Addresses listed at http://www.blockreport.net/iplist.php";
                newRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
                
                // Uncomment the next line to specify ports to block.
                //newRule.LocalPorts = "25,110,143,587";

                newRule.RemoteAddresses = string.Join(",", ipBatch.ToArray());
                newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
                newRule.Enabled = true;
                newRule.Grouping = "BlockReport.net";
                newRule.Profiles = firewallPolicy.CurrentProfileTypes;
                newRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
                firewallPolicy.Rules.Add(newRule);

                batchNum++;
                ipBatch = new List<string>();
            }
        }
    }

    class GzipEnabledWebClient : WebClient
    {

        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            base.Headers.Add("Accept-Encoding", "gzip,deflate");
            return request;
        }
    }
}
bgowland
Offline

Posting Freak

West Yorkshire, UK
Posts: 4,583
Threads: 384
Joined: Dec 2004
#5
2014-04-10, 09:05 AM
Thanks for that. I had put it on a back burner as I hadn't found a solution I was completely happy with but it's still something I'd like to do. I'll have a play with your code example and see what happens.

Cheers,
Brian
« Next Oldest | Next Newest »

Users browsing this thread: 1 Guest(s)



Possibly Related Threads…
Thread Author Replies Views Last Post
  Windows FM Radio support in v5. mvallevand 125 25,862 2023-01-29, 08:13 PM
Last Post: mvallevand
  Problems with Windows UWP App spitefulgod 4 3,762 2016-12-15, 08:35 PM
Last Post: spitefulgod
  Windows Shortcuts ACTCMS 4 2,682 2012-03-24, 12:22 AM
Last Post: mvallevand
  Creating a Windows service McBainUK 8 3,331 2011-03-30, 03:29 AM
Last Post: mvallevand
  Using Windows file system shortcuts ACTCMS 0 1,776 2010-01-26, 11:45 PM
Last Post: ACTCMS
  Windows Media Connect - Storing stuff on a Home Server psycik 3 2,636 2009-09-29, 03:47 AM
Last Post: mvallevand
  Launch windows screensaver McBainUK 4 2,292 2008-07-31, 11:03 AM
Last Post: Reddwarf
  Web site programming - precompiled, compile on demand.... psycik 9 2,778 2008-02-27, 10:23 PM
Last Post: psycik
  General Plug-in programming question skate15e 8 3,150 2007-07-27, 06:21 PM
Last Post: sub
  SLightly OT - Windows Services jtokach 4 2,070 2007-04-24, 08:58 PM
Last Post: jtokach

  • View a Printable Version
  • Subscribe to this thread
Forum Jump:

© Designed by D&D, modified by NextPVR - Powered by MyBB

Linear Mode
Threaded Mode