Tuesday, July 16, 2013

TCP_TW_REUSE vs TCP_TW_RECYCLE


First of all let take a look at the meaning of these two variables,
tcp_tw_reuse (Boolean; default: disabled; since Linux 2.4.19/2.6):
Allow to reuse TIME_WAIT sockets for new connections when it is safe from protocol viewpoint.  It should not be changed without advice/request of technical experts.
tcp_tw_recycle (Boolean; default: disabled; since Linux 2.4):
Enable fast recycling of TIME_WAIT sockets.  Enabling this option is not recommended since this causes problems when working with NAT (Network Address Translation).

By default, both tcp_tw_reuse and tcp_tw_recycle are disabled, the kernel will make sure that sockets in "TIME_WAIT" state will remain in that state long enough -- long enough to be sure that packets belonging to future connections will not be mistaken by late packets of the old connection.

When you enable tcp_tw_reuse, sockets in TIME_WAIT state can be used before they expire, and the kernel will try to make sure that there is no collision regarding TCP sequence numbers. When you enable tcp_tw_recycle, the kernel becomes a little bit more aggressive. It tracks the last timestamp used by each remote host having a connection in TIME_WAIT state, and allow to re-use a socket if the timestamp has correctly increased.

Why tcp_tw_reuse is safer than tcp_tw_recycle? Because tcp_tw_reuse allows one to make use of the same socket if there is already one in TIME_WAIT with the same TCP parameters and TIME_WAIT is a state that no further traffic is expected. tcp_tw_recycle on the other hand will just reuse the sockets that are in TIME_WAIT with the same parameters regardless of the state, which can confuse stateful firewalls which might be expecting different packets.

To enable tcp_tw_reuse or tcp_tw_recycle:
$ echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse
$ echo 1 > /proc/sys/net/ipv4/tcp_tw_recycle

or
$ sysctl -w net.ipv4.tcp_tw_reuse=1
$ sysctl -w net.ipv4.tcp_tw_recycle=1

No comments: