[net.unix-wizards] 4.2bsd/rlogin/source port choices

stanonik@nprdc.arpa (Ron Stanonik) (07/16/85)

4.2bsd/rlogin's use of reserved ports for user authentication
seemed the cause of a little problem here.  While a user was
rlogin'ed from a sun to a vax, the sun crashed.  After the sun
rebooted the user was unable to rlogin to the vax (connection
timed out?), apparently because the vax still thought the previous
connection from the sun was established, and the sun was trying
to reuse the same reserved port.  (rlogin chooses the source port
from the first available port starting at 1023, working downward.)
Of course killing the login on the vax marked the connection closed
and cleared up the problem, but there must be a better/nonmanual
way.  Have we've overlooked a 4.2bsd mod which allows rlogin or
the tcp's to sort this out?

Thanks,

Ron Stanonik
stanonik@nprdc

geof@su-shasta.ARPA (07/17/85)

The TCP source port for rlogin should be chosen in a manner that makes
it unlikely for the same port to be reused twice in a row.  "Twice in a
row" includes the possibility that the ports will be chosen before and
after crashes, so a RAM counter is inappropriate.  4.2's apparent
method of grabbing closest port below 1024 that is not currently used
tends to choose the same port twice in a row with high probability in a
number of cases.  This algorithm is not suitable for choosing TCP port
numbers (Gosh, I hope the kernel does a better job!).

A better technique is to generate some random number in the right range
of ports each time a port number is needed, and regenerate another if
you fail.  A simple expediency is to use the low-order bits of a
millisecond clock.  A user process on Unix (with a one-second clock)
might use:

	long now;

	time(&now);
	sleep(1);
	port = htons( (now + getpid()) % 512) + 512 );

to get a number in the range [512,1024), or

	port = htons( (now + getpid()) | 0x8000 );

to get a port number in the "temporary" range.

- Geof