Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, March 2, 2012 8:33 PM
Hello everybody.
I am trying to block some IP's that are trying to acess a program (when accepting the connection and it's repeated as spam) but I am not sure how to add certain IPs in Windows Firewall or "Local Security Policy" block list.
Right now I have to manually block the IPs but every time I block one it's changed after few minutes. The connections are disconnected if there are too many spamming but not blocked (which makes other legit people not being able to connect).
Any ideeas or ways to get started would be appreciated.
Thanks.
All replies (18)
Saturday, March 3, 2012 2:10 AM âś…Answered | 3 votes
I've created a sample in C# for you. The code is run successfully on my Win7 Ultimate machine.
using System;using System.Runtime.InteropServices;using System.Text;using NetFwTypeLib;namespace WinFirewall{ public class FWCtrl { const string guidFWPolicy2 = "{E2B3C97F-6AE1-41AC-817A-F6F92166D7DD}"; const string guidRWRule = "{2C5BC43E-3369-4C33-AB0C-BE9469677AF4}"; static void Main(string[] args) { FWCtrl ctrl = new FWCtrl(); ctrl.Setup(); } public void Setup() { Type typeFWPolicy2 = Type.GetTypeFromCLSID(new Guid(guidFWPolicy2)); Type typeFWRule = Type.GetTypeFromCLSID(new Guid(guidRWRule)); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2); INetFwRule newRule = (INetFwRule)Activator.CreateInstance(typeFWRule); newRule.Name = "InBound_Rule"; newRule.Description = "Block inbound traffic from 192.168.0.2 over TCP port 4000"; newRule.Protocol = (int) NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; newRule.LocalPorts = "4000"; newRule.RemoteAddress = "192.168.0.2"; newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; newRule.Enabled = true; newRule.Grouping = "@firewallapi.dll,-23255"; newRule.Profiles = fwPolicy2.CurrentProfileTypes; newRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; fwPolicy2.Rules.Add(newRule); } }}
After the code is run, you'll see something like the following in the "Advanced Setting" of "Windows Firewall with Advanced Security" -> "Inbound rules"
Inbound_Rule None Private Yes Block No Any Any 192.168.0.2 TCP 4000 Any Any Any
EDIT: for newRule.Grouping, you can use any string you like. The example is trying to use string resource -23255 in the firewallapi.dll, but seems just any string will do.
EDIT2: One of my friends suggest me to use something like Type.GetTypeFromProgId("HNetCfg.FwPolicy2") and so on instead of hardcoding the AppIds. I have to agree.
Saturday, March 3, 2012 1:41 AM
You can add reference to NetFWTypeLib in your project and use it to add rules.
After adding it you can follow this guide to add your rules. (The constants are defined in the TypeLib so you need not define them) Modify the rule so that the Action property becomes NetFwTypeLib.NET_FW_ACTION_.NET_FW_ACTION_BLOCK to block it.
Saturday, March 3, 2012 3:25 AM
Cheong;
That's some great code, how did you learn about this api?
JP Cowboy Coders Unite!
How to Create a Firewall in C# for Windows 7
Blocking Ports in C#
Blocking IP Address in C#
Saturday, March 3, 2012 3:40 AM | 1 vote
To tell the truth, I found the typeLib only contain interface and enums when I try to test it, so I peeked the C++ examples from the "Using Windows Firewall with Advanced Security" menuitem on the left.
The examples there uses these AppId. Therefore I think it's safe to assume these IDs are binding interface contract and won't be changed across versions. So I performed lookup using "regedit.exe" to find corresponding AppIds for classes I need to use to fill the blanks.
The remaining is just plain usage of using Activator to resemble CreateObject().
Friday, April 13, 2012 8:13 AM
Hi,
this is very useful Cheong00 :)
i was wondering if there was a way to add multiple ports to the same policy here:
newRule.LocalPorts = "4000";Thanks
Friday, April 13, 2012 8:31 AM
Sure, the port number(s) can be added as comma seperated ranges. See the following example:
newRule.LocalPorts = "1001,3000-4000";
This will block port 1001, as well as port 3000 to 4000. :)
EDIT: If you need a mix of TCP and UDP ports, you're advised to create 2 rules and give them the same group name, so you can enable/disable them by group. ("Windows Firewall with Advanced Security" management screen also allow you to filter rules by group name on the right-hand-side panel.)
Tuesday, February 5, 2013 2:16 AM
How do you dispose of the COM object that's created, wouldn't that cause a memory leak over time?
MCTS - Gold Certification
Tuesday, February 5, 2013 2:43 AM
The COM instances reference will be disposed automatically when it goes out of scope (i.e.: when Setup() returns), while the actual COM object will be freed when GC collects.
As usual rule, don't call GC.Collect() directly as it'll cause unnecessary promotion of objects' "generation" and do more harm than good. Just leave it as is and let GC determine when to release the memory.
The policy object is always living when the firewall is up, the only thing of concern here is the INetFwRule object, but it shouldn't take much space to make you worry too much.
Thursday, February 7, 2013 2:15 AM
That doesn't seem to be the case with this "Un-managed Code"
I had it running as a service every 1 min and it blew up my server twice.
That's what I'm concerned with, how do I properly clean up the "INetFwRule" ?
MCTS - Gold Certification
Friday, February 8, 2013 5:47 AM
Something I can't get it... You said you run it as service every minutes, did you check whether the rule exist before trying to add a new one? If not, open "Inbound Rule" now and you should see the firewall list has many duplicate lines now.
Friday, February 15, 2013 8:23 AM
I thought about blocking access to internet to a user, so i have to block port 80. but i am not sure
that the user can't change that manually through firwall configuration and continue to use internet.
I want to know if i will use this technique to block access to internet from the machine , that means i will use this?
newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
And not:
newRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
and without this line?
newRule.RemoteAddress = "192.168.0.2";
Please help me.
Friday, February 15, 2013 10:39 AM | 1 vote
You've got it mostly correct, but miss that the port should be specified through newRule.RemotePorts instead.
You'll also want to change the rule name and description to match what it does, though.
Monday, February 25, 2013 10:30 AM
What if I want to disable the same rule I have already added before? Can I retrieve that rule by its name and change its properties? Is that possible?
Tuesday, February 26, 2013 10:54 AM | 1 vote
Sure. Just use the fwPolicy2 object in my code. The fwPolicy2.Rules properties will have all the rules on the current machine's firewall.
Type typeFWPolicy2 = Type.GetTypeFromCLSID(new Guid(guidFWPolicy2)); Type typeFWRule = Type.GetTypeFromCLSID(new Guid(guidRWRule)); INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(typeFWPolicy2); foreach (INetFwRule rule in fwPolicy2.Rules) { if (rule.Name == "InBound_Rule") { rule.Enabled = false; } }
However I'll note that it'd be more common to enable/disable firewall rules by group.
Thursday, March 7, 2013 9:47 AM
This code didn't work for me on Windows XP, but worked fine in Windows seven, do someone know what is the problem please?
Thursday, March 7, 2013 10:52 AM
That's because "Windows Firewall with Advanced Security" is a feature only available in Vista or later.
For WinXP, there's another set of COM objects you should use.
Tuesday, February 25, 2014 5:08 PM
I got a problem... I get this error:
Error 1 'NetFwTypeLib.INetFwRule' does not contain a definition for 'RemoteAddress' and no extension method 'RemoteAddress' accepting a first argument of type 'NetFwTypeLib.INetFwRule' could be found (are you missing a using directive or an assembly reference?)
^ What i understood from this is that it is telling me that the place where the IP is going in (RemoteAddress) either does not exist or it's a wrong name, so my PC is on a norwegian language and what the name is on IP adress on inbound rules on the firewall settings is either "Lokal Adresse" or "Eksternal Adresse" which ofc is, Local Address and External Address...
Anyways i changed and i get the same error, any solution?
Thanks in advance :)
PS! if you are good at C# please hand me a message looking for someone good ^^
Wednesday, February 26, 2014 1:25 AM
At what system does your code running on?
The firewall under WinXP SP2/3 only concerns incoming ports therefore properties regarding IP addresses is very limited. You can only control the "scope" (local subnet/any network) for the rules to apply.
On the other hand, the firewall included in Vista+ is a feature complete one.
======
Since these are COM+ object properties/method names, they're not localized so you need not to change it to "Lokal Adresse" or "Eksternal Adresse". It's not going to work.