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