0074-Constant-time-grub_crypto_memcmp.patch 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. From 4bbd6ae38efc7c0ae9ffd343157b7f3f37bd729c Mon Sep 17 00:00:00 2001
  2. From: Gary Lin <glin@suse.com>
  3. Date: Fri, 25 Jul 2025 13:50:23 +0800
  4. Subject: [PATCH] Constant-time grub_crypto_memcmp()
  5. Use the constant-time algorithm to compare the given memory blocks.
  6. The code is extracted from the upstream commit:
  7. 0739d24cd1648531d0708d1079ff6bbfa6140268
  8. Fix: bsc#1234959
  9. Signed-off-by: Gary Lin <glin@suse.com>
  10. Upstream: not submitted upstream, as upstream has switched to gcrypt
  11. Taken-from: https://build.opensuse.org/projects/SUSE:SLE-15-SP5:Update/packages/grub2.39923/files/grub2-constant-time-grub_crypto_memcmp.patch?expand=0
  12. Fixes: https://www.cve.org/CVERecord?id=CVE-2024-56738
  13. Signed-off-by: Thomas Petazzoni <thomas.petazzoni@bootlin.com>
  14. ---
  15. grub-core/lib/crypto.c | 23 ++++++++++++++++-------
  16. 1 file changed, 16 insertions(+), 7 deletions(-)
  17. diff --git a/grub-core/lib/crypto.c b/grub-core/lib/crypto.c
  18. index 396f76410..19db7870a 100644
  19. --- a/grub-core/lib/crypto.c
  20. +++ b/grub-core/lib/crypto.c
  21. @@ -433,19 +433,28 @@ grub_crypto_gcry_error (gcry_err_code_t in)
  22. return GRUB_ACCESS_DENIED;
  23. }
  24. +/*
  25. + * Compare byte arrays of length LEN, return 1 if it's not same,
  26. + * 0, otherwise.
  27. + */
  28. int
  29. -grub_crypto_memcmp (const void *a, const void *b, grub_size_t n)
  30. +grub_crypto_memcmp (const void *b1, const void *b2, grub_size_t len)
  31. {
  32. - register grub_size_t counter = 0;
  33. - const grub_uint8_t *pa, *pb;
  34. + const grub_uint8_t *a = b1;
  35. + const grub_uint8_t *b = b2;
  36. + int ab, ba;
  37. + grub_size_t i;
  38. - for (pa = a, pb = b; n; pa++, pb++, n--)
  39. + /* Constant-time compare. */
  40. + for (i = 0, ab = 0, ba = 0; i < len; i++)
  41. {
  42. - if (*pa != *pb)
  43. - counter++;
  44. + /* If a[i] != b[i], either ab or ba will be negative. */
  45. + ab |= a[i] - b[i];
  46. + ba |= b[i] - a[i];
  47. }
  48. - return !!counter;
  49. + /* 'ab | ba' is negative when buffers are not equal, extract sign bit. */
  50. + return ((unsigned int)(ab | ba) >> (sizeof(unsigned int) * 8 - 1)) & 1;
  51. }
  52. #ifndef GRUB_UTIL
  53. --
  54. 2.50.1