Anon port selection

Patrick Mahan mahan at mahan.org
Fri Jan 8 15:30:23 UTC 2010


See inline -

Janne Huttunen wrote:
> Hi!
> 
> The selection of anonymous port in FreeBSD seems to act
> a bit weird (bug?). This was first observed on actual
> use on FreeBSD 6.2, but I have verified that the it
> behaves the same on a December snapshot of CURRENT too.
> 
> 1. A process creates an UDP socket and sends a packet
>    from it (at which point a local port is assigned
>    for it).
> 2. Another process creates an UDP socket, sets
>    SO_REUSEADDR (or SO_REUSEPORT) and sends a packet
>    from it (at which point a local port is assigned
>    for it).
> 
> Every now and then it happens that the second process
> gets the same local port as the first one. If the
> second process doesn't set the socket option this
> won't happen. Note however, that the first process
> does not have to cooperate in any way i.e. it does
> not set any options.
> 
> Now, I'm fairly newbie when it comes to the FreeBSD
> IP stack, but it seems to me that this phenomenon is
> caused by the code in in_pcbconnect_setup(). If the
> local port is zero the in_pcbbind_setup() is called
> to select a port. That routine is called with the
> local address set to the source address selected for
> the outgoing packet, but when the port has been
> selected, it is committed with INADDR_ANY as the
> local address. Then when the second process in
> in_pcbbind_setup() tries to check if the port is
> already in use, it won't match the INADDR_ANY and
> assigns the same port again.

Well it has been almost 20 years since I first ran across
this issue and was told back then that it was "as designed".
I believe you will see that this only happens when INADDR_ANY
is in effect.  If instead you use a specific IP address as
your source it should not happen.  I have not had a chance
to really go over the FreeBSD TCP/IP stack since the beginnings
of FreeBSD back in the early 90's (we were using basically the
same code for our product on a different architecture).

As an example of what the person was explaining he pointed to
the BIND code which expressly binds to each interface IP address
instead of too INADDR_ANY to prevent snooping.

I apologize if I am somewhat off base, having only re-entered
playing with FreeBSD in the last few months.

Patrick


More information about the freebsd-net mailing list