Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Windows Firewall Rule (Exception) using Delphi

I am trying to manage firewall rules (exceptions) on Windows 7 using Delphi XE3. I found a very interesting code for adding a rule to Windows firewall, but nothing about deleting (removing) it. Please, can someone help?

Here is the code for adding the rule:

procedure AddExceptToFirewall(const Caption, AppPath: String);
// Uses ComObj
const
  NET_FW_PROFILE2_PRIVATE = 2;
  NET_FW_PROFILE2_PUBLIC  = 4;
  NET_FW_IP_PROTOCOL_TCP  = 6;
  NET_FW_ACTION_ALLOW     = 1;
var
  Profile: Integer;
  Policy2: OleVariant;
  RObject: OleVariant;
  NewRule: OleVariant;
begin
  Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  Policy2 := CreateOleObject('HNetCfg.FwPolicy2');
  RObject := Policy2.Rules;
  NewRule := CreateOleObject('HNetCfg.FWRule');
  NewRule.Name        := Caption;
  NewRule.Description := Caption;
  NewRule.ApplicationName := AppPath;
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.Enabled := True;
  NewRule.Grouping := '';
  NewRule.Profiles := Profile;
  NewRule.Action := NET_FW_ACTION_ALLOW;
  RObject.Add(NewRule);
end;

Thanks!

like image 557
Guybrush Avatar asked Dec 05 '14 19:12

Guybrush


People also ask

How to exclude a program from firewall?

Go to Start > Settings > Update & Security > Windows Security > Virus & threat protection. Under Virus & threat protection settings, select Manage settings, and then under Exclusions, select Add or remove exclusions. Select Add an exclusion, and then select from files, folders, file types, or process.

How to add java to firewall exception list?

If you have Windows defender set as your default anti virus, you may need to allow Java in Windows defender. You can do this by typing "Allow an App through Windows Firewall" into Windows search. Then when you open the program clicking Change Settings, then clicking the checkboxes next to Java(TM) Platform SE binary.


1 Answers

You simply call INetFWRules.Remove, passing in the name of the rule. The name is the same name you used when creating it (RObject.Name in the code you've provided above).

// Note: Normal COM exception handling should be used. Omitted for clarity.

procedure RemoveExceptFromFirewall(const RuleName: String);
const
  NET_FW_PROFILE2_PRIVATE = 2;
  NET_FW_PROFILE2_PUBLIC  = 4;
var
  Profile: Integer;
  Policy2: OleVariant;
  RObject: OleVariant;
begin
  Profile := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  Policy2 := CreateOleObject('HNetCfg.FwPolicy2');
  RObject := Policy2.Rules;
  RObject.Remove(RuleName);
end;

There's almost nothing provided in the linked documentation, BTW. I provided the link only for reference.

like image 61
Ken White Avatar answered Sep 20 '22 13:09

Ken White