Skip to content

Commit

Permalink
sha2: fix aliasing violation
Browse files Browse the repository at this point in the history
&context->buffer is uint8_t*, but we try to access it as sha2_word64*, which
is an aliasing violation (undefined behaviour).

Use memcpy instead to avoid being miscompiled by e.g. >= GCC 12.

Bug: https://gcc.gnu.org/PR114698
Bug: NetBSD/pkgsrc#122
Bug: archiecobbs/libnbcompat#4
  • Loading branch information
thesamesam committed Apr 11, 2024
1 parent 8f57602 commit 88cd1f4
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/sha2.c
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ void SHA256_Final(SHA256_CTX* context, sha2_byte digest[]) {
*context->buffer = 0x80;
}
/* Set the bit count: */
*(sha2_word64*)&context->buffer[SHA256_SHORT_BLOCK_LENGTH] = context->bitcount;
memcpy(&context->buffer[SHA256_SHORT_BLOCK_LENGTH], &context->bitcount, sizeof(context->bitcount));

/* Final transform: */
SHA256_Transform(context, (sha2_word32*)context->buffer);
Expand Down Expand Up @@ -921,8 +921,8 @@ void SHA512_Last(SHA512_CTX* context) {
*context->buffer = 0x80;
}
/* Store the length of input data (in bits): */
*(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH] = context->bitcount[1];
*(sha2_word64*)&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8] = context->bitcount[0];
memcpy(&context->buffer[SHA512_SHORT_BLOCK_LENGTH], &context->bitcount[1], sizeof(*context->bitcount));
memcpy(&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8], &context->bitcount[0], sizeof(*context->bitcount));

/* Final transform: */
SHA512_Transform(context, (sha2_word64*)context->buffer);
Expand Down

0 comments on commit 88cd1f4

Please sign in to comment.