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!
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.