Add optional parameter validation to the AES module
This adds additional and optional parameter validation to the AES module that
can be used by enabling the MBEDTLS_CHECK_PARAMS config.h option.
diff --git a/include/mbedtls/aes.h b/include/mbedtls/aes.h
index cfb20c4..35c2229 100644
--- a/include/mbedtls/aes.h
+++ b/include/mbedtls/aes.h
@@ -67,6 +67,26 @@
/* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */
+#if defined( MBEDTLS_CHECK_PARAMS )
+#define MBEDTLS_AES_VALIDATE_RET( cond ) do{ if( !(cond) ) { \
+ MBEDTLS_PARAM_FAILED( #cond, \
+ __FILE__, \
+ __LINE__ ); \
+ return MBEDTLS_ERR_AES_BAD_INPUT_DATA;} \
+ } while(0);
+
+#define MBEDTLS_AES_VALIDATE( cond ) do{ if( !(cond) ) { \
+ MBEDTLS_PARAM_FAILED( #cond, \
+ __FILE__, \
+ __LINE__ ); \
+ return; } \
+ } while(0);
+#else
+/* No validation of parameters will be performed */
+#define MBEDTLS_AES_VALIDATE_RET( cond )
+#define MBEDTLS_AES_VALIDATE( cond)
+#endif
+
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
diff --git a/library/aes.c b/library/aes.c
index 3de571e..7a364a0 100644
--- a/library/aes.c
+++ b/library/aes.c
@@ -511,6 +511,8 @@
void mbedtls_aes_init( mbedtls_aes_context *ctx )
{
+ MBEDTLS_AES_VALIDATE( ctx != NULL );
+
memset( ctx, 0, sizeof( mbedtls_aes_context ) );
}
@@ -525,12 +527,16 @@
#if defined(MBEDTLS_CIPHER_MODE_XTS)
void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx )
{
+ MBEDTLS_AES_VALIDATE( ctx != NULL );
+
mbedtls_aes_init( &ctx->crypt );
mbedtls_aes_init( &ctx->tweak );
}
void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx )
{
+ MBEDTLS_AES_VALIDATE( ctx != NULL );
+
mbedtls_aes_free( &ctx->crypt );
mbedtls_aes_free( &ctx->tweak );
}
@@ -546,14 +552,7 @@
unsigned int i;
uint32_t *RK;
-#if !defined(MBEDTLS_AES_ROM_TABLES)
- if( aes_init_done == 0 )
- {
- aes_gen_tables();
- aes_init_done = 1;
-
- }
-#endif
+ MBEDTLS_AES_VALIDATE_RET( ctx != NULL && key != NULL );
switch( keybits )
{
@@ -563,6 +562,15 @@
default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );
}
+#if !defined(MBEDTLS_AES_ROM_TABLES)
+ if( aes_init_done == 0 )
+ {
+ aes_gen_tables();
+ aes_init_done = 1;
+
+ }
+#endif
+
#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)
if( aes_padlock_ace == -1 )
aes_padlock_ace = mbedtls_padlock_has_support( MBEDTLS_PADLOCK_ACE );
@@ -662,6 +670,8 @@
uint32_t *RK;
uint32_t *SK;
+ MBEDTLS_AES_VALIDATE_RET( ctx != NULL && key != NULL );
+
mbedtls_aes_init( &cty );
#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_PADLOCK_ALIGN16)