xref: /freebsd/crypto/openssl/crypto/rand/randfile.c (revision 88b8b7f0c4e9948667a2279e78e975a784049cba)
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 *, ...) =
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  */
RAND_load_file(const char * file,long bytes)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         /* We can hit a signed integer overflow on the next iteration */
172         if (ret > INT_MAX - RAND_LOAD_BUF_SIZE)
173             break;
174     }
175 
176     OPENSSL_cleanse(buf, sizeof(buf));
177     fclose(in);
178     if (!RAND_status()) {
179         ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
180         return -1;
181     }
182 
183     return ret;
184 }
185 
RAND_write_file(const char * file)186 int RAND_write_file(const char *file)
187 {
188     unsigned char buf[RAND_BUF_SIZE];
189     int ret = -1;
190     FILE *out = NULL;
191 #ifndef OPENSSL_NO_POSIX_IO
192     struct stat sb;
193 
194     if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
195         ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
196                        "Filename=%s", file);
197         return -1;
198     }
199 #endif
200 
201     /* Collect enough random data. */
202     if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
203         return  -1;
204 
205 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
206     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
207     {
208 # ifndef O_BINARY
209 #  define O_BINARY 0
210 # endif
211         /*
212          * chmod(..., 0600) is too late to protect the file, permissions
213          * should be restrictive from the start
214          */
215         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
216 
217         if (fd != -1) {
218             out = fdopen(fd, "wb");
219             if (out == NULL) {
220                 close(fd);
221                 ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
222                                "Filename=%s", file);
223                 return -1;
224             }
225         }
226     }
227 #endif
228 
229 #ifdef OPENSSL_SYS_VMS
230     /*
231      * VMS NOTE: Prior versions of this routine created a _new_ version of
232      * the rand file for each call into this routine, then deleted all
233      * existing versions named ;-1, and finally renamed the current version
234      * as ';1'. Under concurrent usage, this resulted in an RMS race
235      * condition in rename() which could orphan files (see vms message help
236      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
237      * the top-level version of the rand file. Note that there may still be
238      * conditions where the top-level rand file is locked. If so, this code
239      * will then create a new version of the rand file. Without the delete
240      * and rename code, this can result in ascending file versions that stop
241      * at version 32767, and this routine will then return an error. The
242      * remedy for this is to recode the calling application to avoid
243      * concurrent use of the rand file, or synchronize usage at the
244      * application level. Also consider whether or not you NEED a persistent
245      * rand file in a concurrent use situation.
246      */
247     out = openssl_fopen(file, "rb+");
248 #endif
249 
250     if (out == NULL)
251         out = openssl_fopen(file, "wb");
252     if (out == NULL) {
253         ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
254                        "Filename=%s", file);
255         return -1;
256     }
257 
258 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
259     /*
260      * Yes it's late to do this (see above comment), but better than nothing.
261      */
262     chmod(file, 0600);
263 #endif
264 
265     ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
266     fclose(out);
267     OPENSSL_cleanse(buf, RAND_BUF_SIZE);
268     return ret;
269 }
270 
RAND_file_name(char * buf,size_t size)271 const char *RAND_file_name(char *buf, size_t size)
272 {
273     char *s = NULL;
274     size_t len;
275     int use_randfile = 1;
276 
277 #if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
278     DWORD envlen;
279     WCHAR *var;
280 
281     /* Look up various environment variables. */
282     if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
283         use_randfile = 0;
284         if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
285                 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
286                                                   NULL, 0)) == 0)
287             envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
288     }
289 
290     /* If we got a value, allocate space to hold it and then get it. */
291     if (envlen != 0) {
292         int sz;
293         WCHAR *val = _alloca(envlen * sizeof(WCHAR));
294 
295         if (GetEnvironmentVariableW(var, val, envlen) < envlen
296                 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
297                                              NULL, NULL)) != 0) {
298             s = _alloca(sz);
299             if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
300                                     NULL, NULL) == 0)
301                 s = NULL;
302         }
303     }
304 #else
305     if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
306         use_randfile = 0;
307         s = ossl_safe_getenv("HOME");
308     }
309 #endif
310 
311 #ifdef DEFAULT_HOME
312     if (!use_randfile && s == NULL)
313         s = DEFAULT_HOME;
314 #endif
315     if (s == NULL || *s == '\0')
316         return NULL;
317 
318     len = strlen(s);
319     if (use_randfile) {
320         if (len + 1 >= size)
321             return NULL;
322         strcpy(buf, s);
323     } else {
324         if (len + 1 + strlen(RFILE) + 1 >= size)
325             return NULL;
326         strcpy(buf, s);
327 #ifndef OPENSSL_SYS_VMS
328         strcat(buf, "/");
329 #endif
330         strcat(buf, RFILE);
331     }
332 
333     return buf;
334 }
335