jedisct1 / libsodium

A modern, portable, easy to use crypto library.
https://libsodium.org
Other
12.06k stars 1.72k forks source link

Several calls to `fe25519_abs` trigger `memcpy` undefined behavior #1376

Closed niooss-ledger closed 1 month ago

niooss-ledger commented 1 month ago

Hello,

In current git master, several functions are calling function fe25519_abs with twice the same pointer. For example:

This call as the consequence of calling memcpy with the same pointer too:

So calling fe25519_abs(x, x); triggers a call to memcpy(x, x, ...), which is undefined behavior in C. Indeed, the C99 standard defined in section "7.21.2.1 The memcpy function":

#include <string.h>
void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

Calling memcpy with s1 == s2 violates the assertions ensured by restrict.

To fix this, I believe memmove should be used instead of memcpy in fe25519_copy.

For information, this issue was found by running clang's static analyzer with scan-build -analyze-headers -enable-checker alpha.unix.cstring.BufferOverlap make. It reported:

./include/sodium/private/ed25519_ref10_fe_51.h:194:5: warning: Arguments must not be overlapping buffers [alpha.unix.cstring.BufferOverlap]
    memcpy(h, f, 5 * sizeof h[0]);
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~