Skip to content

Commit

Permalink
net/mbedtls_net_connect: Preventing double close problem
Browse files Browse the repository at this point in the history
In the test examples and real usage scenarios, 'mbedtls_net_free' is called after 'mbedtls_net_connect' fails, which will cause the problem of double close the same fd. It is possible to close this closed fd which has been applied by other link.

Signed-off-by: makejian <[email protected]>
  • Loading branch information
ThePassionate committed Oct 22, 2024
1 parent 2ca6c28 commit 430a267
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
4 changes: 4 additions & 0 deletions ChangeLog.d/replace-close-with-mbedtls_net_close.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Bugfix
* Use 'mbedtls_net_close' instead of 'close' in 'mbedtls_net_bind'
and 'mbedtls_net_connect' to prevent possible double close fd
problems. Fixes #9711.
8 changes: 4 additions & 4 deletions library/net_sockets.c
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host,
break;
}

close(ctx->fd);
mbedtls_net_close(ctx);
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}

Expand Down Expand Up @@ -237,21 +237,21 @@ int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip, const char *
n = 1;
if (setsockopt(ctx->fd, SOL_SOCKET, SO_REUSEADDR,
(const char *) &n, sizeof(n)) != 0) {
close(ctx->fd);
mbedtls_net_close(ctx);
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}

if (bind(ctx->fd, cur->ai_addr, MSVC_INT_CAST cur->ai_addrlen) != 0) {
close(ctx->fd);
mbedtls_net_close(ctx);
ret = MBEDTLS_ERR_NET_BIND_FAILED;
continue;
}

/* Listen only makes sense for TCP */
if (proto == MBEDTLS_NET_PROTO_TCP) {
if (listen(ctx->fd, MBEDTLS_NET_LISTEN_BACKLOG) != 0) {
close(ctx->fd);
mbedtls_net_close(ctx);
ret = MBEDTLS_ERR_NET_LISTEN_FAILED;
continue;
}
Expand Down

0 comments on commit 430a267

Please sign in to comment.