1 /* 2 * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the Apache License 2.0 (the "License"). You may not use 5 * this file except in compliance with the License. You can obtain a copy 6 * in the file LICENSE in the source distribution or at 7 * https://www.openssl.org/source/license.html 8 */ 9 10 #if defined (__TANDEM) && defined (_SPT_MODEL_) 11 /* 12 * These definitions have to come first in SPT due to scoping of the 13 * declarations in c99 associated with SPT use of stat. 14 */ 15 # include <sys/types.h> 16 # include <sys/stat.h> 17 #endif 18 19 #include "e_os.h" 20 #include "internal/cryptlib.h" 21 22 #include <errno.h> 23 #include <stdio.h> 24 #include <stdlib.h> 25 #include <string.h> 26 27 #include <openssl/crypto.h> 28 #include <openssl/rand.h> 29 #include <openssl/buffer.h> 30 31 #ifdef OPENSSL_SYS_VMS 32 # include <unixio.h> 33 #endif 34 #include <sys/types.h> 35 #ifndef OPENSSL_NO_POSIX_IO 36 # include <sys/stat.h> 37 # include <fcntl.h> 38 # if defined(_WIN32) && !defined(_WIN32_WCE) 39 # include <windows.h> 40 # include <io.h> 41 # define stat _stat 42 # define chmod _chmod 43 # define open _open 44 # define fdopen _fdopen 45 # define fstat _fstat 46 # define fileno _fileno 47 # endif 48 #endif 49 50 /* 51 * Following should not be needed, and we could have been stricter 52 * and demand S_IS*. But some systems just don't comply... Formally 53 * below macros are "anatomically incorrect", because normally they 54 * would look like ((m) & MASK == TYPE), but since MASK availability 55 * is as questionable, we settle for this poor-man fallback... 56 */ 57 # if !defined(S_ISREG) 58 # define S_ISREG(m) ((m) & S_IFREG) 59 # endif 60 61 #define RAND_BUF_SIZE 1024 62 #define RFILE ".rnd" 63 64 #ifdef OPENSSL_SYS_VMS 65 /* 66 * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically) 67 * to make sure the FILE* is a 32-bit pointer no matter what. We know that 68 * stdio functions return this type (a study of stdio.h proves it). 69 * 70 * This declaration is a nasty hack to get around vms' extension to fopen for 71 * passing in sharing options being disabled by /STANDARD=ANSI89 72 */ 73 static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) = 74 (__FILE_ptr32 (*)(const char *, const char *, ...))fopen; 75 # define VMS_OPEN_ATTRS \ 76 "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0" 77 # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS) 78 #endif 79 80 /* 81 * Note that these functions are intended for seed files only. Entropy 82 * devices and EGD sockets are handled in rand_unix.c If |bytes| is 83 * -1 read the complete file; otherwise read the specified amount. 84 */ 85 int RAND_load_file(const char *file, long bytes) 86 { 87 /* 88 * The load buffer size exceeds the chunk size by the comfortable amount 89 * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose 90 * to avoid calling RAND_add() with a small final chunk. Instead, such 91 * a small final chunk will be added together with the previous chunk 92 * (unless it's the only one). 93 */ 94 #define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH) 95 unsigned char buf[RAND_LOAD_BUF_SIZE]; 96 97 #ifndef OPENSSL_NO_POSIX_IO 98 struct stat sb; 99 #endif 100 int i, n, ret = 0; 101 FILE *in; 102 103 if (bytes == 0) 104 return 0; 105 106 if ((in = openssl_fopen(file, "rb")) == NULL) { 107 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, 108 "Filename=%s", file); 109 return -1; 110 } 111 112 #ifndef OPENSSL_NO_POSIX_IO 113 if (fstat(fileno(in), &sb) < 0) { 114 ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR, 115 "Filename=%s", file); 116 fclose(in); 117 return -1; 118 } 119 120 if (bytes < 0) { 121 if (S_ISREG(sb.st_mode)) 122 bytes = sb.st_size; 123 else 124 bytes = RAND_DRBG_STRENGTH; 125 } 126 #endif 127 /* 128 * On VMS, setbuf() will only take 32-bit pointers, and a compilation 129 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here. 130 * However, we trust that the C RTL will never give us a FILE pointer 131 * above the first 4 GB of memory, so we simply turn off the warning 132 * temporarily. 133 */ 134 #if defined(OPENSSL_SYS_VMS) && defined(__DECC) 135 # pragma environment save 136 # pragma message disable maylosedata2 137 #endif 138 /* 139 * Don't buffer, because even if |file| is regular file, we have 140 * no control over the buffer, so why would we want a copy of its 141 * contents lying around? 142 */ 143 setbuf(in, NULL); 144 #if defined(OPENSSL_SYS_VMS) && defined(__DECC) 145 # pragma environment restore 146 #endif 147 148 for ( ; ; ) { 149 if (bytes > 0) 150 n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE; 151 else 152 n = RAND_LOAD_BUF_SIZE; 153 i = fread(buf, 1, n, in); 154 #ifdef EINTR 155 if (ferror(in) && errno == EINTR){ 156 clearerr(in); 157 if (i == 0) 158 continue; 159 } 160 #endif 161 if (i == 0) 162 break; 163 164 RAND_add(buf, i, (double)i); 165 ret += i; 166 167 /* If given a bytecount, and we did it, break. */ 168 if (bytes > 0 && (bytes -= i) <= 0) 169 break; 170 } 171 172 OPENSSL_cleanse(buf, sizeof(buf)); 173 fclose(in); 174 if (!RAND_status()) { 175 ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file); 176 return -1; 177 } 178 179 return ret; 180 } 181 182 int RAND_write_file(const char *file) 183 { 184 unsigned char buf[RAND_BUF_SIZE]; 185 int ret = -1; 186 FILE *out = NULL; 187 #ifndef OPENSSL_NO_POSIX_IO 188 struct stat sb; 189 190 if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) { 191 ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE, 192 "Filename=%s", file); 193 return -1; 194 } 195 #endif 196 197 /* Collect enough random data. */ 198 if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1) 199 return -1; 200 201 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \ 202 !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS) 203 { 204 # ifndef O_BINARY 205 # define O_BINARY 0 206 # endif 207 /* 208 * chmod(..., 0600) is too late to protect the file, permissions 209 * should be restrictive from the start 210 */ 211 int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600); 212 213 if (fd != -1) { 214 out = fdopen(fd, "wb"); 215 if (out == NULL) { 216 close(fd); 217 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, 218 "Filename=%s", file); 219 return -1; 220 } 221 } 222 } 223 #endif 224 225 #ifdef OPENSSL_SYS_VMS 226 /* 227 * VMS NOTE: Prior versions of this routine created a _new_ version of 228 * the rand file for each call into this routine, then deleted all 229 * existing versions named ;-1, and finally renamed the current version 230 * as ';1'. Under concurrent usage, this resulted in an RMS race 231 * condition in rename() which could orphan files (see vms message help 232 * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares 233 * the top-level version of the rand file. Note that there may still be 234 * conditions where the top-level rand file is locked. If so, this code 235 * will then create a new version of the rand file. Without the delete 236 * and rename code, this can result in ascending file versions that stop 237 * at version 32767, and this routine will then return an error. The 238 * remedy for this is to recode the calling application to avoid 239 * concurrent use of the rand file, or synchronize usage at the 240 * application level. Also consider whether or not you NEED a persistent 241 * rand file in a concurrent use situation. 242 */ 243 out = openssl_fopen(file, "rb+"); 244 #endif 245 246 if (out == NULL) 247 out = openssl_fopen(file, "wb"); 248 if (out == NULL) { 249 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE, 250 "Filename=%s", file); 251 return -1; 252 } 253 254 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO) 255 /* 256 * Yes it's late to do this (see above comment), but better than nothing. 257 */ 258 chmod(file, 0600); 259 #endif 260 261 ret = fwrite(buf, 1, RAND_BUF_SIZE, out); 262 fclose(out); 263 OPENSSL_cleanse(buf, RAND_BUF_SIZE); 264 return ret; 265 } 266 267 const char *RAND_file_name(char *buf, size_t size) 268 { 269 char *s = NULL; 270 size_t len; 271 int use_randfile = 1; 272 273 #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE) 274 DWORD envlen; 275 WCHAR *var; 276 277 /* Look up various environment variables. */ 278 if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) { 279 use_randfile = 0; 280 if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0 281 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE", 282 NULL, 0)) == 0) 283 envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0); 284 } 285 286 /* If we got a value, allocate space to hold it and then get it. */ 287 if (envlen != 0) { 288 int sz; 289 WCHAR *val = _alloca(envlen * sizeof(WCHAR)); 290 291 if (GetEnvironmentVariableW(var, val, envlen) < envlen 292 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0, 293 NULL, NULL)) != 0) { 294 s = _alloca(sz); 295 if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz, 296 NULL, NULL) == 0) 297 s = NULL; 298 } 299 } 300 #else 301 if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') { 302 use_randfile = 0; 303 s = ossl_safe_getenv("HOME"); 304 } 305 #endif 306 307 #ifdef DEFAULT_HOME 308 if (!use_randfile && s == NULL) 309 s = DEFAULT_HOME; 310 #endif 311 if (s == NULL || *s == '\0') 312 return NULL; 313 314 len = strlen(s); 315 if (use_randfile) { 316 if (len + 1 >= size) 317 return NULL; 318 strcpy(buf, s); 319 } else { 320 if (len + 1 + strlen(RFILE) + 1 >= size) 321 return NULL; 322 strcpy(buf, s); 323 #ifndef OPENSSL_SYS_VMS 324 strcat(buf, "/"); 325 #endif 326 strcat(buf, RFILE); 327 } 328 329 return buf; 330 } 331