diff --git a/doc/dox_comments/header_files/sha256.h b/doc/dox_comments/header_files/sha256.h index 8a896ff795f..b88b0269a21 100644 --- a/doc/dox_comments/header_files/sha256.h +++ b/doc/dox_comments/header_files/sha256.h @@ -402,12 +402,16 @@ int wc_Sha256_Grow(wc_Sha256* sha256, const byte* in, int inSz); \ingroup SHA \brief Copies SHA256 context. + The memory regions occupied by the source and destination structures + must not overlap. If they overlap, including when src == dst, the + behavior is undefined. + \return 0 on success \return negative on error \param src Source SHA256 structure \param dst Destination SHA256 structure; - (must be zeroed or previously initialized) + (must be zeroed or previously initialized and must not overlap src) _Example_ \code @@ -613,12 +617,16 @@ int wc_Sha224GetHash(wc_Sha224* sha224, byte* hash); \ingroup SHA \brief Copies SHA224 context. + The memory regions occupied by the source and destination structures + must not overlap. If they overlap, including when src == dst, the + behavior is undefined. + \return 0 on success \return negative on error \param src Source SHA224 structure \param dst Destination SHA224 structure - (must be zeroed or previously initialized) + (must be zeroed or previously initialized and must not overlap src) _Example_ \code diff --git a/wolfcrypt/src/sha256.c b/wolfcrypt/src/sha256.c index 12e95b6aef8..3f3aded4fee 100644 --- a/wolfcrypt/src/sha256.c +++ b/wolfcrypt/src/sha256.c @@ -3425,11 +3425,22 @@ int wc_Sha224Reset(wc_Sha224* sha224) { int wc_Sha224Copy(wc_Sha224* src, wc_Sha224* dst) { int ret = 0; /* assume success unless proven otherwise */ + wc_ptr_t srcAddr; + wc_ptr_t dstAddr; if (src == NULL || dst == NULL) { return BAD_FUNC_ARG; } + /* Reject if src and dst had overlapping */ + srcAddr = (wc_ptr_t)src; + dstAddr = (wc_ptr_t)dst; + + if ((srcAddr <= dstAddr && dstAddr - srcAddr < sizeof(*src)) || + (dstAddr < srcAddr && srcAddr - dstAddr < sizeof(*dst))) { + return BAD_FUNC_ARG; + } + #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_COPY) #ifndef WOLF_CRYPTO_CB_FIND if (src->devId != INVALID_DEVID) @@ -3574,11 +3585,22 @@ int wc_Sha256GetHash(wc_Sha256* sha256, byte* hash) int wc_Sha256Copy(wc_Sha256* src, wc_Sha256* dst) { int ret = 0; + wc_ptr_t srcAddr; + wc_ptr_t dstAddr; if (src == NULL || dst == NULL) { return BAD_FUNC_ARG; } + /* Reject if src and dst had overlapping */ + srcAddr = (wc_ptr_t)src; + dstAddr = (wc_ptr_t)dst; + + if ((srcAddr <= dstAddr && dstAddr - srcAddr < sizeof(*src)) || + (dstAddr < srcAddr && srcAddr - dstAddr < sizeof(*dst))) { + return BAD_FUNC_ARG; + } + #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_COPY) #ifndef WOLF_CRYPTO_CB_FIND if (src->devId != INVALID_DEVID)