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