How can I enumerate sockets on a given windows process? - windows

I need my program to check if a given Windows process is abusing the network.
I would like to enumerate the process tcp and udp sockets, and see how much data they transferred during a given period.
Is there a C or .Net API that can provide such info?

On Win2k, you can use GetTcpTable(), GetTcp6Table(), GetUdpTable(), and GetUdp6Table() to locate all of the active socket connections. But to match them to specific process IDs, you would have to manually enumerate the system's open handles looking for TCP/UDP handles, and then query the process information from them.
On XP, you can use AllocateAndGetTcpExTableFromStack() and AllocateAndGetUdpExTableFromStack(), which can return process IDs with each socket connection.
On XP SP2 and later, you can use GetExtendedTcpTable() and GetExtendedUdpTable(), which can return process IDs with each socket connection as well.

You might look at WinPcap. http://www.winpcap.org/
A C#.net version is available in SharpPcap. http://www.tamirgal.com/blog/page/SharpPcap.aspx

Related

How to get an application listening ports with windows c++ api

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 a socket (ipv4 and ipv6) connection on Windows from any 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

Is there a way to monitor what process sends UDP packets (source/dest IP and port) in Windows?

I discovered almost accidentally that my machine was sending and receiving UDP packets to a machine in Poland. Not that I have any problem with Poland, I just don't know why my laptop has the need to communicate with a server there. Reverse DNS shows just the ISP providing the address to some end user. Using Wireshark, I can monitor the messages, which were indecipherable as they were probably encrypted. All packets sent from my machine had the same source port, so clearly the application that sent them opened this UDP socket to use it. I am searching for ways to:
1) enumerate all current sockets open in the system, including the process that created it and, for both TCP and UDP, what ports and addresses they are current bound to.
2) because applications can open these sockets, use them, and close them right away, I would love to find (or perhaps even write) a program that once started would somehow get notification each time a socket gets created, or really more importantly when bound to a source and/or destination address and port. For UDP, I would love to also be able to monitor/keep track of the destination IP addresses and ports that socket has sent messages to.
I don't want to monitor the traffic itself, I have Wireshark if I want to view the traffic. I want to be able to then cross reference to discover what application is generating the packets. I want to know if it is from a process I trust, or if it is something I need to investigate further.
Does anybody know of any applications (for the Windows platform) that can do this? If not, any ideas about a .NET or Windows API that provides this capability, should I want to write it myself?
Edit:
After further research - looks like the APIs to use are GetExtendedUdpTable and GetExtendedTcpTable, CodeProject.com has some samples wrapping these in .NET (see http://www.codeproject.com/Articles/14423/Getting-the-active-TCP-UDP-connections-using-the-G). So a combination of this API and some sniffer code would be needed to monitor and keep track of what hosts at what ports using what protocol any particular application on your machine is talking to. If I ever get some free time, I'll consider creating this, if you know of an app that does all this, please let me know.
Try SysInternals TCPView. Despite its name, it handles UDP as well.
netstat -b to enumerate all ports along with the process names.
You can try using SysInternals' Process MOnitor (ProcMon.exe or ProcMon64.exe).
It allows for filtering of Processes by "UDP Send" Operation - and provides detailed UDP Connection data, including source and destination addresses(IP) and ports etc.

Mapping Port to PID for Transient Windows TCP Connections

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.

Sockets vs named pipes for local IPC on Windows?

Are there any reasons for favoring named pipes over sockets for local IPC (both using win-api), effectiveness-wize, resource-wize or otherwise, since both behave very much alike (and likely to be abstracted by a similiar interface anyway), in an application that is likely to already use sockets for network purposes anyway?
I can name at least the addressing issue: port numbers for sockets against filenames for pipes. Also, named pipes (AFAIK) won't alert the firewall (block/unblock dialog), although blocked applications can still communicate via sockets locally. Anything else to take into account?
In the case of using sockets, are there any winsock settings/flags that are recomended when using sockets locally?
Some subtle differences:
Sockets won't work for local IPC if you don't have a functioning adapter. How common is it to have a PC without a functioning adapter? Well, I got bitten when somebody tried to demonstrate our software to a customer on a laptop that was not plugged in to a network or a power supply (so the OS disabled the network card to save power) and the wireless adapter was disabled (because the laptop user didn't use wireless). You can get around this by installing a loopback adapter but that's not ideal.
Firewall software can cause problems with establishing TCP/IP connections. It's not supposed to be an issue for local IPC, but I'm not convinced. Named pipes can have firewalls too.
You may have issues due to the privileges needed to create named pipes, or to create new instances of named pipes. For instance, I was running multiple servers using the same named pipe (probably not a good idea, but this was for testing) and some failed in CreateNamedPipe because the first server to create the pipe was running in Administrator mode (because it was launched from Visual Studio in Administrator mode) while the rest were launched from the command line with normal UAC level.
Although the article mentioned by Rubens is mostly about IPC over a network, it does make the point that "Local named pipes runs in kernel mode and is extremely fast".
Another solution you may want to consider is a named shared memory region. It is a little bit of work because you have to establish a flow control protocol yourself, but I have used this successfully in the past where speed was the most important thing.

Resources