dotpcap / sharppcap

Official repository - Fully managed, cross platform (Windows, Mac, Linux) .NET library for capturing packets
1.34k stars 268 forks source link

Packet manipulation with WinDivert #289

Closed alexalok closed 3 years ago

alexalok commented 3 years ago

Hi!

I have tried to come up with a simple example of packet manipulation using WinDivert but failed miserably. At last I've noticed that during device opening there's a special flag being passed: https://github.com/chmorgan/sharppcap/blob/774b7f03ded1abd2845ab09641faca1052b9b369/SharpPcap/WinDivert/WinDivertDevice.cs#L250

which is, according to the WinDivert source, is

#define WINDIVERT_FLAG_SNIFF            0x0001

This flag, according to WinDivert documentation,

... opens the WinDivert handle in packet sniffing mode. In packet sniffing mode the original packet is not dropped-and-diverted (the default) but copied-and-diverted. This mode is useful for implementing packet sniffing tools similar to those applications that currently use Winpcap.

So I wonder whether this is a deliberate limitation of SharpPcap or has it just not been implemented yet. If the latter is the case, I'd be happy to work on an implementation.

kayoub5 commented 3 years ago

the value WINDIVERT_FLAG_SNIFF was chosen as default to have a simular behavior to winpcap (original driver of sharppcap)

other values for the flags could be used as well.

When you said that you failed, what kind of error did you run into?

alexalok commented 3 years ago

Thank you for your answer. Actually looks like I've found out the culprit of the issue. I was following these instructions which include setting WINDIVERT_FLAG_DROP flag.

The docs, however, state the following:

This flag indicates that the user application does not intend to read matching packets with WinDivertRecv(), instead the packets should be silently dropped. This is useful for implementing simple packet filters using the WinDivert filter language.

WinDivertRecv() should not be used on any WinDivert handle created with the WINDIVERT_FLAG_DROP set.

I unset all flags and now everything works as a charm.

UDP: sorry, forgot to answer on what the actual error was. There was no error, just OnPacketArrival never invoked.

alexalok commented 3 years ago

Looks like WINDIVERT_FLAG_DROP in 1.x versions of WinDivert has a different behavior and indeed dropped the packet but also sent it to WinDivertRecv. In 2.x the this behavior is now by-default and WINDIVERT_FLAG_DROP just prevents packets from going into WinDivertRecv.