Only implement secure malloc if _POSIX_VERSION allows
[openssl.git] / crypto / mem_sec.c
index 11e95c42b891b2c63e971d934d6d44ddebed0cdd..87c19a1395497283f07f27adc8cdd9e3fc0c391b 100644 (file)
  * For details on that implementation, see below (look for uppercase
  * "SECURE HEAP IMPLEMENTATION").
  */
+#include "e_os.h"
 #include <openssl/crypto.h>
-#include <e_os.h>
 
 #include <string.h>
 
-#if defined(OPENSSL_SYS_LINUX) || defined(OPENSSL_SYS_UNIX)
+/* e_os.h includes unistd.h, which defines _POSIX_VERSION */
+#if defined(OPENSSL_SYS_UNIX) \
+    && defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L
 # define IMPLEMENTED
 # include <stdlib.h>
 # include <assert.h>
@@ -66,7 +68,7 @@ int CRYPTO_secure_malloc_init(size_t size, int minsize)
     int ret = 0;
 
     if (!secure_mem_initialized) {
-        sec_malloc_lock = CRYPTO_THREAD_lock_new();
+        sec_malloc_lock = CRYPTO_THREAD_glock_new("sec_malloc");
         if (sec_malloc_lock == NULL)
             return 0;
         if ((ret = sh_init(size, minsize)) != 0) {
@@ -157,6 +159,33 @@ void CRYPTO_secure_free(void *ptr, const char *file, int line)
 #endif /* IMPLEMENTED */
 }
 
+void CRYPTO_secure_clear_free(void *ptr, size_t num,
+                              const char *file, int line)
+{
+#ifdef IMPLEMENTED
+    size_t actual_size;
+
+    if (ptr == NULL)
+        return;
+    if (!CRYPTO_secure_allocated(ptr)) {
+        OPENSSL_cleanse(ptr, num);
+        CRYPTO_free(ptr, file, line);
+        return;
+    }
+    CRYPTO_THREAD_write_lock(sec_malloc_lock);
+    actual_size = sh_actual_size(ptr);
+    CLEAR(ptr, actual_size);
+    secure_mem_used -= actual_size;
+    sh_free(ptr);
+    CRYPTO_THREAD_unlock(sec_malloc_lock);
+#else
+    if (ptr == NULL)
+        return;
+    OPENSSL_cleanse(ptr, num);
+    CRYPTO_free(ptr, file, line);
+#endif /* IMPLEMENTED */
+}
+
 int CRYPTO_secure_allocated(const void *ptr)
 {
 #ifdef IMPLEMENTED
@@ -347,7 +376,7 @@ static int sh_init(size_t size, int minsize)
     size_t pgsize;
     size_t aligned;
 
-    memset(&sh, 0, sizeof sh);
+    memset(&sh, 0, sizeof(sh));
 
     /* make sure size and minsize are powers of 2 */
     OPENSSL_assert(size > 0);
@@ -374,7 +403,7 @@ static int sh_init(size_t size, int minsize)
     for (i = sh.bittable_size; i; i >>= 1)
         sh.freelist_size++;
 
-    sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof (char *));
+    sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
     OPENSSL_assert(sh.freelist != NULL);
     if (sh.freelist == NULL)
         goto err;
@@ -471,7 +500,7 @@ static void sh_done()
     OPENSSL_free(sh.bitmalloc);
     if (sh.map_result != NULL && sh.map_size)
         munmap(sh.map_result, sh.map_size);
-    memset(&sh, 0, sizeof sh);
+    memset(&sh, 0, sizeof(sh));
 }
 
 static int sh_allocated(const char *ptr)