mirror of
https://github.com/Mbed-TLS/mbedtls.git
synced 2025-03-25 04:43:32 +00:00
Merge pull request #7342 from gabor-mezei-arm/6679_prevent_mpi_mod_write_from_corrupting_the_input
Prevent mpi_mod_write from corrupting the input
This commit is contained in:
commit
3615be65f8
@ -362,38 +362,46 @@ int mbedtls_mpi_mod_write(const mbedtls_mpi_mod_residue *r,
|
|||||||
size_t buflen,
|
size_t buflen,
|
||||||
mbedtls_mpi_mod_ext_rep ext_rep)
|
mbedtls_mpi_mod_ext_rep ext_rep)
|
||||||
{
|
{
|
||||||
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
|
|
||||||
|
|
||||||
/* Do our best to check if r and m have been set up */
|
/* Do our best to check if r and m have been set up */
|
||||||
if (r->limbs == 0 || N->limbs == 0) {
|
if (r->limbs == 0 || N->limbs == 0) {
|
||||||
goto cleanup;
|
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
|
||||||
}
|
}
|
||||||
if (r->limbs != N->limbs) {
|
if (r->limbs != N->limbs) {
|
||||||
|
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
|
||||||
|
mbedtls_mpi_uint *working_memory = r->p;
|
||||||
|
size_t working_memory_len = sizeof(mbedtls_mpi_uint) * r->limbs;
|
||||||
|
|
||||||
|
if (N->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) {
|
||||||
|
|
||||||
|
working_memory = mbedtls_calloc(r->limbs, sizeof(mbedtls_mpi_uint));
|
||||||
|
|
||||||
|
if (working_memory == NULL) {
|
||||||
|
ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
|
||||||
goto cleanup;
|
goto cleanup;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (N->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) {
|
memcpy(working_memory, r->p, working_memory_len);
|
||||||
ret = mbedtls_mpi_mod_raw_from_mont_rep(r->p, N);
|
|
||||||
|
ret = mbedtls_mpi_mod_raw_from_mont_rep(working_memory, N);
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
goto cleanup;
|
goto cleanup;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ret = mbedtls_mpi_mod_raw_write(r->p, N, buf, buflen, ext_rep);
|
ret = mbedtls_mpi_mod_raw_write(working_memory, N, buf, buflen, ext_rep);
|
||||||
|
|
||||||
if (N->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY) {
|
|
||||||
/* If this fails, the value of r is corrupted and we want to return
|
|
||||||
* this error (as opposed to the error code from the write above) to
|
|
||||||
* let the caller know. If it succeeds, we want to return the error
|
|
||||||
* code from write above. */
|
|
||||||
int conv_ret = mbedtls_mpi_mod_raw_to_mont_rep(r->p, N);
|
|
||||||
if (ret == 0) {
|
|
||||||
ret = conv_ret;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup:
|
cleanup:
|
||||||
|
|
||||||
|
if (N->int_rep == MBEDTLS_MPI_MOD_REP_MONTGOMERY &&
|
||||||
|
working_memory != NULL) {
|
||||||
|
|
||||||
|
mbedtls_platform_zeroize(working_memory, working_memory_len);
|
||||||
|
mbedtls_free(working_memory);
|
||||||
|
}
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user