delphi - Windows firewall regel for XP

Indlæg af Hanne Mølgaard Plasc

Problem



Sådan tilføjes programmisk program eller port til Windows Firewall i Windows XP?

Bedste reference


Prøv denne kode uddraget fra vores open source SQlite3UI.pas enhed: [2]


function GetXPFirewall(var fwMgr, profile: OleVariant): boolean;
begin
  Result := (Win32Platform=VER\_PLATFORM\_WIN32\_NT) and
    (Win32MajorVersion>5) or ((Win32MajorVersion=5) and (Win32MinorVersion>0));
  if result then // need Windows XP at least
  try 
    fwMgr := CreateOleObject('HNetCfg.FwMgr');
    profile := fwMgr.LocalPolicy.CurrentProfile;
  except
    on E: Exception do
      result := false;
  end;
end;

const
  NET\_FW\_PROFILE\_DOMAIN = 0;
  NET\_FW\_PROFILE\_STANDARD = 1;
  NET\_FW\_IP\_VERSION\_ANY = 2;
  NET\_FW\_IP\_PROTOCOL\_UDP = 17;
  NET\_FW\_IP\_PROTOCOL\_TCP = 6;
  NET\_FW\_SCOPE\_ALL = 0;
  NET\_FW\_SCOPE\_LOCAL\_SUBNET = 1;

procedure AddApplicationToXPFirewall(const EntryName, ApplicationPathAndExe: string);
var fwMgr, profile, app: OleVariant;
begin
  if GetXPFirewall(fwMgr,profile) then
  try
    if profile.FirewallEnabled then begin
      app := CreateOLEObject('HNetCfg.FwAuthorizedApplication');
      try
        app.ProcessImageFileName := ApplicationPathAndExe;
        app.Name := EntryName;
        app.Scope := NET\_FW\_SCOPE\_ALL;
        app.IpVersion := NET\_FW\_IP\_VERSION\_ANY;
        app.Enabled :=true;
        profile.AuthorizedApplications.Add(app);
      finally
        app := varNull;
      end;
    end;
  finally
    profile := varNull;
    fwMgr := varNull;
  end;
end;

procedure AddPortToXPFirewall(const EntryName: string; PortNumber: cardinal);
var fwMgr, profile, port: OleVariant;
begin
  if GetXPFirewall(fwMgr,profile) then
  try
    if profile.FirewallEnabled then begin
      port := CreateOLEObject('HNetCfg.FWOpenPort');
      port.Name := EntryName;
      port.Protocol := NET\_FW\_IP\_PROTOCOL\_TCP;
      port.Port := PortNumber;
      port.Scope := NET\_FW\_SCOPE\_ALL;
      port.Enabled := true;
      profile.GloballyOpenPorts.Add(port);
    end;
  finally
    port := varNull;
    profile := varNull;
    fwMgr := varNull;
  end;
end;


Det giver dig mulighed for at tilføje et program eller en port til XP firewall.
Skal arbejde fra Delphi 6 op til XE.

Andre referencer 1


Scripting af Windows Firewall er mulig, se Scripting Windows Firewall [3]


Og kode eksempler for eksempel her [4]