Add invalid padding_len check in get_pkcs_padding

When trying to decrypt data with an invalid key, we found that `mbedtls`
returned `0x6200` (`-25088`), which means "_CIPHER - Input data contains
invalid padding and is rejected_" from `mbedtls_cipher_finish`, but it also
set the output len as `18446744073709551516`.

In case we detect an error with padding, we leave the output len zero'ed
and return `MBEDTLS_ERR_CIPHER_INVALID_PADDING`. I believe that the current
test cases are sufficient, as they fail if I return the alternative code
`MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA`, so they do already expect a padding
failure, but now we don't change the output len in the error case.

Here's a reference for the way `openssl` checks the padding length:
  - 1848c561ec/crypto/evp/evp_enc.c (L1023)
  - b554eef43b

Signed-off-by: Andre Goddard Rosa <andre.goddard@gmail.com>
Signed-off-by: Andre Goddard Rosa <agoddardrosa@roku.com>
This commit is contained in:
Andre Goddard Rosa 2024-05-01 11:47:12 -05:00
parent 489688c0f7
commit 30666d478b

View File

@ -849,6 +849,9 @@ static int get_pkcs_padding(unsigned char *input, size_t input_len,
}
padding_len = input[input_len - 1];
if (padding_len == 0 || padding_len > (int)input_len) {
return MBEDTLS_ERR_CIPHER_INVALID_PADDING;
}
*data_len = input_len - padding_len;
mbedtls_ct_condition_t bad = mbedtls_ct_uint_gt(padding_len, input_len);