dotpcap / sharppcap

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

WinDivertDevice.SendPacket wrongly infers interface index #527

Open verdie-g opened 3 months ago

verdie-g commented 3 months ago

When I use WinDivertDevice.SendPacket without specifying an ICaptureHeader, the wrong interface is chosen.

WinDivertDevice device = new()
{
    Filter = "XXX",
    Layer = WinDivertLayer.Network,
    Flags = 0,
};

// ...

device.GetNextPacket(out PacketCapture capture);

// ...

// 1. This works fine
device.SendPacket(capture.GetPacket(), capture.Header);
// 2. This doesn't work fine
device.SendPacket(capture.GetPacket());

After some debugging, I saw that 1. uses IfIdx=0, SubIfIdx=7 but 2. uses IfIdx=7, SubIfIdx=0 (unset).

Does this code do the best it can to get the right interface or do you think it could be improved? https://github.com/dotpcap/sharppcap/blob/15c95ecb2d7150b92a31dc6a2a3114aa4c6b683c/SharpPcap/WinDivert/WinDivertDevice.cs#L280-L303

I'm on Windows 11 23H2

> Get-NetAdapter | Select-Object Name, InterfaceIndex, Status

Name       InterfaceIndex Status
----       -------------- ------
Ethernet 2              8 Disconnected
Ethernet                7 Up
kayoub5 commented 2 months ago

@verdie-g

// 1. This works fine
device.SendPacket(capture.GetPacket(), capture.Header);

This call preserve the metadata of the received packet, the metadata include the direction of the packet, what interface it was received on, etc

the metadata is stored in the capture header.

// 2. This doesn't work fine
device.SendPacket(capture.GetPacket());

In this case, you took the packet data, and removed all associated metadata, in this case sharppcap will use the default configuration libpcap driver would use, this means it will assume the packet is outgoing from the system, which may not be the case in the original metadata.

verdie-g commented 2 months ago

it will assume the packet is outgoing from the system

Could you help me understand where in the code that assumption is made.

if (IpHelper.IsOutbound((int)addr.IfIdx, src, dst)) 
     { 
         addr.Flags |= WinDivertPacketFlags.Outbound; 
     } 

here it looks like it can know if the packet is inbound or outbound.

kayoub5 commented 2 months ago

@verdie-g what ip addresses does the interferences and the packet have?

os version?

windivert driver version?

verdie-g commented 2 months ago

Remote ip: 54.171.35.223 OS: 11 23H2 Windivert: 2.2.2

kayoub5 commented 2 months ago

@verdie-g I can't reproduce the problem, the logic implemented in sharppcap does a "Best Effort" guess of what interface should be used, and uses GetBestInterfaceEx API

@basil00 Is there a better API to infer the interface from the packet address?

verdie-g commented 2 months ago

It's fine, I realized later that using WinDivertSend without the original WINDIVERT_ADDRESS was probably a bad idea.