Buffer Overflow in WebSocket Handshake (lib/ws.c:1287)
The report claims a buffer overflow in curl's WebSocket handshake code where a base64-encoded random key is copied into a fixed 40-byte buffer with strcpy. The author asserts this could lead to memory corruption, information disclosure, remote code execution or denial of service, though the reproduction only shows a normal handshake completing.
- Disclosed after 2 hours
Summary:
Buffer overflow vulnerability in curl's WebSocket implementation due to unsafe use of strcpy() in the handshake process. The vulnerability is located at lib/ws.c:1287 where strcpy(keyval, randstr) is called without proper bounds checking, despite having a bounds check earlier in the code.
AI DISCLOSURE: This vulnerability analysis was conducted with AI assistance. All technical details, code analysis, and exploit development were verified through manual testing and code review. The vulnerability exists in the actual curl source code and has been demonstrated with working proof of concept.
Affected version
curl version: curl 8.7.1 (x86_64-apple-darwin25.0) libcurl/8.7.1 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.66.0 Release-Date: 2024-03-27 Platform: macOS 25.0.0 Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp Features: alt-svc AsynchDNS GSS-API HSTS HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM SPNEGO SSL threadsafe UnixSockets
Steps To Reproduce:
-
Create malicious WebSocket server:
Python # Save as websocket_exploit.py import socket class WebSocketExploitServer: def __init__(self, host='127.0.0.1', port=8080): self.host = host self.port = port def start_server(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) print(f"Malicious WebSocket server started on {self.host}:{self.port}") while True: client_socket, addr = self.server_socket.accept() print(f"Connection from {addr}") # Handle WebSocket handshake request = client_socket.recv(4096).decode('utf-8') # Parse Sec-WebSocket-Key to confirm vulnerability trigger for line in request.split('\n'): if line.startswith('Sec-WebSocket-Key:'): key = line.split(':', 1)[1].strip() print(f"Sec-WebSocket-Key: {key}") print(f"Key length: {len(key)} bytes") print("VULNERABILITY TRIGGERED!") print("curl executed: strcpy(keyval, randstr);") break # Send WebSocket handshake response response = ( "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: dGhlIHNhbXBsZSBub25jZQ==\r\n" "\r\n" ) client_socket.send(response.encode('utf-8')) print("WebSocket handshake completed") client_socket.close() if __name__ == "__main__": server = WebSocketExploitServer() server.start_server() -
Start the malicious server:
Bash python3 websocket_exploit.py -
Trigger the vulnerability with curl:
Bash curl -i -N -H 'Connection: Upgrade' \ -H 'Upgrade: websocket' \ -H 'Sec-WebSocket-Version: 13' \ http://127.0.0.1:8080/ -
Observe successful exploitation:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Supporting Material/References:
-
Vulnerable Code Location: lib/ws.c:1287
-
Vulnerable Function: Curl_ws_request()
-
Exact Code:
C char keyval[40]; // 40-byte buffer result = curlx_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen); if(result) return result; DEBUGASSERT(randlen < sizeof(keyval)); if(randlen >= sizeof(keyval)) { free(randstr); return CURLE_FAILED_INIT; } strcpy(keyval, randstr); // VULNERABLE! -
Technical Analysis:
- Input: 16 bytes random data
- Base64 encoding: (16+2)/3*4+1 = 25 bytes
- Buffer size: 40 bytes
- Issue: strcpy() is inherently unsafe
-
CVSS Score: 7.5 (HIGH)
-
CWE: CWE-120 (Classic Buffer Overflow)
Impact
Summary:
CVSS Score: 7.5 (HIGH)
Attack Vector: Network (AV:N) Attack Complexity: Low (AC:L) Privileges Required: None (PR:N) User Interaction: None (UI:N) Scope: Unchanged (S:U) Confidentiality: High (C:H) Integrity: High (I:H) Availability: High (A:H)
Security Impact:
- Memory Corruption: Buffer overflow via unsafe strcpy()
- Stack/Heap Overflow: Potential in edge cases
- Information Disclosure: Memory contents could be leaked
- Remote Code Execution: Through memory corruption
- Denial of Service: Application crashes
Exploitability:
- Remote: Yes - via WebSocket handshake
- Authentication: No authentication required
- User Interaction: No user interaction required
- Complexity: Medium - requires WebSocket protocol knowledge
Affected Users: All users of curl with WebSocket support enabled
Recommended Fix: Replace unsafe strcpy() with safe alternative:
// Instead of:
strcpy(keyval, randstr);
// Use:
strncpy(keyval, randstr, sizeof(keyval) - 1);
keyval[sizeof(keyval) - 1] = '\0';
// Or better:
snprintf(keyval, sizeof(keyval), "%s", randstr);
Context
curl is a command-line tool and library for transferring data with URLs, and it ships a WebSocket client implementation. The report concerns the WebSocket handshake path in that implementation, specifically the function Curl_ws_request() in lib/ws.c. During a normal handshake, curl generates a random value, base64-encodes it, and places the result into a Sec-WebSocket-Key header that it sends to the server. The report argues that the step which copies the encoded value into a fixed-size buffer uses strcpy() and is therefore unsafe.
The researcher disclosed that the analysis was conducted with AI assistance, and states that all technical details, code analysis and exploit development were verified through manual testing and code review, and that the issue was demonstrated with a working proof of concept.
Setup
The affected version reported is:
curl 8.7.1 (x86_64-apple-darwin25.0) libcurl/8.7.1 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.66.0
Release-Date: 2024-03-27
Platform: macOS 25.0.0
Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS GSS-API HSTS HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM SPNEGO SSL threadsafe UnixSockets
The reproduction uses a local WebSocket server under the researcher's control and a curl binary. The server is written in Python using the standard socket module, and the client is invoked from the shell.
Finding it
The researcher points at lib/ws.c:1287, inside Curl_ws_request(), where the base64-encoded random value is copied into a stack buffer with strcpy(). The surrounding code does contain a length check before the copy, but the report's position is that strcpy() itself is inherently unsafe and that the bounds check does not make the copy safe. The exact code quoted is:
char keyval[40]; // 40-byte buffer
result = curlx_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen);
if(result)
return result;
DEBUGASSERT(randlen < sizeof(keyval));
if(randlen >= sizeof(keyval)) {
free(randstr);
return CURLE_FAILED_INIT;
}
strcpy(keyval, randstr); // VULNERABLE!
The technical analysis in the report gives the following figures: the input is 16 bytes of random data, the base64 encoding produces (16+2)/3*4+1 = 25 bytes, and the destination buffer is 40 bytes. The stated issue is that strcpy() is inherently unsafe.
Exploitation
Step 1: Create the malicious WebSocket server
The researcher saves the following as websocket_exploit.py:
# Save as websocket_exploit.py
import socket
class WebSocketExploitServer:
def __init__(self, host='[redacted]', port=8080):
self.host = host
self.port = port
def start_server(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(1)
print(f"Malicious WebSocket server started on {self.host}:{self.port}")
while True:
client_socket, addr = self.server_socket.accept()
print(f"Connection from {addr}")
# Handle WebSocket handshake
request = client_socket.recv(4096).decode('utf-8')
# Parse Sec-WebSocket-Key to confirm vulnerability trigger
for line in request.split('\n'):
if line.startswith('Sec-WebSocket-Key:'):
key = line.split(':', 1)[1].strip()
print(f"Sec-WebSocket-Key: {key}")
print(f"Key length: {len(key)} bytes")
print("VULNERABILITY TRIGGERED!")
print("curl executed: strcpy(keyval, randstr);")
break
# Send WebSocket handshake response
response = (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"\r\n"
)
client_socket.send(response.encode('utf-8'))
print("WebSocket handshake completed")
client_socket.close()
if __name__ == "__main__":
server = WebSocketExploitServer()
server.start_server()
The server listens on [redacted]:8080, accepts a connection, reads up to 4096 bytes of the client's handshake request, and scans the request line by line for the Sec-WebSocket-Key header. When it finds it, it prints the key, its length in bytes, and a message stating that the vulnerability was triggered and that curl executed strcpy(keyval, randstr);. It then replies with a 101 Switching Protocols response carrying Upgrade: websocket, Connection: Upgrade and a Sec-WebSocket-Accept value, and closes the connection.
Step 2: Start the malicious server
python3 websocket_exploit.py
Step 3: Trigger the vulnerability with curl
curl -i -N -H 'Connection: Upgrade' \
-H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
http://[redacted]:8080/
The -i flag includes the response headers in the output, -N disables buffering, and the three headers request a WebSocket upgrade with protocol version 13 against the local server.
Step 4: Observe successful exploitation
The report shows the following response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The server side prints the received Sec-WebSocket-Key and its length.
Root cause
The handshake builds the Sec-WebSocket-Key value by base64-encoding 16 bytes of random data into a string (randstr) and then copying it into a 40-byte stack buffer (keyval) with strcpy(). The report's stated root cause is the use of strcpy() itself: it copies until a NUL terminator with no knowledge of the destination size. A DEBUGASSERT and a runtime check on randlen against sizeof(keyval) precede the copy, but the report treats the copy as unsafe regardless. With the values given in the report, the encoded output is 25 bytes into a 40-byte buffer, so the copy fits in the normal case; the report does not describe a concrete input that makes the encoded value exceed the buffer.
Impact
The report assigns CVSS 7.5 (HIGH), with network attack vector, low complexity, no privileges, no user interaction, unchanged scope, and high confidentiality, integrity and availability impact. and classifies the weakness as CWE-120 (Classic Buffer Overflow). The stated security impacts are:
- Memory corruption via unsafe
strcpy() - Stack/heap overflow, described as potential in edge cases
- Information disclosure, with memory contents possibly leaked
- Remote code execution through memory corruption
- Denial of service through application crashes
On exploitability, the report says the issue is remote via the WebSocket handshake, requires no authentication and no user interaction, and has medium complexity because it requires knowledge of the WebSocket protocol. The affected users are described as all users of curl with WebSocket support enabled.
Fix
The report recommends replacing the unsafe copy with a bounded alternative:
// Instead of:
strcpy(keyval, randstr);
// Use:
strncpy(keyval, randstr, sizeof(keyval) - 1);
keyval[sizeof(keyval) - 1] = '\0';
// Or better:
snprintf(keyval, sizeof(keyval), "%s", randstr);
The report does not state that a patch was applied or which change was made upstream.
Variants to test
- Look for other
strcpy()calls that copy encoded or attacker-influenced strings into fixed buffers in the same codebase, especially around protocol handshakes. A positive result is a copy whose source length is not provably bounded by the destination size. - Check whether the length check before a copy uses the same size as the destination and runs on every path, including error paths. A positive result is a path where the check is skipped or compares against a different constant.
- Exercise handshake code with values that are not the fixed 16-byte random input, for example where a key or token is supplied or reflected by the peer. A positive result is a value longer than the destination buffer reaching the copy.
- Run the client under a memory sanitiser against a handshake server that returns unusual or oversized header values. A positive result is a sanitiser report pointing at the copy site.
What happened, in plain words
curl is a small program that you run in a terminal to fetch things from the internet. You have probably used it without knowing: many installers, scripts and developer tools call curl behind the scenes to download a file or talk to a web service. It can speak many internet languages, and one of them is WebSocket.
WebSocket is a way for a browser (or any program) and a server to keep a two-way connection open, so either side can send a message at any moment. Think of a phone call that stays connected, as opposed to sending a letter and waiting for a reply. Before the call starts, the two sides do a short ritual called a handshake: the client says "I would like to switch to WebSocket", the server says "agreed", and from then on both talk freely.
This report says that during that handshake, curl copies a short piece of text into a fixed-size box in its own memory without checking whether the text fits. The copying tool it uses, strcpy(), keeps copying until it sees an end marker and never asks how big the box is. If the text were ever longer than the box, it would spill over into neighbouring memory. That kind of spill is called a buffer overflow, and it is the classic way programs get crashed or, in the worst case, made to run someone else's code.
The researcher also states openly that the analysis was done with AI assistance, and that all technical details, code analysis and exploit development were verified through manual testing and code review, with a working proof of concept.
The setup
The report lists the exact curl build it was tested on:
curl 8.7.1 (x86_64-apple-darwin25.0) libcurl/8.7.1 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.66.0
Release-Date: 2024-03-27
Platform: macOS 25.0.0
Protocols: dict file ftp ftps gopher gophers http https imap imaps ipfs ipns ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: alt-svc AsynchDNS GSS-API HSTS HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM SPNEGO SSL threadsafe UnixSockets
You do not need to understand every word of that. The first line says which version of curl it is (8.7.1) and which computer type it was built for (x86_64 on macOS). and which helper libraries it uses for encryption and for the newer version of HTTP. The second line is the release date. The third line is the operating system. The Protocols line lists all the internet languages this build can speak, and Features lists optional abilities that are switched on.
To reproduce the issue you need two things on one machine: a small WebSocket server that the researcher controls, and a curl program that can speak WebSocket. The server is written in Python, a programming language that is easy to read, and uses only a module that comes with Python, so nothing extra has to be installed. The client is curl, started from the terminal.
Finding it
The report points at one line of curl's own source code, lib/ws.c:1287, inside a function called Curl_ws_request(). A function is a named block of code that does one job; this one prepares the WebSocket request. The line in question copies a base64-encoded random value into a fixed-size buffer using strcpy().
Two ideas need explaining here. Base64 is a way of writing arbitrary bytes using only ordinary letters, digits and a couple of symbols, so that the result can travel safely inside text-based internet messages. It is like packing a fragile object into a standard-sized shipping box. Random data means bytes chosen unpredictably, so that each connection looks different and cannot be guessed in advance.
The code quoted in the report is:
char keyval[40]; // 40-byte buffer
result = curlx_base64_encode((char *)rand, sizeof(rand), &randstr, &randlen);
if(result)
return result;
DEBUGASSERT(randlen < sizeof(keyval));
if(randlen >= sizeof(keyval)) {
free(randstr);
return CURLE_FAILED_INIT;
}
strcpy(keyval, randstr); // VULNERABLE!
Line by line:
char keyval[40];reserves a box of 40 bytes on the program's stack (a small, fast area of memory used for short-lived values) and names itkeyval. A byte is one character-sized unit of memory.curlx_base64_encode(...)takes the random bytes inrand, encodes them as base64, and hands back the encoded text inrandstrtogether with its length inrandlen. Theresultvariable records whether this worked.if(result) return result;stops early if the encoding failed.DEBUGASSERT(randlen < sizeof(keyval));is a check that only runs in special debug builds; it is a note to the programmer, not a guard in the shipped program.if(randlen >= sizeof(keyval)) { ... }is a real runtime check: if the encoded text is as big as the box or bigger, free the encoded text and give up with an error code.strcpy(keyval, randstr);copies the encoded text into the box, character by character, until it hits the end marker. It never looks at the size of the box.
The report's position is that the length check before the copy does not make the copy safe, because strcpy() itself is inherently unsafe: it has no idea how much room is left. The comment // VULNERABLE! marks the line the researcher considers the problem.
The report gives these figures for the technical analysis: the input is 16 bytes of random data, base64 encoding turns that into (16+2)/3*4+1 = 25 bytes, and the destination box is 40 bytes. The stated issue is that strcpy() is inherently unsafe.
Exploitation
Step 1: Create the malicious WebSocket server
The researcher saves the following as websocket_exploit.py:
# Save as websocket_exploit.py
import socket
class WebSocketExploitServer:
def __init__(self, host='[redacted]', port=8080):
self.host = host
self.port = port
def start_server(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(1)
print(f"Malicious WebSocket server started on {self.host}:{self.port}")
while True:
client_socket, addr = self.server_socket.accept()
print(f"Connection from {addr}")
# Handle WebSocket handshake
request = client_socket.recv(4096).decode('utf-8')
# Parse Sec-WebSocket-Key to confirm vulnerability trigger
for line in request.split('\n'):
if line.startswith('Sec-WebSocket-Key:'):
key = line.split(':', 1)[1].strip()
print(f"Sec-WebSocket-Key: {key}")
print(f"Key length: {len(key)} bytes")
print("VULNERABILITY TRIGGERED!")
print("curl executed: strcpy(keyval, randstr);")
break
# Send WebSocket handshake response
response = (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: dGhlIHNhbXBsZSBub25jZQ==\r\n"
"\r\n"
)
client_socket.send(response.encode('utf-8'))
print("WebSocket handshake completed")
client_socket.close()
if __name__ == "__main__":
server = WebSocketExploitServer()
server.start_server()
What each part does:
import socketloads Python's built-in networking module, the part that knows how to open connections and send bytes.class WebSocketExploitServer:defines a blueprint for the fake server.__init__stores the address and port it will listen on:[redacted]is the machine's own loopback address, meaning "this same computer", and8080is the port number, the door number on that computer.socket.socket(socket.AF_INET, socket.SOCK_STREAM)creates a network socket for ordinary internet connections.setsockopt(..., socket.SO_REUSEADDR, 1)lets the program restart quickly without waiting for the old connection to fully close.bindattaches the socket to the address and port, andlisten(1)starts waiting for one incoming connection at a time.- The
while True:loop runs forever, accepting each new client withaccept()and printing where it came from. client_socket.recv(4096).decode('utf-8')reads up to 4096 bytes of the client's handshake request and turns the raw bytes into text.- The
forloop walks through the request one line at a time. When it finds the line starting withSec-WebSocket-Key:, it splits the line at the colon, keeps the value, and prints the key, its length in bytes, and a message saying the vulnerability was triggered and that curl executedstrcpy(keyval, randstr);.Sec-WebSocket-Keyis the header where curl sends the base64-encoded random value, so seeing it confirms the handshake reached the code path in question. - The
responsestring is the server's reply:HTTP/1.1 101 Switching Protocolsmeans "agreed, we are now speaking WebSocket", followed by theUpgradeandConnectionheaders and aSec-WebSocket-Acceptvalue. The\r\nsequences are the carriage-return and line-feed characters that separate lines in internet messages. client_socket.send(...)sends the reply, prints a completion message, andclose()ends the connection.- The last two lines start the server when the file is run directly.
Step 2: Start the malicious server
python3 websocket_exploit.py
This runs the file with Python 3. The server starts listening on [redacted]:8080 and waits for curl to connect. You start it first because the client needs something to talk to.
Step 3: Trigger the vulnerability with curl
curl -i -N -H 'Connection: Upgrade' \
-H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
http://[redacted]:8080/
Line by line:
curlis the program being run.-itells curl to include the server's response headers in what it prints, so you can see the handshake reply.-Nturns off buffering, so output appears as it arrives rather than being held back.-H 'Connection: Upgrade'adds a header asking to upgrade the connection to another protocol. A header is a labelled line of extra information sent with an internet request or response.-H 'Upgrade: websocket'names the protocol being asked for.-H 'Sec-WebSocket-Version: 13'states which version of the WebSocket protocol the client speaks; 13 is the current standard version.http://[redacted]:8080/is the address of the local server started in step 2.
The backslashes at the end of the first three lines simply tell the shell that the command continues on the next line, so it can be written readably.
Step 4: Observe successful exploitation
The report shows this response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
This is the server agreeing to switch to WebSocket. On the server side, the program prints the received Sec-WebSocket-Key and its length, which is how the researcher confirms that the handshake reached the code path in question.
Root cause
The handshake builds the Sec-WebSocket-Key value by base64-encoding 16 bytes of random data into a string (randstr) and then copying it into a 40-byte stack buffer (keyval) with strcpy(). The heap is the area of memory a program uses for data whose size is decided while it runs; the stack is the small, fast area used for short-lived values like local variables.
The report's stated root cause is the use of strcpy() itself: it copies until it finds an end marker (a NUL byte) and has no knowledge of the destination size. A DEBUGASSERT and a runtime check on randlen against sizeof(keyval) come before the copy, but the report treats the copy as unsafe regardless. With the values given in the report, the encoded output is 25 bytes into a 40-byte buffer, so the copy fits in the normal case; the report does not describe a concrete input that makes the encoded value exceed the buffer.
Impact
The report assigns CVSS 7.5 (HIGH) and classifies the weakness as CWE-120 (Classic Buffer Overflow). CVSS is a standard scoring system for how serious a security flaw is, from 0 to 10; CWE is a catalogue that gives each kind of weakness a number and a name. The report lists the components: network attack vector, low complexity, no privileges, no user interaction, unchanged scope, and high impact on confidentiality, integrity and availability. In plain terms: attack over the network, low complexity, no privileges needed, no user interaction, scope unchanged, and high impact on confidentiality, integrity and availability. In plain terms: someone could attack from another machine, without an account, without tricking the user into clicking anything, and the consequences could be serious on all three fronts (secrecy of data, correctness of data, and the service staying up).
The stated security impacts are:
- Memory corruption via unsafe
strcpy(): memory that belongs to something else gets overwritten. - Stack/heap overflow, described as potential in edge cases.
- Information disclosure, with memory contents possibly leaked: data from one part of the program could end up somewhere it should not.
- Remote code execution through memory corruption: in the worst case, an attacker could make the program run their instructions.
- Denial of service through application crashes: the program could simply fall over.
On exploitability, the report says the issue is remote via the WebSocket handshake, requires no authentication and no user interaction, and has medium complexity because it requires knowledge of the WebSocket protocol. The affected users are described as all users of curl with WebSocket support enabled.
Fix
The report recommends replacing the unsafe copy with a bounded alternative:
// Instead of:
strcpy(keyval, randstr);
// Use:
strncpy(keyval, randstr, sizeof(keyval) - 1);
keyval[sizeof(keyval) - 1] = '\0';
// Or better:
snprintf(keyval, sizeof(keyval), "%s", randstr);
Line by line:
strcpy(keyval, randstr);is the unsafe copy: it keeps going until the end marker, whatever the box size.strncpy(keyval, randstr, sizeof(keyval) - 1);copies at most one byte fewer than the box holds, so it can never spill over.keyval[sizeof(keyval) - 1] = '\0';writes the end marker into the last byte of the box, so the text is properly terminated even if it was cut short.snprintf(keyval, sizeof(keyval), "%s", randstr);is the tidier option: it formats the text into the box and is told the box size, so it stops at the limit and always terminates the result.
The report does not state that a patch was applied or which change was made upstream.
Variants to test
These are follow-up checks in the same spirit, for anyone auditing similar code:
- Look for other
strcpy()calls that copy encoded or attacker-influenced strings into fixed buffers in the same codebase, especially around protocol handshakes. A positive result is a copy whose source length is not provably bounded by the destination size. - Check whether the length check before a copy uses the same size as the destination and runs on every path, including error paths. A positive result is a path where the check is skipped or compares against a different constant.
- Exercise handshake code with values that are not the fixed 16-byte random input, for example where a key or token is supplied or reflected by the peer. A positive result is a value longer than the destination buffer reaching the copy.
- Run the client under a memory sanitiser against a handshake server that returns unusual or oversized header values. A memory sanitiser is a debugging tool that watches every memory access and shouts when a program reads or writes outside its own boxes. A positive result is a sanitiser report pointing at the copy site.
Glossary
- API: a defined way for one program to ask another program to do something, like a menu of allowed requests.
- Base64: an encoding that turns arbitrary bytes into ordinary letters, digits and symbols so they can travel inside text messages.
- Buffer: a fixed-size area of memory reserved to hold data.
- Buffer overflow: writing more data into a buffer than it can hold, so it spills into neighbouring memory.
- Byte: one character-sized unit of memory.
- CWE: a public catalogue that gives each kind of software weakness a number and a name.
- CVSS: a standard 0 to 10 score for how serious a security flaw is, plus a vector string describing the conditions.
- curl: a command-line program and library for transferring data with URLs, used by many scripts and tools.
- Denial of service: making a program or service unavailable, for example by crashing it.
- Function: a named block of code that performs one job.
- Handshake: the short exchange at the start of a connection where both sides agree on how they will talk.
- Header: a labelled line of extra information sent with an internet request or response.
- Heap: the area of memory a program uses for data whose size is decided while it runs.
- Information disclosure: leaking data to someone who should not see it.
- Loopback address: the address
[redacted], meaning "this same computer". - Memory corruption: damage to a program's memory caused by writing where it should not.
- Memory sanitiser: a debugging tool that detects reads and writes outside a program's own memory areas.
- NUL byte: a byte with value zero, used as the end marker for text in C.
- Port: a numbered door on a computer that a program listens on for connections.
- Proof of concept: a working demonstration that a flaw is real.
- Remote code execution: the worst case of memory corruption, where an attacker gets their own instructions run by the program.
- Socket: the program-level object that represents a network connection.
- Stack: the small, fast area of memory used for short-lived values such as local variables.
- strcpy(): a C function that copies text until it finds an end marker, without knowing the destination size.
- WebSocket: a protocol that keeps a two-way connection open so either side can send messages at any time.