Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

selftests/sgx: Fix Q1 and Q2 calculation in sigstruct.c

Q1 and Q2 are numbers with *maximum* length of 384 bytes. If the
calculated length of Q1 and Q2 is less than 384 bytes, things will
go wrong.

E.g. if Q2 is 383 bytes, then

1. The bytes of q2 are copied to sigstruct->q2 in calc_q1q2().
2. The entire sigstruct->q2 is reversed, which results it being
256 * Q2, given that the last byte of sigstruct->q2 is added
to before the bytes given by calc_q1q2().

Either change in key or measurement can trigger the bug. E.g. an
unmeasured heap could cause a devastating change in Q1 or Q2.

Reverse exactly the bytes of Q1 and Q2 in calc_q1q2() before returning
to the caller.

Fixes: 2adcba79e69d ("selftests/x86: Add a selftest for SGX")
Link: https://lore.kernel.org/linux-sgx/20210301051836.30738-1-tianjia.zhang@linux.alibaba.com/
Signed-off-by: Tianjia Zhang <tianjia.zhang@linux.alibaba.com>
Signed-off-by: Jarkko Sakkinen <jarkko@kernel.org>
Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

authored by

Tianjia Zhang and committed by
Shuah Khan
567c3904 2734d6c1

+21 -20
+21 -20
tools/testing/selftests/sgx/sigstruct.c
··· 55 55 return true; 56 56 } 57 57 58 + static void reverse_bytes(void *data, int length) 59 + { 60 + int i = 0; 61 + int j = length - 1; 62 + uint8_t temp; 63 + uint8_t *ptr = data; 64 + 65 + while (i < j) { 66 + temp = ptr[i]; 67 + ptr[i] = ptr[j]; 68 + ptr[j] = temp; 69 + i++; 70 + j--; 71 + } 72 + } 73 + 58 74 static bool calc_q1q2(const uint8_t *s, const uint8_t *m, uint8_t *q1, 59 75 uint8_t *q2) 60 76 { 61 77 struct q1q2_ctx ctx; 78 + int len; 62 79 63 80 if (!alloc_q1q2_ctx(s, m, &ctx)) { 64 81 fprintf(stderr, "Not enough memory for Q1Q2 calculation\n"); ··· 106 89 goto out; 107 90 } 108 91 109 - BN_bn2bin(ctx.q1, q1); 110 - BN_bn2bin(ctx.q2, q2); 92 + len = BN_bn2bin(ctx.q1, q1); 93 + reverse_bytes(q1, len); 94 + len = BN_bn2bin(ctx.q2, q2); 95 + reverse_bytes(q2, len); 111 96 112 97 free_q1q2_ctx(&ctx); 113 98 return true; ··· 169 150 BIO_free(bio); 170 151 171 152 return key; 172 - } 173 - 174 - static void reverse_bytes(void *data, int length) 175 - { 176 - int i = 0; 177 - int j = length - 1; 178 - uint8_t temp; 179 - uint8_t *ptr = data; 180 - 181 - while (i < j) { 182 - temp = ptr[i]; 183 - ptr[i] = ptr[j]; 184 - ptr[j] = temp; 185 - i++; 186 - j--; 187 - } 188 153 } 189 154 190 155 enum mrtags { ··· 370 367 /* BE -> LE */ 371 368 reverse_bytes(sigstruct->signature, SGX_MODULUS_SIZE); 372 369 reverse_bytes(sigstruct->modulus, SGX_MODULUS_SIZE); 373 - reverse_bytes(sigstruct->q1, SGX_MODULUS_SIZE); 374 - reverse_bytes(sigstruct->q2, SGX_MODULUS_SIZE); 375 370 376 371 EVP_MD_CTX_destroy(ctx); 377 372 RSA_free(key);