Ir al contenido


Foto

Como obtener puertos abiertos y el programa o servicio asociado


  • Por favor identifícate para responder
18 respuestas en este tema

#1 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 25 junio 2014 - 11:15

Hola a todos
Estoy haciendo un software para auditoría informatica y necesito saber como puedo mostrar los puertos abiertos en la PC y que programa o servicio lo está usando

  • 0

#2 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 25 junio 2014 - 12:20

Te contesto desde mi android.
Seguro que esto te da ideas.

Saludos.


  • 0

#3 seoane

seoane

    Advanced Member

  • Administrador
  • 1.259 mensajes
  • LocationEspaña

Escrito 25 junio 2014 - 03:21

Aquí te dejo mi viejo Netstat recien bajado de la web de embarcadero no se donde deje el código original  :D )

Archivos adjuntos


  • 0

#4 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 26 junio 2014 - 05:12

Basado en el código expuesto aquí, he preparado un ejemplo simple que lista los puertos usados, los procesos que lo abren, direcciones IP y su estado. Ejecutado como administrador nos da, también, la ruta completa del proceso.


delphi
  1. program Project1;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. uses
  6.   Windows,
  7.   SysUtils,
  8.   winsock,
  9.   tlhelp32;
  10.  
  11. // TCP
  12. type
  13. MIB_TCPROW_OWNER_PID = record
  14.   dwState:          DWORD;
  15.   dwLocalAddr:      DWORD;
  16.   dwLocalPort:      DWORD;
  17.   dwRemoteAddr:      DWORD;
  18.   dwRemotePort:      DWORD;
  19.   dwOwningPid:      DWORD;
  20. end;
  21. PMIB_TCPROW_OWNER_PID = ^MIB_TCPROW_OWNER_PID;
  22.  
  23. MIB_TCPTABLE_OWNER_PID = record
  24.   dwNumEntries: DWORD;
  25.   table:        array[0..0] of MIB_TCPROW_OWNER_PID;
  26. end;
  27. PMIB_TCPTABLE_OWNER_PID = ^MIB_TCPTABLE_OWNER_PID;
  28.  
  29. TCP_TABLE_CLASS = (
  30.   TCP_TABLE_BASIC_LISTENER,
  31.   TCP_TABLE_BASIC_CONNECTIONS,
  32.   TCP_TABLE_BASIC_ALL,
  33.   TCP_TABLE_OWNER_PID_LISTENER,
  34.   TCP_TABLE_OWNER_PID_CONNECTIONS,
  35.   TCP_TABLE_OWNER_PID_ALL,
  36.   TCP_TABLE_OWNER_MODULE_LISTENER,
  37.   TCP_TABLE_OWNER_MODULE_CONNECTIONS,
  38.   TCP_TABLE_OWNER_MODULE_ALL
  39. );
  40. PTCP_TABLE_CLASS = ^TCP_TABLE_CLASS;
  41.  
  42. MIB_TCP_STATE = (
  43.   MIB_TCP_STATE_CLOSED = 1,
  44.   MIB_TCP_STATE_LISTEN,
  45.   MIB_TCP_STATE_SYN_SENT,
  46.   MIB_TCP_STATE_SYN_RCVD,
  47.   MIB_TCP_STATE_ESTAB,
  48.   MIB_TCP_STATE_FIN_WAIT1,
  49.   MIB_TCP_STATE_FIN_WAIT2,
  50.   MIB_TCP_STATE_CLOSE_WAIT,
  51.   MIB_TCP_STATE_CLOSING,
  52.   MIB_TCP_STATE_LAST_ACK,
  53.   MIB_TCP_STATE_TIME_WAIT,
  54.   MIB_TCP_STATE_DELETE_TCB
  55. );
  56.  
  57. // UDP
  58. MIB_UDPROW_OWNER_PID = record
  59.   dwLocalAddr: DWORD;
  60.   dwLocalPort: DWORD;
  61.   dwOwningPid: DWORD;
  62. end;
  63. PMIB_UDPROW_OWNER_PID = ^MIB_UDPROW_OWNER_PID;
  64.  
  65. MIB_UDPTABLE_OWNER_PID = record
  66.   dwNumEntries: DWORD;
  67.   table:        array[0..0] of MIB_UDPROW_OWNER_PID;
  68. end;
  69. PMIB_UDPTABLE_OWNER_PID = ^MIB_UDPTABLE_OWNER_PID;
  70.  
  71. UDP_TABLE_CLASS = (
  72.   UDP_TABLE_BASIC,
  73.   UDP_TABLE_OWNER_PID,
  74.   UDP_TABLE_OWNER_MODULE
  75. );
  76. PUDP_TABLE_CLASS = ^UDP_TABLE_CLASS;
  77.  
  78. function GetExtendedTcpTable(lpTable: Pointer; lpSize: PCardinal; bOrder: LongBool; ulAf: ULONG; TableClass: TCP_TABLE_CLASS; Reserved: Cardinal): Cardinal; stdcall; external 'Iphlpapi.dll';
  79. function GetExtendedUdpTable(lpTable: Pointer; lpSize: PCardinal; bOrder: LongBool; ulAf: ULONG; TableClass: UDP_TABLE_CLASS; Reserved: Cardinal): Cardinal; stdcall; external 'Iphlpapi.dll';
  80.  
  81. var
  82. StateStr: array[1..12] of String = ('CLOSED', 'LISTEN', 'SYN_SENT', 'SYN_RCVD',  'ESTAB', 'FIN_WAIT1', 'FIN_WAIT2', 'CLOSE_WAIT', 'CLOSING', 'LAST_ACK', 'TIME_WAIT', 'DELETE_TCB');
  83.  
  84. function EnablePrivilege(name: String; Enable: boolean): boolean;
  85. var
  86.   hToken: Cardinal;
  87.   priv: TOKEN_PRIVILEGES;
  88. begin
  89.   priv.PrivilegeCount:= 1;
  90.   priv.Privileges[0].Attributes:= 0;
  91.   if Enable then priv.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  92.   LookupPrivilegeValue(nil, PCHAR(name), priv.Privileges[0].Luid);
  93.   OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken);
  94.   AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);
  95.   Result:= (GetLastError = ERROR_SUCCESS);
  96.   CloseHandle (hToken);
  97. end;
  98.  
  99. function GetExeNameByProcessId(dwProcessId: DWORD): string;
  100. var
  101.   snp: THandle;
  102.   lppe: TProcessEntry32;
  103. begin
  104.   Result := '';
  105.   snp := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  106.   lppe.dwSize:= sizeof(lppe);
  107.   if Process32First(snp, lppe) then
  108.   begin
  109.     repeat
  110.       if lppe.th32ProcessID = dwProcessId then
  111.       begin
  112.         Result := lppe.szExeFile;
  113.         Break;
  114.       end;
  115.     until not(Process32Next(snp, lppe));
  116.     CloseHandle(snp);
  117.   end; 
  118. end;
  119.  
  120. function GetProcessImageFileName(PId: DWORD): String;
  121. var
  122.   hSnapshot: THANDLE;
  123.   ModuleEntry: MODULEENTRY32 ;
  124. begin
  125.   ModuleEntry.dwSize:= sizeof(MODULEENTRY32);
  126.   Result:= '';
  127.   hSnapshot:= CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PId);
  128.   if hSnapshot <> THANDLE(-1) then
  129.   begin
  130.     if Module32First(hSnapshot, ModuleEntry) then
  131.       Result:= ModuleEntry.szExePath;
  132.     CloseHandle(hSnapshot);
  133.   end;
  134. end;
  135.  
  136. function GetProcessProcessName(PId: DWORD): String;
  137. begin
  138.   Result:= GetProcessImageFileName(PId);
  139.   if Result = '' then
  140.     Result:= GetExeNameByProcessId(PId);
  141. end;
  142.  
  143. var
  144.   TCPTablePID: PMIB_TCPTABLE_OWNER_PID;
  145.   UDPTablePID: PMIB_UDPTABLE_OWNER_PID;
  146.   Size, i: DWORD;
  147.   hProcess: THandle;
  148.  
  149. begin
  150.   EnablePrivilege('SeDebugPrivilege', true);
  151.   Size:= 0;
  152.   // Listando los puertos TCP
  153.   GetExtendedTcpTable(nil, @Size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
  154.   TCPTablePID:= VirtualAlloc(nil, Size, MEM_COMMIT, PAGE_READWRITE);
  155.   GetExtendedTcpTable(TCPTablePID, @Size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
  156.   for i:= 0 to TCPTablePID.dwNumEntries-1 do
  157.   begin
  158.     with TCPTablePID.table[i] do
  159.     begin
  160.       WriteLn('TCP');
  161.       WriteLn('Pid: ', IntToStr(dwOwningPid));
  162.       WriteLn('Puerto: ', IntToStr(ntohs(dwLocalPort)));
  163.       WriteLn('Estado: ', StateStr[dwState]);
  164.       WriteLn('Direccion local: ' + inet_ntoa(in_addr(dwLocalAddr)), ' - Direccion remota: ' + inet_ntoa(in_addr(dwRemoteAddr)));
  165.       WriteLn(GetProcessProcessName(dwOwningPid));
  166.       WriteLn;
  167.     end;
  168.   end;
  169.   VirtualFree(TCPTablePID, 0, MEM_RELEASE);
  170.  
  171.   // Listado de los puertos UDP
  172.   GetExtendedUdpTable(nil, @Size, TRUE, AF_INET, UDP_TABLE_OWNER_PID, 0);
  173.   UDPTablePID:= VirtualAlloc(nil, Size, MEM_COMMIT, PAGE_READWRITE);
  174.   GetExtendedUdpTable(UDPTablePID, @Size, TRUE, AF_INET, UDP_TABLE_OWNER_PID, 0);
  175.   for i:= 0 to UDPTablePID.dwNumEntries-1 do
  176.   begin
  177.     with UDPTablePID.table[i] do
  178.     begin
  179.       WriteLn('UDP');
  180.       WriteLn('Pid: ', IntToStr(dwOwningPid));
  181.       WriteLn('Puerto: ', IntToStr(ntohs(dwLocalPort)));
  182.       WriteLn('Direccion local: ' + inet_ntoa(in_addr(dwLocalAddr)));
  183.       WriteLn(GetProcessProcessName(dwOwningPid));
  184.       WriteLn;
  185.     end;
  186.   end;
  187.   VirtualFree(UDPTablePID, 0, MEM_RELEASE);
  188.  
  189.   Readln;
  190.  
  191. end.


Probado en WinXP
PD/ probado también en Win8

Saludos.
  • 0

#5 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 26 junio 2014 - 10:12

Pues no he podido compilarlo me salta este error:

[DCC Error] Project1.dpr(93): E2033 Types of actual and formal var parameters must be identical


Y surge en esta linea:



delphi
  1. function EnablePrivilege(name: String; Enable: boolean): boolean;
  2. var
  3.   hToken: Cardinal;
  4.   priv: TOKEN_PRIVILEGES;
  5. begin
  6.   priv.PrivilegeCount:= 1;
  7.   priv.Privileges[0].Attributes:= 0;
  8.   if Enable then priv.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  9.   LookupPrivilegeValue(nil, PCHAR(name), priv.Privileges[0].Luid);
  10.   [b]OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken);[/b]
  11.   AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);
  12.   Result:= (GetLastError = ERROR_SUCCESS);
  13.   CloseHandle (hToken);
  14. end;



Alguna idea? Windows 7 Pro, Delphi XE2 Update 4 Hot fix 1
  • 0

#6 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 26 junio 2014 - 10:48

Yo use delphi7 que no tiene bien "tipados" ciertos tipos. No puedo reproducir el error.
Prueba así:


delphi
  1. function EnablePrivilege(name: String; Enable: boolean): boolean;
  2. var
  3.   hToken: THANDLE;
  4.   priv: TOKEN_PRIVILEGES;
  5. begin
  6.   priv.PrivilegeCount:= 1;
  7.   priv.Privileges[0].Attributes:= 0;
  8.   if Enable then priv.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  9.   LookupPrivilegeValue(nil, PCHAR(name), priv.Privileges[0].Luid);
  10.   OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken);
  11.   AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);
  12.   Result:= (GetLastError = ERROR_SUCCESS);
  13.   CloseHandle (hToken);
  14. end;


Saludos.
  • 0

#7 FGarcia

FGarcia

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 687 mensajes
  • LocationMéxico

Escrito 26 junio 2014 - 10:58

OK!

Compilo a la primera.

Gracias!!
  • 0

#8 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 26 junio 2014 - 11:23

Muchas gracias
Probaré los codigos y despues les digo que tal me resultó
(y)
  • 0

#9 Wilson

Wilson

    Advanced Member

  • Moderadores
  • PipPipPip
  • 2.137 mensajes

Escrito 26 junio 2014 - 01:51

Gracias a los maestros Seoane y Escafandra, muy buen código y por supuesto de mucha utilidad.

Un cordial saludo.
  • 0

#10 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 27 junio 2014 - 11:03

Todo Ok  (y)
Muchas gracias, con eso resolví mi problema

:wink:
  • 0

#11 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 26 agosto 2015 - 03:07

Despues de tanto tiempo, no se si reabrir el hilo o crear otro

 

Pues he querido ampliar las funcionalidades de mi soft para que funcione para toda la red local, y por eso quisiera saber como podria hacer esto mismo, pero a cualquier equipo conectado a mi red, ya sea dando el IP o el nombre DNS

 


  • 0

#12 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 27 agosto 2015 - 05:02

Se me ocurre usar el código para una máquina local y comunicarlo por red, puedes basarte en este ejemplo que ya conoces.

 

 

Saludos.


  • 0

#13 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 07 marzo 2017 - 12:17

 

Yo use delphi7 que no tiene bien "tipados" ciertos tipos. No puedo reproducir el error.
Prueba así:
 


delphi
  1. function EnablePrivilege(name: String; Enable: boolean): boolean;
  2. var
  3.   hToken: THANDLE;
  4.   priv: TOKEN_PRIVILEGES;
  5. begin
  6.   priv.PrivilegeCount:= 1;
  7.   priv.Privileges[0].Attributes:= 0;
  8.   if Enable then priv.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  9.   LookupPrivilegeValue(nil, PCHAR(name), priv.Privileges[0].Luid);
  10.   OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken);
  11.   AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);
  12.   Result:= (GetLastError = ERROR_SUCCESS);
  13.   CloseHandle (hToken);
  14. end;

Saludos.

 

 

Pues de nuevo lo que me funciono bien en Delphi7, ahora no funciona en XE7


delphi
  1. AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);

Me da el error:

 

[dcc32 Error] scanpuertos.dpr(94): E2250 There is no overloaded version of 'AdjustTokenPrivileges' that can be called with these arguments

 

 


  • 0

#14 Agustin Ortu

Agustin Ortu

    Advanced Member

  • Moderadores
  • PipPipPip
  • 831 mensajes
  • LocationArgentina

Escrito 07 marzo 2017 - 12:50

Yo la invoco asi en Berlin

delphi
  1. function SetPrivilege(const PrivilegeName: string; const Enabled: Boolean): Boolean;
  2. var
  3. TokenPrivileges, RequestedPrivileges: TTokenPrivileges;
  4. TokenHandle: THandle;
  5. ReturnLength: DWORD;
  6. begin
  7. Result := False;
  8. OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, TokenHandle);
  9.  
  10. RequestedPrivileges.PrivilegeCount := 1;
  11. if LookupPrivilegeValue(nil, PWideChar(PrivilegeName), RequestedPrivileges.Privileges[0].LUID) then
  12. begin
  13. if Enabled then
  14. RequestedPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
  15. else
  16. RequestedPrivileges.Privileges[0].Attributes := 0;
  17.  
  18. ReturnLength := 0;
  19. Result := AdjustTokenPrivileges(TokenHandle, False, RequestedPrivileges, SizeOf(TokenPrivileges),
  20. TokenPrivileges, ReturnLength);
  21. end;
  22.  
  23. CloseHandle(TokenHandle)
  24. end;

Fuente
  • 0

#15 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 07 marzo 2017 - 01:17

Pues de nuevo lo que me funciono bien en Delphi7, ahora no funciona en XE7


delphi
  1. AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);

Me da el error:

 

Pues a mi me compila perfectamente en Berlin y, además, funciona.

Mira a ver como está declarada la API AdjustTokenPrivileges  en XE7

 

 

Saludos.


  • 0

#16 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 07 marzo 2017 - 01:29

Muchas gracias Agustin, cambiando la funcion, ahora si me funciona (y)


  • 0

#17 JoAnCa

JoAnCa

    Advanced Member

  • Miembro Platino
  • PipPipPip
  • 775 mensajes
  • LocationPinar del Río, Cuba

Escrito 07 marzo 2017 - 01:34

Pues a mi me compila perfectamente en Berlin y, además, funciona.

Mira a ver como está declarada la API AdjustTokenPrivileges  en XE7

 

 

Saludos.

 

Respondiendo a Agustin, no habia visto tu respuesta

 

Segun Winapi.Windows esta declarado así:


delphi
  1. function AdjustTokenPrivileges(TokenHandle: THandle; DisableAllPrivileges: BOOL;
  2. const NewState: TTokenPrivileges; BufferLength: DWORD;
  3. var PreviousState: TTokenPrivileges; var ReturnLength: DWORD): BOOL; external advapi32 name 'AdjustTokenPrivileges';


  • 0

#18 Agustin Ortu

Agustin Ortu

    Advanced Member

  • Moderadores
  • PipPipPip
  • 831 mensajes
  • LocationArgentina

Escrito 07 marzo 2017 - 02:39

A mi tambien me funciona bien en Berlin. Aunque ese casteo raro sobre PDWORD no me gusta nada, se supone que la funcion escribe en los parametros var la long. del retorno y el token o estado anterior anterior

 

Esto por ej produce errores access violation, si bien compila:


delphi
  1. uses
  2. Winapi.Windows;
  3.  
  4. procedure Test(var Value: DWORD);
  5. begin
  6. Value := 5;
  7. end;
  8.  
  9. var
  10. Value: DWORD;
  11. begin
  12. Value := 3;
  13. Writeln(Value);
  14. Test(Value);
  15. Writeln(Value);
  16.  
  17. Test(PDWORD(nil)^); // accesss violation
  18. Test(PDWORD(Value)^); // accesss violation
  19. Writeln(Value);
  20. Readln;
  21. end.

Por otro lado, la API AdjustTokenPrivileges te permite pasar null en los dos ultimos parametros, pero en los dos al mismo tiempo!


  • 0

#19 escafandra

escafandra

    Advanced Member

  • Administrador
  • 4.107 mensajes
  • LocationMadrid - España

Escrito 07 marzo 2017 - 03:50

A mi tambien me funciona bien en Berlin. Aunque ese casteo raro sobre PDWORD no me gusta nada, se supone que la funcion escribe en los parametros var la long. del retorno y el token o estado anterior anterior

 

Esto por ej produce errores access violation, si bien compila:


delphi
  1. uses
  2. Winapi.Windows;
  3.  
  4. procedure Test(var Value: DWORD);
  5. begin
  6. Value := 5;
  7. end;
  8.  
  9. var
  10. Value: DWORD;
  11. begin
  12. Value := 3;
  13. Writeln(Value);
  14. Test(Value);
  15. Writeln(Value);
  16.  
  17. Test(PDWORD(nil)^); // accesss violation
  18. Test(PDWORD(Value)^); // accesss violation
  19. Writeln(Value);
  20. Readln;
  21. end.

Por otro lado, la API AdjustTokenPrivileges te permite pasar null en los dos ultimos parametros, pero en los dos al mismo tiempo!

 

El tema es que delphi cambia la declaración original de la API que no usa referencias sino punteros:


cpp
  1. BOOL WINAPI AdjustTokenPrivileges(
  2. _In_ HANDLE TokenHandle,
  3. _In_ BOOL DisableAllPrivileges,
  4. _In_opt_ PTOKEN_PRIVILEGES NewState,
  5. _In_ DWORD BufferLength,
  6. _Out_opt_ PTOKEN_PRIVILEGES PreviousState,
  7. _Out_opt_ PDWORD ReturnLength
  8. );

PDWORD(nil)^ realmente está pasando un puntero nulo. Como no me interesa ningún resultado, y los dos últimos parámetros son nulos, cono dice msdn, me permito la licencia que, por otro lado, uso con la API de Windows y delphi muy a menudo sin el más mínimo inconveniente ahorrándome declarar variables incómodas e innecesarias. 


delphi
  1. AdjustTokenPrivileges (hToken, FALSE, priv, sizeof(priv), nil, PDWORD(nil)^);

Si he observado que aveces hay dos declaraciones, sobrecargadas de la misma API. Como no dispongo de todas las versiones de delphi, no puedo jugar con estas cosas, y no creas, rabia me da. :)

 

Saludos.


  • 1




IP.Board spam blocked by CleanTalk.