Fix data loss in unsigned int cast in PK
This patch introduces some additional checks in the PK module for 64-bit
systems only. The problem is that the API functions in the PK
abstraction accept a size_t value for the hashlen, while the RSA module
accepts an unsigned int for the hashlen. Instead of silently casting
size_t to unsigned int, this change checks whether the hashlen overflows
an unsigned int and returns an error.
diff --git a/library/pk_wrap.c b/library/pk_wrap.c
index 6068605..ceaaad1 100644
--- a/library/pk_wrap.c
+++ b/library/pk_wrap.c
@@ -31,6 +31,7 @@
/* Even if RSA not activated, for the sake of RSA-alt */
#include "polarssl/rsa.h"
+#include "polarssl/bignum.h"
#include <string.h>
@@ -50,6 +51,8 @@
#define polarssl_free free
#endif
+#include <limits.h>
+
/* Implementation that should never be optimized out by the compiler */
static void polarssl_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -73,6 +76,11 @@
{
int ret;
+#if defined(POLARSSL_HAVE_INT64)
+ if( md_alg == POLARSSL_MD_NONE && UINT_MAX < hash_len )
+ return( POLARSSL_ERR_PK_BAD_INPUT_DATA );
+#endif /* POLARSSL_HAVE_INT64 */
+
if( sig_len < ((rsa_context *) ctx)->len )
return( POLARSSL_ERR_RSA_VERIFY_FAILED );
@@ -92,6 +100,11 @@
unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
+#if defined(POLARSSL_HAVE_INT64)
+ if( md_alg == POLARSSL_MD_NONE && UINT_MAX < hash_len )
+ return( POLARSSL_ERR_PK_BAD_INPUT_DATA );
+#endif /* POLARSSL_HAVE_INT64 */
+
*sig_len = ((rsa_context *) ctx)->len;
return( rsa_pkcs1_sign( (rsa_context *) ctx, f_rng, p_rng, RSA_PRIVATE,
@@ -411,6 +424,11 @@
{
rsa_alt_context *rsa_alt = (rsa_alt_context *) ctx;
+#if defined(POLARSSL_HAVE_INT64)
+ if( UINT_MAX < hash_len )
+ return( POLARSSL_ERR_PK_BAD_INPUT_DATA );
+#endif /* POLARSSL_HAVE_INT64 */
+
*sig_len = rsa_alt->key_len_func( rsa_alt->key );
return( rsa_alt->sign_func( rsa_alt->key, f_rng, p_rng, RSA_PRIVATE,