1 /*
2 * Copyright 1995-2025 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 "internal/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 *, ...) = (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
74 #define VMS_OPEN_ATTRS \
75 "shr=get,put,upd,del", "ctx=bin,stm", "rfm=stm", "rat=none", "mrs=0"
76 #define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
77 #endif
78
79 /*
80 * Note that these functions are intended for seed files only. Entropy
81 * devices and EGD sockets are handled in rand_unix.c If |bytes| is
82 * -1 read the complete file; otherwise read the specified amount.
83 */
RAND_load_file(const char * file,long bytes)84 int RAND_load_file(const char *file, long bytes)
85 {
86 /*
87 * The load buffer size exceeds the chunk size by the comfortable amount
88 * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose
89 * to avoid calling RAND_add() with a small final chunk. Instead, such
90 * a small final chunk will be added together with the previous chunk
91 * (unless it's the only one).
92 */
93 #define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH)
94 unsigned char buf[RAND_LOAD_BUF_SIZE];
95
96 #ifndef OPENSSL_NO_POSIX_IO
97 struct stat sb;
98 #endif
99 int i, n, ret = 0;
100 FILE *in;
101
102 if (bytes == 0)
103 return 0;
104
105 if ((in = openssl_fopen(file, "rb")) == NULL) {
106 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
107 "Filename=%s", file);
108 return -1;
109 }
110
111 #ifndef OPENSSL_NO_POSIX_IO
112 if (fstat(fileno(in), &sb) < 0) {
113 ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR,
114 "Filename=%s", file);
115 fclose(in);
116 return -1;
117 }
118
119 if (bytes < 0) {
120 if (S_ISREG(sb.st_mode))
121 bytes = sb.st_size;
122 else
123 bytes = RAND_DRBG_STRENGTH;
124 }
125 #endif
126 /*
127 * On VMS, setbuf() will only take 32-bit pointers, and a compilation
128 * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
129 * However, we trust that the C RTL will never give us a FILE pointer
130 * above the first 4 GB of memory, so we simply turn off the warning
131 * temporarily.
132 */
133 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
134 #pragma environment save
135 #pragma message disable maylosedata2
136 #endif
137 /*
138 * Don't buffer, because even if |file| is regular file, we have
139 * no control over the buffer, so why would we want a copy of its
140 * contents lying around?
141 */
142 setbuf(in, NULL);
143 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
144 #pragma environment restore
145 #endif
146
147 for (;;) {
148 if (bytes > 0)
149 n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE;
150 else
151 n = RAND_LOAD_BUF_SIZE;
152 i = fread(buf, 1, n, in);
153 #ifdef EINTR
154 if (ferror(in) && errno == EINTR) {
155 clearerr(in);
156 if (i == 0)
157 continue;
158 }
159 #endif
160 if (i == 0)
161 break;
162
163 RAND_add(buf, i, (double)i);
164 ret += i;
165
166 /* If given a bytecount, and we did it, break. */
167 if (bytes > 0 && (bytes -= i) <= 0)
168 break;
169
170 /* We can hit a signed integer overflow on the next iteration */
171 if (ret > INT_MAX - RAND_LOAD_BUF_SIZE)
172 break;
173 }
174
175 OPENSSL_cleanse(buf, sizeof(buf));
176 fclose(in);
177 if (!RAND_status()) {
178 ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
179 return -1;
180 }
181
182 return ret;
183 }
184
RAND_write_file(const char * file)185 int RAND_write_file(const char *file)
186 {
187 unsigned char buf[RAND_BUF_SIZE];
188 int ret = -1;
189 FILE *out = NULL;
190 #ifndef OPENSSL_NO_POSIX_IO
191 struct stat sb;
192
193 if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
194 ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
195 "Filename=%s", file);
196 return -1;
197 }
198 #endif
199
200 /* Collect enough random data. */
201 if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
202 return -1;
203
204 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
205 {
206 #ifndef O_BINARY
207 #define O_BINARY 0
208 #endif
209 /*
210 * chmod(..., 0600) is too late to protect the file, permissions
211 * should be restrictive from the start
212 */
213 int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
214
215 if (fd != -1) {
216 out = fdopen(fd, "wb");
217 if (out == NULL) {
218 close(fd);
219 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
220 "Filename=%s", file);
221 return -1;
222 }
223 }
224 }
225 #endif
226
227 #ifdef OPENSSL_SYS_VMS
228 /*
229 * VMS NOTE: Prior versions of this routine created a _new_ version of
230 * the rand file for each call into this routine, then deleted all
231 * existing versions named ;-1, and finally renamed the current version
232 * as ';1'. Under concurrent usage, this resulted in an RMS race
233 * condition in rename() which could orphan files (see vms message help
234 * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
235 * the top-level version of the rand file. Note that there may still be
236 * conditions where the top-level rand file is locked. If so, this code
237 * will then create a new version of the rand file. Without the delete
238 * and rename code, this can result in ascending file versions that stop
239 * at version 32767, and this routine will then return an error. The
240 * remedy for this is to recode the calling application to avoid
241 * concurrent use of the rand file, or synchronize usage at the
242 * application level. Also consider whether or not you NEED a persistent
243 * rand file in a concurrent use situation.
244 */
245 out = openssl_fopen(file, "rb+");
246 #endif
247
248 if (out == NULL)
249 out = openssl_fopen(file, "wb");
250 if (out == NULL) {
251 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
252 "Filename=%s", file);
253 return -1;
254 }
255
256 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
257 /*
258 * Yes it's late to do this (see above comment), but better than nothing.
259 */
260 chmod(file, 0600);
261 #endif
262
263 ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
264 fclose(out);
265 OPENSSL_cleanse(buf, RAND_BUF_SIZE);
266 return ret;
267 }
268
RAND_file_name(char * buf,size_t size)269 const char *RAND_file_name(char *buf, size_t size)
270 {
271 char *s = NULL;
272 size_t len;
273 int use_randfile = 1;
274
275 #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
276 DWORD envlen;
277 WCHAR *var;
278
279 /* Look up various environment variables. */
280 if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
281 use_randfile = 0;
282 if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
283 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
284 NULL, 0))
285 == 0)
286 envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
287 }
288
289 /* If we got a value, allocate space to hold it and then get it. */
290 if (envlen != 0) {
291 int sz;
292 WCHAR *val = _alloca(envlen * sizeof(WCHAR));
293
294 if (GetEnvironmentVariableW(var, val, envlen) < envlen
295 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
296 NULL, NULL))
297 != 0) {
298 s = _alloca(sz);
299 if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
300 NULL, NULL)
301 == 0)
302 s = NULL;
303 }
304 }
305 #else
306 if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
307 use_randfile = 0;
308 s = ossl_safe_getenv("HOME");
309 }
310 #endif
311
312 #ifdef DEFAULT_HOME
313 if (!use_randfile && s == NULL)
314 s = DEFAULT_HOME;
315 #endif
316 if (s == NULL || *s == '\0')
317 return NULL;
318
319 len = strlen(s);
320 if (use_randfile) {
321 if (len + 1 >= size)
322 return NULL;
323 strcpy(buf, s);
324 } else {
325 if (len + 1 + strlen(RFILE) + 1 >= size)
326 return NULL;
327 strcpy(buf, s);
328 #ifndef OPENSSL_SYS_VMS
329 strcat(buf, "/");
330 #endif
331 strcat(buf, RFILE);
332 }
333
334 return buf;
335 }
336