I am about to use Wireshark for some traffic monitoring on my Windows computer. While working on it, I was wondering how Wireshark manages to catch low level network packets before Windows does.
First of all, a network interface on my NIC receives a packet. The NIC then does some initial checks (CRC, right MAC address, ... etc. ). Assuming that the verification was successful, the NIC forwards the packet. But how and where?
I understand that drivers are the glue between the NIC and the OS or any other application. I further guess that there's a separate driver for Windows and Wireshark (WinPcap?). Otherwise, Wireshark wouldn't be able to receive Ethernet frames. Are there two or more NIC drivers coexisting at the same time? How does the NIC know, which one to use?
The I/O model in Windows is based on a stack of components. Data must flow through the various components of that stack that exists between the physical network card, and the application that will consume the data. Sometimes those various components inspect the data (a TCP packet for example,) as they flow through the stack, and based on the contents of that packet, the data may be altered, or the packet may be discarded entirely.
This is a simplified model of the "network stack" that packets flow through in order to get from the application to the wire and vice versa.
One of the most interesting components shown in the screenshot above is the WFP (Windows Filtering Platform) Callout API. If we zoomed in on that, it might look something like this:
Developers are free to plug in their own modules into the appropriate places in this stack. For instance, antivirus products typically use a "filter driver" that plugs in to this model and inspects network traffic or provides firewall capabilities. The Windows Firewall service also obviously fits in to this model as well.
If you wanted to write an application that records network traffic, such as Wireshark, then the appropriate way to do it would be to use a driver of your own, and insert it into the stack as low as possible so that it can detect network packets before your firewall module has a chance to drop them.
So there are many "drivers" involved in this process. Many different types of drivers too. Also, other forms of input/output on the system, such as hard disk drive reads and writes, follow very similar models.
One other note - WFP callouts are not the only way to insinuate yourself into the network stack. WinPCap as an example, interfaces with NDIS directly with a driver, meaning it has a chance to intercept traffic before any filtering has taken place at all.
NDIS Drivers
WinPCap
References:
Next Generation TCP/IP Stack in Vista+
Windows Filtering Platform Architecture
As Ryan Ries' answer says:
and this is a description, in the WinPcap documentation, of how that works.