AVG accuses Windows Service Application infection if Windows Firewall addition command is present

Asked

Viewed 483 times

8

I have an app that’s a Windows Service (Windows service) and because of facilities I am seeking to add a method to add it to Firewall of Windows automatically.

Thus:

procedure AddInFirewall(cApplicationName, cEntryName: string);
var
  cAppName: string;
begin
  if Trim(cApplicationName) = '' then
    cAppName := Application.ExeName
  else
    cAppName := cApplicationName;

  if Trim(cEntryName) = '' then
    begin
      cEntryName := ExtractFileName(cAppName);
    end;

  WinExec(PAnsiChar(AnsiString('netsh firewall delete allowedprogram ' + cAppName)), SW_HIDE);
  WinExec(PAnsiChar(AnsiString('netsh advfirewall firewall delete rule name="'+cEntryName+'" program="'+cAppName+'"')), SW_HIDE);

  WinExec(PAnsiChar(AnsiString('netsh firewall add allowedprogram '+cAppName+' "'+cEntryName+'" ENABLE')), SW_HIDE);
  WinExec(PAnsiChar(AnsiString('netsh advfirewall firewall add rule name="'+cEntryName+'" dir=in action=allow program="'+cAppName+'" enable=yes')), SW_HIDE);
end;

procedure TServerModule.DataModuleCreate(Sender: TObject);
begin
  AddInFirewall(Application.ExeName, 'MeuServico');
  FClients := TList.Create;
  StartService;
end;

However, the blessed AVG antivirus is complaining that he is infected with the:

Win32/DH{IFVEIS4}

Just comment on the lines with WinExec and compile again that he no longer claims the infection.

How can I solve such a problem?

  • I found it interesting that no one answered speaking of this important point: you made the digital signature of your executable? This is one of the steps for the behavior of a number of parts of the system to "look at its application with other eyes". This includes part of the anti-virus.

  • Yes. You provide a digital certificate, and sign the executable with this certificate. This solves a number of problems, including "unknown source" messages and a number of Windows alerts. Making a single executable is one thing, when you want things for the corporate environment, such as a service, you cannot stay in the home solution: http://msdn.microsoft.com/en-us/library/ms537361.aspx http://en.wikipedia.org/wikiCode_signing

  • 1

    PS: This is not a substitute calling the firewall API in the right way, but an important addition to this type of application.

  • 1

    You spoke of your program being treated like virus, digital signature is part of the solutions...

  • 1

    Nice find :) I don’t remember seeing this question before. (and it’s your name, or old account? I just saw that the user’s old name is @Tiago)

2 answers

7

If an application requires a special firewall configuration, the configuration must be done by an administrator. In your case, antivirus is correct in assuming that your program is malware.

Think about it. If any application could modify the Firewall rules with a specific call to some API, without alerting any protection system... Which would prevent me from distributing any application, a little freemium game maybe, that would open all the ports of your firewall and enable all the protocols?

In your case, when adding an application, Windows can take care of it automatically - the UAC goes up and asks the user for confirmation to add the application to the permissions list. But remove a Firewall rule programmatically? No. Just and nothing more than no.

  • @Crood when the application is running for the first time, the user who is logged in must see that dialog that darkens the rest of the screen and says something like "are you sure you want to allow this program to access network resources", and which allows you to choose whether to release the ports only on private networks or on public networks as well. If it doesn’t show up, well, then I really don’t know how to proceed. I hope someone more experienced can help here, but I suggest asking on Soen as well. I don’t know if the question fits Server Fault also.

6


The question itself has already been answered in the other answer so I will just try to supplement it.

That piece of code WinExec(....) is well known(manly/beaten) by antivirus because it is doing this in the background, antivirus is sure to consider your application as a malware.

Try to approach this in some other way, such as using the Apis of Windows Firewall, more precisely using the interfaces INetFwPolicy2 and FWRule.

See the following example that will try to add a rule to an application(Note: privileges are required to run the application):

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj;

// Este código adiciona uma regra de aplicativo usando as APIs do Windows Firewall.
Procedure AddApplicationRule;
Const
 NET_FW_ACTION_ALLOW = 1;
 NET_FW_IP_PROTOCOL_TCP = 6;
var
 CurrentProfiles : OleVariant;
 fwPolicy2       : OleVariant;
 RulesObject     : OleVariant;
 NewRule         : OleVariant;
begin
  // Cria o objeto que permite acessar a política de Firewall
  fwPolicy2   := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject := fwPolicy2.Rules;
  CurrentProfiles := fwPolicy2.CurrentProfileTypes;

  // Cria o objeto que proporcionará acessar as propriedades de uma regra.
  NewRule := CreateOleObject('HNetCfg.FWRule');

  NewRule.Name := 'Foo Bar';  // Nome da Aplicação
  NewRule.Description := 'My Powerful Service Example'; // Descrição da Aplicação
  NewRule.Applicationname := ParamStr(0); // Caminho da Aplicaçao
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.LocalPorts := 4000; // Porta
  NewRule.Enabled := True;
  NewRule.Grouping := ''; // Grupo
  NewRule.Profiles := CurrentProfiles;
  NewRule.Action := NET_FW_ACTION_ALLOW;

  // Adiciona a nova regra
  RulesObject.Add(NewRule);
end;

begin
 try
    CoInitialize(nil);
    try
      AddApplicationRule;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

When opening the Firewall Advanced Settings Panel (Type firewall.cpl in the Run from Windows - on the left click on Advanced Settings) the application will be present there.

k

I hope I haven’t run away from the focus of the question. For more information on how to manipulate the Firewall through the Apis see esse tópico in the MSDN and aqui precisely in Delphi.

Updating

From @Renan’s reply, I was able to reproduce what he mentioned, I’m not sure if the antivirus will block or not, follow the procedure AddInFirewall() modified(tested on Windows 7):

procedure AddInFirewall(cApplicationName, cEntryName: string);
Var
  TShell: TShellExecuteInfo;
  cAppName: string;
begin
  if Trim(cApplicationName) = '' then
    cAppName := Application.ExeName
  else
    cAppName := cApplicationName;

  if Trim(cEntryName) = '' then
    cEntryName := ExtractFileName(cAppName);

  FillChar(TShell, sizeof(TShell), 0);
  TShell.cbSize := SizeOf(TShell);
  TShell.fMask := SEE_MASK_NOCLOSEPROCESS;
  TShell.Wnd := Application.Handle;
  TShell.lpVerb := Nil;
  TShell.nShow := SW_NORMAL; // Utilize SW_HIDE para esconder a janela
  TShell.lpFile := 'cmd.exe';
  TShell.lpParameters := PWideChar('/k netsh advfirewall firewall add rule name="' + cEntryName + '" dir=in action=allow program="' + cApplicationName + '" enable=yes');
  TShell.lpVerb := 'runas';

  ShellExecuteEx(@TShell);
  WaitForSingleObject(TShell.hProcess, INFINITE);
  CloseHandle(TShell.hProcess);

  ShowMessage('Procedimento concluido!');
end;

Call the procedure the same way you were doing, so:

AddInFirewall(Application.ExeName, 'MeuServico');

By calling the function, we will create the process cmd.exe and we will pass as parameter the command responsible for adding the application to the Firewall, a popup of WOW will appear asking for confirmation to execute cmd.exe with high duties.

Through WaitForSingleObject we will only be able to continue using the application after cmd.exe have been finalized.

If all goes well, we’ll see Command Prompt show something like that:

inserir a descrição da imagem aqui

And finally, in the advanced Firewall settings panel:

inserir a descrição da imagem aqui

  • Very good @DBX8!!

  • 3

    +1, and this should be the answer marked as correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.