From 80bb77e16d0c6295d998a25c7f6b3a81b8727e10 Mon Sep 17 00:00:00 2001 From: Hanno Becker Date: Fri, 19 Jul 2019 14:44:36 +0100 Subject: [PATCH] ECP restart: Don't calculate address of sub ctx if ctx is NULL All modules using restartable ECC operations support passing `NULL` as the restart context as a means to not use the feature. The restart contexts for ECDSA and ECP are nested, and when calling restartable ECP operations from restartable ECDSA operations, the address of the ECP restart context to use is calculated by adding the to the address of the ECDSA restart context the offset the of the ECP restart context. If the ECP restart context happens to not reside at offset `0`, this leads to a non-`NULL` pointer being passed to restartable ECP operations from restartable ECDSA-operations; those ECP operations will hence assume that the pointer points to a valid ECP restart address and likely run into a segmentation fault when trying to dereference the non-NULL but close-to-NULL address. The problem doesn't arise currently because luckily the ECP restart context has offset 0 within the ECDSA restart context, but we should not rely on it. This commit fixes the passage from restartable ECDSA to restartable ECP operations by propagating NULL as the restart context pointer. Apart from being fragile, the previous version could also lead to NULL pointer dereference failures in ASanDbg builds which dereferenced the ECDSA restart context even though it's not needed to calculate the address of the offset'ed ECP restart context. --- library/ecdsa.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/ecdsa.c b/library/ecdsa.c index dc19384d6..74576b387 100644 --- a/library/ecdsa.c +++ b/library/ecdsa.c @@ -172,11 +172,11 @@ static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx ) } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ -#define ECDSA_RS_ECP &rs_ctx->ecp +#define ECDSA_RS_ECP ( rs_ctx == NULL ? NULL : &rs_ctx->ecp ) /* Utility macro for checking and updating ops budget */ #define ECDSA_BUDGET( ops ) \ - MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, &rs_ctx->ecp, ops ) ); + MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, ECDSA_RS_ECP, ops ) ); /* Call this when entering a function that needs its own sub-context */ #define ECDSA_RS_ENTER( SUB ) do { \