Ensure Ncat receives enough bytes during SOCKS negotiation

This commit is contained in:
dmiller 2026-04-16 23:36:46 +00:00
parent ff5ea1b9ad
commit b477941dfd

View file

@ -509,6 +509,18 @@ bail:
return -1;
}
static int recv_bytes(int sd, char *buf, size_t len)
{
int t = 0;
while (t < len) {
int n = recv(sd, buf + t, len - t, 0);
if (n <= 0) {
return n;
}
t += n;
}
return t;
}
/* SOCKS4a support
* Return a usable socket descriptor after
@ -587,7 +599,7 @@ static int do_proxy_socks4(void)
/* The size of the socks4 response is 8 bytes. So read exactly
8 bytes from the buffer */
if (recv(sd, socksbuf, 8, 0) < 0) {
if (recv_bytes(sd, socksbuf, 8) < 8) {
loguser("Error: short response from proxy.\n");
close(sd);
return -1;
@ -650,7 +662,7 @@ static int do_proxy_socks5(void)
}
/* connect response just two bytes, version and auth method */
if (recv(sd, socksbuf, 2, 0) < 0) {
if (recv_bytes(sd, socksbuf, 2) < 2) {
loguser("Error: malformed connect response from proxy.\n");
close(sd);
return -1;
@ -732,7 +744,7 @@ static int do_proxy_socks5(void)
return -1;
}
if (recv(sd, socksbuf, 2, 0) < 0) {
if (recv_bytes(sd, socksbuf, 2) < 2) {
loguser("Error: malformed proxy authentication response.\n");
close(sd);
return -1;
@ -815,7 +827,7 @@ static int do_proxy_socks5(void)
return -1;
}
if (recv(sd, socksbuf, 4, 0) < 0) {
if (recv_bytes(sd, socksbuf, 4) < 4) {
loguser("Error: malformed request response from proxy.\n");
close(sd);
return -1;
@ -878,7 +890,7 @@ static int do_proxy_socks5(void)
bndaddrlen = 16 + 2;
break;
case SOCKS5_ATYP_NAME:
if (recv(sd, socksbuf, 1, 0) < 0) {
if (recv_bytes(sd, socksbuf, 1) < 1) {
loguser("Error: malformed request response from proxy.\n");
close(sd);
return -1;
@ -891,7 +903,7 @@ static int do_proxy_socks5(void)
return -1;
}
if (recv(sd, bndaddr, bndaddrlen, 0) < 0) {
if (recv_bytes(sd, bndaddr, bndaddrlen) < bndaddrlen) {
loguser("Error: malformed request response from proxy.\n");
close(sd);
return -1;