From b9ed93fcb8d253213c6d04a4bfb8b6706d3cd61f Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Thu, 17 Aug 2017 17:23:53 +0200 Subject: [PATCH] Change the sodium_pad() API to accept a maximum buffer length Of course, this is not required. Just like `strcat()` can be used safely. But since the cost of this extra check is negligible, better return `-1` than potentially overwrite unrelated memory locations. --- src/libsodium/include/sodium/utils.h | 2 +- src/libsodium/sodium/utils.c | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/libsodium/include/sodium/utils.h b/src/libsodium/include/sodium/utils.h index 86c2e43a..3af24ba8 100644 --- a/src/libsodium/include/sodium/utils.h +++ b/src/libsodium/include/sodium/utils.h @@ -138,7 +138,7 @@ int sodium_mprotect_readwrite(void *ptr); SODIUM_EXPORT int sodium_pad(size_t *padded_buflen_p, unsigned char *buf, - size_t unpadded_buflen, size_t blocksize); + size_t unpadded_buflen, size_t blocksize, size_t max_buflen); SODIUM_EXPORT int sodium_unpad(size_t *unpadded_buflen_p, const unsigned char *buf, diff --git a/src/libsodium/sodium/utils.c b/src/libsodium/sodium/utils.c index 3606f13a..66b1b1c0 100644 --- a/src/libsodium/sodium/utils.c +++ b/src/libsodium/sodium/utils.c @@ -622,7 +622,7 @@ sodium_mprotect_readwrite(void *ptr) int sodium_pad(size_t *padded_buflen_p, unsigned char *buf, - size_t unpadded_buflen, size_t blocksize) + size_t unpadded_buflen, size_t blocksize, size_t max_buflen) { unsigned char *tail; size_t i; @@ -644,6 +644,9 @@ sodium_pad(size_t *padded_buflen_p, unsigned char *buf, sodium_misuse(); } xpadded_len = unpadded_buflen + xpadlen; + if (xpadded_len >= max_buflen) { + return -1; + } tail = &buf[xpadded_len]; *padded_buflen_p = xpadded_len + 1U; mask = 0U;