Skip to content

Commit

Permalink
sha2: fix aliasing violation (#24)
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. This is
just as fast with any modern compiler.

Bug: https://gcc.gnu.org/PR114698
Bug: NetBSD/pkgsrc#122
Bug: archiecobbs/libnbcompat#4
Bug: https://bugs.launchpad.net/ubuntu-power-systems/+bug/2033405

Signed-off-by: Sam James <sam@gentoo.org>
  • Loading branch information
thesamesam committed May 2, 2024
1 parent 8f57602 commit 5f076fa
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[1]));
memcpy(&context->buffer[SHA512_SHORT_BLOCK_LENGTH+8], &context->bitcount[0], sizeof(context->bitcount[0]));

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

0 comments on commit 5f076fa

Please sign in to comment.