I want a method of finding out what process opened what port without the aid of an external application. I.e. no netstat or other tools like it.
You need to use the IP helper functions. More specifically GetExtendedTcpTable and GetExtendedUdpTable.
For example, for GetExtendedUdpTable, you can pass in MIB_UDPTABLE_OWNER_PID as the TableClass and you will be able to receive the PID of the process that issued the call to bind for the UDP endpoint.
Related
As show in Windows Resource Monitor:
I want to analyse network traffic of an application, but I dont know the Windows API. I used scapy or wireshark, but I don't know what data packages are this application.
So, I want to get the listening port first. But I don't know the API.
You can use GetTcpTable2() or GetExtendedTcpTable() to enumerate open TCP ports, determining which ports are listeners, and get each one's owning process.
You can use GetExtendedUdpTable() to enumerate open UDP ports and get each one's owning process.
How do I close tcp v4 and tcp v6 connections on Windows? I don't want to kill the entire process that has the open connection as this obviously will kick everyone else off that process. I need to do this from a separate process, and so will not have access to socket handles, etc. I am using Windows API to get tcp table, etc. so I know which connections are active.
One way might be to enumerate all open handles on the system, or at least the open handles of a given target process, until you find the SOCKET handle you are interested in (see HOWTO: Enumerate handles, Socket Handles, and C++ Get Handle of Open Sockets of a Program - though I'm not sure how you would be able to retrieve the IP/Port pairs of a SOCKET to compare to the active connection you are interested in, without injecting remote getsockname()/getpeername() calls into the owning process of the SOCKET).
Once you have found the SOCKET handle you want, you can then close it by using DuplicateHandle() with the DUPLICATE_CLOSE_SOURCE flag 1.
1: This is how the "Close Handle" feature in Process Explorer works.
Since I'm using C#, I cannot PInvoke SetTcpEntry, even as administrator with an app.manifest file, it always sends a 317 error. So I created a C++ .exe to close a comma separated list of ipv4 addresses on the command line using SetTcpEntry, works fine even without an app.manifest file. That solves kicking ipv4 connections.
I tried using the get handles approach with NtQuerySystemInformation but never could get it working quite right, and it is a private mostly undocumented API and seems unsafe to use.
So, for ipv6, I am using windivert and injecting RST flag to ipv6 packets with certain ip addresses. It is as simple as setting the RST flag of an incoming packet before sending it on through with windivert. The downside is, if the client never sends another packet, the ipv6 socket still stays open indefinitely.
Perhaps someday Microsoft will add a SetTcpEntry6 function, but until then this appears to be the only realistic way.
UPDATE 2022-05-01, found this gem at https://www.x86matthew.com/view_post?id=settcpentry6
I am facing issue with c++ service which uses port 30015.It runs fine,but sometime it fails to start as the port 30015 is occupied and bind fails with error WSAEADDRINUSE.
I ran netstat command to know the port status
netstat -aon | findstr 30015
Output:
TCP 0.0.0.0:30015 0.0.0.0 LISTENING 6740
I checked the PID 6740 in task manager,this PID is not be taken by an process.
After searching in the net, I used TCPVIEW to see the status of the port. TCPView is showing port in listening mode and process name is "non-existance".
Application basically compress,decompress the file using 7za. Application listen on 30015 port for request and than create a child process and pass the commandline to run 7za command to compress and decompress file.
Here child process doesn't uses socket. Server runs on the main thread and listen on port 30015. This problem comes after restart of the server.
Here child process does not use socket as such. Do I need to make bInheritHandle = FALSE ?
Are you sure? This all sounds very confused. It's not possible for netstat to show a socket in the LISTEN state but for there to be no process -- especially if it shows the pid! You're confused because the process simply exited by the time you looked in Task Manager. All TCP connections in netstat are associated with a running process (except for unusual cases like TIME-WAIT sockets). So, find out which process has the socket open.
Secondly, I think you're trying to say that using bInheritHandles=TRUE as an argument to CreateProcess can lead to handle leaks. Only you have your code -- why not just look at the handles in your child and see if you do have a leak? It is only possible to use bInheritHandles=TRUE with great discipline, in the hands of novice programmers it will only lead to bugs. Create a named pipe with a suitable security descriptor, pass the name on the commandline to the child, and connect back, rather than using handle inheritance which is much too coarse-grained.
Finally, just to make sure, you do know to bind listening sockets with SO_REUSEADDR to prevent conflicting with active sockets using the same port? (SO_REUSEADDR still won't let two passive sockets be created on the same address/port combination, although it is a bit broken on Windows.)
Yes this can happen on Windows. If you've created a child process that inherits handles from the parent process then that includes TCP server sockets in the LISTEN state that will always be listed as owned by the parent PID even after that PID has died.
These sockets will disappear when all child processes that you spawned have exited, causing the reference count on their handles to reach zero.
From a security standpoint you should not use inter-process handle-inheritance, particularly when launching a 3rd part application, unless you have a good reason to need the feature.
I found port numbers and process ID through GetTcpTable(), PID only identifies process, but I want services within process such as svchost.exe is actully using the port....
sysinternals "procexp" tool shows TCP/IP ports along with services using those ports, under 'TCP/IP' tab...
I would like to know what win32 api should use to implement such feature?
Or how to implement by other ways?
Firstly query the port information from one of the table such as TCP or UDP with TCP_TABLE_OWNER_MODULE_ALL flag, you will get table with information. Now send each row in the table to GetOwnerModuleFromTcpEntry() which is of IpHlper API. Now you will get ModuleName which is either process name or service name that is running on given port.
Now from this moduleName you can retrive other information about service or process.
I am trying to reverse engineer a third-party TCP client / server Windows XP, SP 3 app for which I have no source available. My main line of attack is to use WireShark to capture TCP traffic.
When I issue a certain GUI command on the client side, the client creates a TCP connection to the server, sends some data, and tears down the connection. The server port is 1234, and the client port is assigned by the OS and therefore varies.
WireShark is showing that the message corresponding to the GUI command I issued gets sent twice. The two messages bear a different source port, but they have the same destination port (1234, as mentioned previosuly).
The client side actually consists of several processes, and I would like to determine which processes are sending these messages. These processes are long-lived, so their PIDs are stable and known. However, the TCP connections involved are transient, lasting only a few milliseconds or so. Though I've captured the client-side port numbers in WireShark and though I know all of the PIDs involved, the fact the connections are transient makes it difficult to determine which PID opened the port. (If the connections were long-lived, I could use netstat to map port numbers to PIDs.) Does anybody have any suggestions on how I can determine which processes are creating these transient connections?
I can think of two things:
Try sysinternals' tcpview program. It gives a detailed listing of all tcp connections opened by all the processes in the system. If a process creates connections, you will be able to see them flash (both connect and disconnect are flashed) in tcpview and you will know which processes to start looking into.
Try running the binary under a debugger. Windbg supports multi-process debugging (so does visual studio I think). You may have only export symbols to work with but that should still work for calls made to system dlls. Try breaking on any suspected windows APIs you know will be called by the process to create the connections. MSDN should have the relevant dlls for most system APIs documented.
Start here... post a follow-up if you get stuck again.
I ended up creating a batch file that runs netstat in a tight loop and appends its output to a text file. I ran this batch file while running the system, and by combing through all of the netstat dumps, I was able to find a dump that contained the PIDs associated with the ports.