Skip to content

Commit 17ddcc0

Browse files
rveerama1nashif
authored andcommitted
net: tcp: Accept connections only in LISTENING state
Issue noticed with following scenario. 1) TCP server is listening for connections but will handle only one connection at a time (e.g. echo-server sample) 2) Client A connects, and the connection is accepted. 3) Client B connects, instead of denying a connection, it is "auto" accepted (this is the actual bug) even if the application has not called accept(). 4) After the connection A is closed, the connection B gets accepted by application but now the closed connection A will cause confusion in the net-stack 5) This confusion can cause memory leak or double free in the TCP core. It is not easy to trigger this issue because it depends on timing of the connections A & B. Fixes: #18308 Signed-off-by: Ravi kumar Veeramally <[email protected]>
1 parent 261c0d5 commit 17ddcc0

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

subsys/net/ip/tcp.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2264,6 +2264,11 @@ NET_CONN_CB(tcp_syn_rcvd)
22642264

22652265
switch (net_tcp_get_state(tcp)) {
22662266
case NET_TCP_LISTEN:
2267+
if (net_context_get_state(context) != NET_CONTEXT_LISTENING) {
2268+
NET_DBG("Context %p is not listening", context);
2269+
return NET_DROP;
2270+
}
2271+
22672272
net_context_set_iface(context, net_pkt_iface(pkt));
22682273
break;
22692274
case NET_TCP_SYN_RCVD:
@@ -2450,6 +2455,14 @@ NET_CONN_CB(tcp_syn_rcvd)
24502455
0,
24512456
context->user_data);
24522457
net_pkt_unref(pkt);
2458+
2459+
/* Set the context in CONNECTED state, so that it can not
2460+
* accept any new connections. If application is ready to
2461+
* accept the connection, zsock_accept_ctx() will set
2462+
* the state back to LISTENING.
2463+
*/
2464+
net_context_set_state(context, NET_CONTEXT_CONNECTED);
2465+
24532466
return NET_OK;
24542467
}
24552468

subsys/net/lib/sockets/sockets.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,10 @@ int zsock_accept_ctx(struct net_context *parent, struct sockaddr *addr,
382382
return -1;
383383
}
384384

385+
if (net_context_get_ip_proto(parent) == IPPROTO_TCP) {
386+
net_context_set_state(parent, NET_CONTEXT_LISTENING);
387+
}
388+
385389
struct net_context *ctx = k_fifo_get(&parent->accept_q, K_FOREVER);
386390

387391
#ifdef CONFIG_USERSPACE

0 commit comments

Comments
 (0)