Skip to content

Commit 3cc504f

Browse files
authored
core: fix uninitialized memory in SHA256 (#1196)
Move `w[16]` buffer outside of the outer loop. Otherwise, `w` goes out of scope in every outer loop iteration and uninitialized memory is used. This bug has become visible by building with GCC 13 in Release. I restored the correct location of `w[16]` as in the original implementation at https://github.com/amosnier/sha-2/blob/5beabbcc0d872e15a16d51539922dbfabb806316/sha-256.c#L40-L53. The code was introduced already with the bug in #113. Fixes #1191.
1 parent e5c3f67 commit 3cc504f

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

silkworm/core/crypto/sha256.c

+15-17
Original file line numberDiff line numberDiff line change
@@ -181,25 +181,23 @@ static inline ALWAYS_INLINE void sha_256_implementation(uint32_t h[8], const voi
181181

182182
const uint8_t* p = chunk;
183183

184+
/*
185+
* The w-array is really w[64], but since we only need 16 of them at a time, we save stack by
186+
* calculating 16 at a time.
187+
*
188+
* This optimization was not there initially and the rest of the comments about w[64] are kept in their
189+
* initial state.
190+
*/
191+
192+
/*
193+
* create a 64-entry message schedule array w[0..63] of 32-bit words (The initial values in w[0..63]
194+
* don't matter, so many implementations zero them here) copy chunk into first 16 words w[0..15] of the
195+
* message schedule array
196+
*/
197+
uint32_t w[16];
198+
184199
/* Compression function main loop: */
185200
for (i = 0; i < 4; i++) {
186-
/*
187-
* The w-array is really w[64], but since we only need
188-
* 16 of them at a time, we save stack by calculating
189-
* 16 at a time.
190-
*
191-
* This optimization was not there initially and the
192-
* rest of the comments about w[64] are kept in their
193-
* initial state.
194-
*/
195-
196-
/*
197-
* create a 64-entry message schedule array w[0..63] of 32-bit words
198-
* (The initial values in w[0..63] don't matter, so many implementations zero them here)
199-
* copy chunk into first 16 words w[0..15] of the message schedule array
200-
*/
201-
uint32_t w[16];
202-
203201
for (j = 0; j < 16; j++) {
204202
if (i == 0) {
205203
w[j] = (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | (uint32_t)p[3];

0 commit comments

Comments
 (0)