dotpcap / sharppcap

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

AccessViolationException with WinDivert and Socket/Flow layers #290

Closed alexalok closed 3 years ago

alexalok commented 3 years ago

Hi!

I've noticed that SharpPcap tries to read packet data every time it receives an event from WinDivert. However, it looks like some events do not have any which leads to AccessViolationException when trying to access the non-existing data.

Simple repro:

var device = new WinDivertDevice()
{
    Flags = 1 | 4, // WINDIVERT_FLAG_SNIFF | WINDIVERT_FLAG_RECV_ONLY
    Filter = "outbound",
    Layer = WinDivertLayer.Socket
};
device.OnPacketArrival += (_, _) => { };; 
device.Open(new DeviceConfiguration());
device.StartCapture();

For instance, it crashes on an WINDIVERT_EVENT_SOCKET_BIND event: image

alexalok commented 3 years ago

Okay, this is strange. Please have a look at the minimum repro attached. Notice that despite buffer not being used (even VS warns me about an unused variable) it becomes "damaged" after WinDivertRecv is executed and debugger shows "Unable to read memory" when trying to evaluate the variable.

I am quite new to the unsafe part of C# world so any tips/hints would be appreciated!

image

alexalok commented 3 years ago

Ok, so I believe this is due to WinDivertAddress struct being different for different layers: https://www.reqrypt.org/windivert-doc.html#divert_address Trying to come up with the correct struct for the flow layer...

kayoub5 commented 3 years ago

The imlimentation I wrote for windivert only supports network flow (since that was the only flow simular to winpcap) feel free to open a PR for support of other flows.

alexalok commented 3 years ago

Thanks for clarifying! I'll do some more research and open a PR once I have something decent.