mdlayher / raw

Package raw enables reading and writing data at the device driver level for a network interface. MIT Licensed.
MIT License
425 stars 71 forks source link

raw: allow specifying a filter at creation #44

Closed lmb closed 5 years ago

lmb commented 5 years ago

Packet filtering on Linux raw sockets suffers from a race condition: packets are queued on a raw socket as soon as it is created. Attaching a filter via SetBPF does not clear the queue, and so the next ReadFrom after SetBPF may return a random packet.

Fix this by not specifying a protocol at socket creation time, which prevents the socket from capturing packets from the get go. We can then attach a filter. Finally, we call Bind which enables capturing packets for the protocol requested by the user.

See [1] for more information on the issue.

1: https://github.com/the-tcpdump-group/libpcap/blob/4f2b0f5befaa75c18a68a6849c759fe94c885727/pcap-linux.c#L7501

arthurfabre commented 5 years ago

Might not matter, but this only works for setting the initial filter. Updating the filter afterwards can still return packets that match the old filter. Maybe we could have a FlushAndSetBPF() function that uses the libpcap approach: