[BN] harden `BN_copy()` against leaks from memory accesses
authorNicola Tuveri <nic.tuv@gmail.com>
Tue, 21 Jan 2020 15:08:16 +0000 (17:08 +0200)
committerNicola Tuveri <nic.tuv@gmail.com>
Fri, 24 Apr 2020 14:44:10 +0000 (17:44 +0300)
commit3655e35b78df095b367b3334b6515f6d9436fd95
treea458f36969908679c19061951055c3074c0c8c34
parent6a01f6f4b41d045e2a3abcb10163633d769db76a
[BN] harden `BN_copy()` against leaks from memory accesses

`BN_copy()` (and indirectly `BN_dup()`) do not propagate the
`BN_FLG_CONSTTIME` flag: the propagation has been turned on and off a
few times in the past years, because in some conditions it has shown
unintended consequences in some code paths.

Without turning the propagation on once more, we can still improve
`BN_copy()` by avoiding to leak `src->top` in case `src` is flagged with
`BN_FLG_CONSTTIME`.
In this case we can instead use `src->dmax` as the number of words
allocated for `dst` and for the `memcpy` operation.

Barring compiler or runtime optimizations, if the caller provides `src`
flagged as const time and preallocated to a public size, no leak should
happen due to the copy operation.

(cherry picked from commit 2d9167ed0b588dacbdd0303fb6041ffe1d8b3a92)

Reviewed-by: Matt Caswell <matt@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/11127)
crypto/bn/bn_lib.c