1 /*
2 * Copyright 1995-2021 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/cryptlib.h"
20
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #include <openssl/crypto.h>
27 #include <openssl/rand.h>
28 #include <openssl/buffer.h>
29
30 #ifdef OPENSSL_SYS_VMS
31 # include <unixio.h>
32 #endif
33 #include <sys/types.h>
34 #ifndef OPENSSL_NO_POSIX_IO
35 # include <sys/stat.h>
36 # include <fcntl.h>
37 # if defined(_WIN32) && !defined(_WIN32_WCE)
38 # include <windows.h>
39 # include <io.h>
40 # define stat _stat
41 # define chmod _chmod
42 # define open _open
43 # define fdopen _fdopen
44 # define fstat _fstat
45 # define fileno _fileno
46 # endif
47 #endif
48
49 /*
50 * Following should not be needed, and we could have been stricter
51 * and demand S_IS*. But some systems just don't comply... Formally
52 * below macros are "anatomically incorrect", because normally they
53 * would look like ((m) & MASK == TYPE), but since MASK availability
54 * is as questionable, we settle for this poor-man fallback...
55 */
56 # if !defined(S_ISREG)
57 # define S_ISREG(m) ((m) & S_IFREG)
58 # endif
59
60 #define RAND_BUF_SIZE 1024
61 #define RFILE ".rnd"
62
63 #ifdef OPENSSL_SYS_VMS
64 /*
65 * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
66 * to make sure the FILE* is a 32-bit pointer no matter what. We know that
67 * stdio functions return this type (a study of stdio.h proves it).
68 *
69 * This declaration is a nasty hack to get around vms' extension to fopen for
70 * passing in sharing options being disabled by /STANDARD=ANSI89
71 */
72 static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
73 (__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
171 OPENSSL_cleanse(buf, sizeof(buf));
172 fclose(in);
173 if (!RAND_status()) {
174 ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
175 return -1;
176 }
177
178 return ret;
179 }
180
RAND_write_file(const char * file)181 int RAND_write_file(const char *file)
182 {
183 unsigned char buf[RAND_BUF_SIZE];
184 int ret = -1;
185 FILE *out = NULL;
186 #ifndef OPENSSL_NO_POSIX_IO
187 struct stat sb;
188
189 if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
190 ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
191 "Filename=%s", file);
192 return -1;
193 }
194 #endif
195
196 /* Collect enough random data. */
197 if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
198 return -1;
199
200 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
201 !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
202 {
203 # ifndef O_BINARY
204 # define O_BINARY 0
205 # endif
206 /*
207 * chmod(..., 0600) is too late to protect the file, permissions
208 * should be restrictive from the start
209 */
210 int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
211 if (fd != -1)
212 out = fdopen(fd, "wb");
213 }
214 #endif
215
216 #ifdef OPENSSL_SYS_VMS
217 /*
218 * VMS NOTE: Prior versions of this routine created a _new_ version of
219 * the rand file for each call into this routine, then deleted all
220 * existing versions named ;-1, and finally renamed the current version
221 * as ';1'. Under concurrent usage, this resulted in an RMS race
222 * condition in rename() which could orphan files (see vms message help
223 * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
224 * the top-level version of the rand file. Note that there may still be
225 * conditions where the top-level rand file is locked. If so, this code
226 * will then create a new version of the rand file. Without the delete
227 * and rename code, this can result in ascending file versions that stop
228 * at version 32767, and this routine will then return an error. The
229 * remedy for this is to recode the calling application to avoid
230 * concurrent use of the rand file, or synchronize usage at the
231 * application level. Also consider whether or not you NEED a persistent
232 * rand file in a concurrent use situation.
233 */
234 out = openssl_fopen(file, "rb+");
235 #endif
236
237 if (out == NULL)
238 out = openssl_fopen(file, "wb");
239 if (out == NULL) {
240 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
241 "Filename=%s", file);
242 return -1;
243 }
244
245 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
246 /*
247 * Yes it's late to do this (see above comment), but better than nothing.
248 */
249 chmod(file, 0600);
250 #endif
251
252 ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
253 fclose(out);
254 OPENSSL_cleanse(buf, RAND_BUF_SIZE);
255 return ret;
256 }
257
RAND_file_name(char * buf,size_t size)258 const char *RAND_file_name(char *buf, size_t size)
259 {
260 char *s = NULL;
261 size_t len;
262 int use_randfile = 1;
263
264 #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
265 DWORD envlen;
266 WCHAR *var;
267
268 /* Look up various environment variables. */
269 if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
270 use_randfile = 0;
271 if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
272 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
273 NULL, 0)) == 0)
274 envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
275 }
276
277 /* If we got a value, allocate space to hold it and then get it. */
278 if (envlen != 0) {
279 int sz;
280 WCHAR *val = _alloca(envlen * sizeof(WCHAR));
281
282 if (GetEnvironmentVariableW(var, val, envlen) < envlen
283 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
284 NULL, NULL)) != 0) {
285 s = _alloca(sz);
286 if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
287 NULL, NULL) == 0)
288 s = NULL;
289 }
290 }
291 #else
292 if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
293 use_randfile = 0;
294 s = ossl_safe_getenv("HOME");
295 }
296 #endif
297
298 #ifdef DEFAULT_HOME
299 if (!use_randfile && s == NULL)
300 s = DEFAULT_HOME;
301 #endif
302 if (s == NULL || *s == '\0')
303 return NULL;
304
305 len = strlen(s);
306 if (use_randfile) {
307 if (len + 1 >= size)
308 return NULL;
309 strcpy(buf, s);
310 } else {
311 if (len + 1 + strlen(RFILE) + 1 >= size)
312 return NULL;
313 strcpy(buf, s);
314 #ifndef OPENSSL_SYS_VMS
315 strcat(buf, "/");
316 #endif
317 strcat(buf, RFILE);
318 }
319
320 return buf;
321 }
322