RAND_add(): fix heap corruption in error path
[oweals/openssl.git] / crypto / rand / randfile.c
index 99a3f1424c0162ad11102a4dcece50c414d3f1f6..89720eb5cf6bb16267b1d5b5920ad91faa7512c3 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
  *
  * Licensed under the OpenSSL license (the "License").  You may not use
  * this file except in compliance with the License.  You can obtain a copy
@@ -94,6 +94,7 @@ int RAND_load_file(const char *file, long bytes)
     if (fstat(fileno(in), &sb) < 0) {
         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_INTERNAL_ERROR);
         ERR_add_error_data(2, "Filename=", file);
+        fclose(in);
         return -1;
     }
 
@@ -166,7 +167,7 @@ int RAND_write_file(const char *file)
 #endif
 
     /* Collect enough random data. */
-    if (RAND_bytes(buf, (int)sizeof(buf)) != 1)
+    if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
         return  -1;
 
 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
@@ -261,11 +262,9 @@ const char *RAND_file_name(char *buf, size_t size)
         }
     }
 #else
-    if (OPENSSL_issetugid() != 0) {
+    if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
         use_randfile = 0;
-    } else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') {
-        use_randfile = 0;
-        s = getenv("HOME");
+        s = ossl_safe_getenv("HOME");
     }
 #endif