How do I hook the TCP stack in Windows to sniff and modify packets?

Eyal picture Eyal · Mar 29, 2009 · Viewed 15.4k times · Source

I'd like to write a packet sniffer and editor for Windows. I want to able to see the contents of all packets entering and leaving my system and possibly modify them. Any language is fine but I'd like it to run fast enough that it won't burden the system.

I've read a little about WinPcap but the documentation claims that you can't use WinPcap to create a firewall because it can't drop packets. What tools will help me write this software?

Answer

froh42 picture froh42 · Mar 29, 2009

Been there, done that :-) Back in 2000 my first Windows program ever was a filter hook driver.

What I did was implementing the filter hook driver and writing a userspace application that prepared a filter table on what to allow and what to disallow. When you get around your initial set of blue screens (see below for my debug tip in kernel mode) the filter mode driver is quite easy to use ... it gives each packet to a function you wrote and depending on the return code drops it or lets it pass.

Unfortunatley packets at that level are QUITE raw, fragments are not reassembled and it looks more like the "network card" end of things (but no ethernet headers anymore). So you'll have quite a bad time decoding the packets to filter with that solution.

There also is the firewall hook driver, as discussed in this codeproject article.

If you are on Vista or Server 2008 you'd better have a look at WFP (Windows Filtering Platform) instead, that seems to be the mandated API of the day for writing firewalls. I don't know about it other than google turing it up some minutes ago when I googled for the filter hook driver.

Update: Forgot the debug tip:

Sysinternals DbgView shows kernel-mode DbgPrint output, and more important - it can also read them from the dump file your last blue screen produced. So sprinkle your code with dbgprint and if it bluescreens just load the dump into dbgview to see what happened before it died ... VERY useful. Using this I managed without having a kernel debugger.