tcp: drain the queues of a listen() that fails

If listen() fails on a TCP socket that has listened before, the sockets
of connections from the earlier listen() can leak, together with their
network namespace.

inet_csk_listen_start() sets TCP_LISTEN before it calls get_port() and
hash(), and its error path sets TCP_CLOSE again, then purges the Fast
Open RST queue since commit 342e62fd34c2 ("tcp: purge Fast Open RST
queue when listen() fails"), but not the accept queue. Pending request
socks outlive an earlier listen() and still point to the socket, so in
TCP_LISTEN, inet_csk_reqsk_queue_add() adds them to the accept queue,
with their new child. These entries, and the sockets that they hold,
are never freed, since close() drains this queue only in TCP_LISTEN and
the next listen() stores NULL in rskq_accept_head.

The fix used here is to call inet_csk_listen_stop() after the error path
sets TCP_CLOSE, which also purges the RST queue, except for an MPTCP
subflow, which needs mptcp_subflow_queue_clean() first: only its RST
queue is purged here, and mptcp_listen() has to drain its accept queue,
which is done in the next patch, "mptcp: drain the queues of a listen()
that fails".

This issue has been found with the help of an LLM, and reproduced in a
VM, with the reproducer shared with the original version of this patch,
run as an unprivileged user: listen() failing with EADDRINUSE in a loop,
while the connections of an earlier listen() complete. Without this
patch, sockets were leaked, and network namespaces too when each round
was in its own one, without any message from the kernel:

  result: request socks: 10000 made, 2535 left. Sockets: 33373 made, 5070 left
  [...]
  result: namespaces: 1000 made, 694 taken down, 306 left

Fixes: 079096f103fa ("tcp/dccp: install syn_recv requests into ehash table")
Cc: stable@vger.kernel.org
Signed-off-by: Chris Mason <mason@kernel.org>
[ Shorter comments. Commit message: how the issue was found, and its
  symptoms. On top of commit 342e62fd34c2, with a Fixes tag for the
  accept queue. ]
Signed-off-by: Matthieu Baerts (NGI0) <matttbe@kernel.org>
Reviewed-by: Kuniyuki Iwashima <kuniyu@google.com>
Link: https://patch.msgid.link/20261123-net-mptcp-misc-fixes-7-4-rc5-v1-1-278042217e8d@kernel.org
Signed-off-by: Paolo Abeni <pabeni@redhat.com>
1 file changed