jvinet / knock

A port-knocking daemon
http://www.zeroflux.org/projects/knock
GNU General Public License v2.0
552 stars 114 forks source link

Don't use a timeout of 0 in pcap_open_live() #5

Closed guyharris closed 10 years ago

guyharris commented 10 years ago

To quote the pcap(3PCAP) man page:

   read timeout
          If, when capturing,  packets  are  delivered  as  soon  as  they
          arrive,  the  application capturing the packets will be woken up
          for each packet as it arrives, and might have  to  make  one  or
          more calls to the operating system to fetch each packet.

          If,  instead,  packets are not delivered as soon as they arrive,
          but are delivered after a short delay (called a "read timeout"),
          more  than  one packet can be accumulated before the packets are
          delivered, so that a single wakeup would be  done  for  multiple
          packets,  and  each  set  of  calls made to the operating system
          would supply multiple packets,  rather  than  a  single  packet.
          This reduces the per-packet CPU overhead if packets are arriving
          at a high rate, increasing the number of packets per second that
          can be captured.

          The  read  timeout is required so that an application won't wait
          for the operating system's capture  buffer  to  fill  up  before
          packets are delivered; if packets are arriving slowly, that wait
          could take an arbitrarily long period of time.

          Not all platforms support a  read  timeout;  on  platforms  that
          don't,  the read timeout is ignored.  A zero value for the time-
          out, on platforms that support a read timeout, will cause a read
          to wait forever to allow enough packets to arrive, with no time-
          out.

"Enough packets to arrive" can mean "enough packets to fill up a buffer", and, in fact, does mean so on, for example, *BSD, OS X, and Solaris. This is presumably why knockd does not use a timeout of 0 on FreeBSD or OS X; it should also not do so on NetBSD, OpenBSD, DragonFly BSD, or Solaris.

This means that "wait forever" can mean "wait a very very very very long time" if packets are arriving slowly - and if they stop arriving at all, it truly can mean "wait forever".

And, with the advent of libpcap 1.5, which uses TPACKET_V3 (which is more BSD BPF-like than earlier versions of the memory-mapped packet capture code) on Linux, "enough packets to arrive" can mean "enough packets to fill up a buffer" on Linux.

I would strongly suggest that knockd not use a timeout of 0 on any platforms, and pick an appropriate timeout value instead. That also means one less #ifdef....

jvinet commented 10 years ago

Thanks, Guy. I've pushed up a change for this.