curl · Report #3427460
Incorrect sizeof() in Rustls Backend Memory Allocation
How it was found
Summary
There's a bug in lib/vtls/rustls.c where malloc() uses sizeof(cipher_suites) instead of sizeof(*cipher_suites). This allocates memory based on pointer size rather than element size.
Steps To Reproduce
- Look at
lib/vtls/rustls.cline 530:
const struct rustls_supported_ciphersuite **cipher_suites = NULL;
- Then line 589:
cipher_suites = malloc(sizeof(cipher_suites) * (cipher_suites_len));
The problem: sizeof(cipher_suites) returns the size of a pointer (8 bytes on 64-bit), not the size of what it points to.
The Bug
// Line 530 - cipher_suites is a double pointer
const struct rustls_supported_ciphersuite **cipher_suites = NULL;
// Line 589 - Wrong: sizeof(pointer) instead of sizeof(element)
cipher_suites = malloc(sizeof(cipher_suites) * (cipher_suites_len));
Should be:
cipher_suites = malloc(sizeof(*cipher_suites) * cipher_suites_len);
Why This Matters
On 64-bit systems, this happens to work because:
sizeof(cipher_suites)= 8 (pointer size)sizeof(*cipher_suites)= 8 (pointer to pointer size)
But the code is still wrong. It's using the wrong pattern and violates C best practices. If you look at the rest of the curl codebase, you'll see the correct pattern sizeof(*ptr) is used everywhere else.
Proof
I wrote a small test program that shows the issue:
const struct rustls_supported_ciphersuite **cipher_suites = NULL;
// What the code does now (WRONG)
size_t wrong = sizeof(cipher_suites); // = 8 (pointer size)
// What it should do (CORRECT)
size_t correct = sizeof(*cipher_suites); // = 8 (element size)
On 64-bit: both are 8, so bug is masked On 32-bit or if struct changes: could cause underallocation
Impact
- Type: Incorrect buffer size calculation
- Currently works by accident on 64-bit
- Code quality issue that should be fixed
- Violates the pattern used everywhere else in curl