How to check a rule in windows firewall?

时间:2016-07-11 20:43:10

标签: windows delphi delphi-xe2 firewall windows-firewall

I would like to check if a port is open in the Windows firewall.

I found this way using netsh:

netsh advfirewall firewall show rule name="My rule"

which will return if the rule exists or not...

But, depending on Windows language, this will return different messages. I am trying to solve this in a better way. I would like to have a result Yes or No, True or False, not a localized string.

Do you have any tips??

1 个答案:

答案 0 :(得分:3)

AS: the "advfirewall" command and underlying service were introduced in Windows Vista. Windows 2000/XP do not have it and to support it you should use different interfaces.

Same goes for the computers with third-party, non-Microsoft firewalls installed (as part of antivirus suite for example).

In general on Vista+ you should obtain INetFwRules COM object, then enumerate all the rules in it, and check every rule if it covers the port you are about.

Follows example to obtain and enumerate the rules https://theroadtodelphi.com/2013/11/21/using-the-windows-firewall-with-advanced-security-scripting-api-and-delphi/#Enumerating Firewall Rules

var
 CurrentProfiles : Integer;
 fwPolicy2       : OleVariant;
 RulesObject     : OleVariant;
 rule            : OleVariant;
 oEnum           : IEnumvariant;
 iValue          : LongWord;

  fwPolicy2   := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject := fwPolicy2.Rules;
  CurrentProfiles := fwPolicy2.CurrentProfileTypes;

  .....

  Writeln('Rules:');

  oEnum         := IUnknown(Rulesobject._NewEnum) as IEnumVariant;
  while oEnum.Next(1, rule, iValue) = 0 do
  begin
    if (rule.Profiles And CurrentProfiles)<>0 then
    begin
        Writeln('  Rule Name:          ' + rule.Name);
        Writeln('   ----------------------------------------------');
        Writeln('  Description:        ' + rule.Description);
        Writeln('  Application Name:   ' + rule.ApplicationName);
        Writeln('  Service Name:       ' + rule.ServiceName);

        if (rule.Protocol = NET_FW_IP_PROTOCOL_TCP) or (rule.Protocol = NET_FW_IP_PROTOCOL_UDP) then
        begin
          Writeln('  Local Ports:        ' + rule.LocalPorts);
          Writeln('  Remote Ports:       ' + rule.RemotePorts);
          Writeln('  LocalAddresses:     ' + rule.LocalAddresses);
          Writeln('  RemoteAddresses:    ' + rule.RemoteAddresses);
        end;

    .....

  end;

OTOH using static binding rather than OleVariant should be faster and more reliable, check https://github.com/yypbd/yypbd-Delphi-HeaderPorting/tree/master/example/FirewallExample