diff --git a/src/wh_client_crypto.c b/src/wh_client_crypto.c index 89b5a3649..02c031cdc 100644 --- a/src/wh_client_crypto.c +++ b/src/wh_client_crypto.c @@ -2826,14 +2826,30 @@ int wh_Client_Curve25519SharedSecret(whClientContext* ctx, /* wolfCrypt allows positive error codes on success in some * scenarios */ if (ret >= 0) { + uint8_t* res_out = (uint8_t*)(res + 1); + const size_t hdr_sz = + sizeof(whMessageCrypto_GenericResponseHeader) + + sizeof(*res); + /* Defensive bound: res->sz must fit within the actual + * received frame */ + if (res_len < hdr_sz || res->sz > (res_len - hdr_sz)) { + ret = WH_ERROR_ABORTED; + } if (out_size != NULL) { + if ((ret >= 0) && + (out != NULL) && (res->sz > *out_size)) { + /* Output buffer too small. Report required size + * and fail rather than silently truncating + * X25519 key material. */ + ret = WH_ERROR_BUFFER_SIZE; + } + /* Give caller the required size, even on failure */ *out_size = res->sz; - } - if (out != NULL) { - uint8_t* res_out = (uint8_t*)(res + 1); - memcpy(out, res_out, res->sz); - WH_DEBUG_VERBOSE_HEXDUMP("[client] X25519:", res_out, - res->sz); + if ((ret >= 0) && (out != NULL) && (res->sz > 0)) { + memcpy(out, res_out, res->sz); + WH_DEBUG_VERBOSE_HEXDUMP("[client] X25519:", + res_out, res->sz); + } } } }