Adapt CRYPTO_secure_malloc() like CRYPTO_malloc()
authorRichard Levitte <levitte@openssl.org>
Thu, 29 Sep 2022 11:56:43 +0000 (13:56 +0200)
committerRichard Levitte <levitte@openssl.org>
Wed, 5 Oct 2022 12:02:02 +0000 (14:02 +0200)
In other words, make it raise ERR_R_MALLOC_FAILURE appropriately.

Reviewed-by: Tomas Mraz <tomas@openssl.org>
Reviewed-by: Hugo Landau <hlandau@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/19301)

crypto/mem_sec.c

index 60559a930ed4b8e7bae598478c7a8347868443f5..8d2c161c707c210510510385e52cad6797b87ef1 100644 (file)
@@ -17,6 +17,7 @@
  */
 #include "internal/e_os.h"
 #include <openssl/crypto.h>
+#include <openssl/err.h>
 
 #include <string.h>
 
@@ -140,18 +141,27 @@ int CRYPTO_secure_malloc_initialized(void)
 void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
 {
 #ifndef OPENSSL_NO_SECURE_MEMORY
-    void *ret;
+    void *ret = NULL;
     size_t actual_size;
+    int reason = CRYPTO_R_SECURE_MALLOC_FAILURE;
 
     if (!secure_mem_initialized) {
         return CRYPTO_malloc(num, file, line);
     }
-    if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
-        return NULL;
+    if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) {
+        reason = ERR_R_CRYPTO_LIB;
+        goto err;
+    }
     ret = sh_malloc(num);
     actual_size = ret ? sh_actual_size(ret) : 0;
     secure_mem_used += actual_size;
     CRYPTO_THREAD_unlock(sec_malloc_lock);
+ err:
+    if (ret == NULL && (file != NULL || line != 0)) {
+        ERR_new();
+        ERR_set_debug(file, line, NULL);
+        ERR_set_error(ERR_LIB_CRYPTO, reason, NULL);
+    }
     return ret;
 #else
     return CRYPTO_malloc(num, file, line);