89720eb5cf6bb16267b1d5b5920ad91faa7512c3
[openssl.git] / crypto / rand / randfile.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 # ifdef _WIN32
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_FILE_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     unsigned char buf[RAND_FILE_SIZE];
78 #ifndef OPENSSL_NO_POSIX_IO
79     struct stat sb;
80 #endif
81     int i, n, ret = 0;
82     FILE *in;
83
84     if (bytes == 0)
85         return 0;
86
87     if ((in = openssl_fopen(file, "rb")) == NULL) {
88         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE);
89         ERR_add_error_data(2, "Filename=", file);
90         return -1;
91     }
92
93 #ifndef OPENSSL_NO_POSIX_IO
94     if (fstat(fileno(in), &sb) < 0) {
95         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_INTERNAL_ERROR);
96         ERR_add_error_data(2, "Filename=", file);
97         fclose(in);
98         return -1;
99     }
100
101     if (!S_ISREG(sb.st_mode) && bytes < 0)
102         bytes = 256;
103 #endif
104     /*
105      * On VMS, setbuf() will only take 32-bit pointers, and a compilation
106      * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
107      * However, we trust that the C RTL will never give us a FILE pointer
108      * above the first 4 GB of memory, so we simply turn off the warning
109      * temporarily.
110      */
111 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
112 # pragma environment save
113 # pragma message disable maylosedata2
114 #endif
115     /*
116      * Don't buffer, because even if |file| is regular file, we have
117      * no control over the buffer, so why would we want a copy of its
118      * contents lying around?
119      */
120     setbuf(in, NULL);
121 #if defined(OPENSSL_SYS_VMS) && defined(__DECC)
122 # pragma environment restore
123 #endif
124
125     for ( ; ; ) {
126         if (bytes > 0)
127             n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE;
128         else
129             n = RAND_FILE_SIZE;
130         i = fread(buf, 1, n, in);
131 #ifdef EINTR
132         if (ferror(in) && errno == EINTR){
133             clearerr(in);
134             if (i == 0)
135                 continue;
136         }
137 #endif
138         if (i == 0)
139             break;
140
141         RAND_add(buf, i, (double)i);
142         ret += i;
143
144         /* If given a bytecount, and we did it, break. */
145         if (bytes > 0 && (bytes -= i) <= 0)
146             break;
147     }
148
149     OPENSSL_cleanse(buf, sizeof(buf));
150     fclose(in);
151     return ret;
152 }
153
154 int RAND_write_file(const char *file)
155 {
156     unsigned char buf[RAND_FILE_SIZE];
157     int ret = -1;
158     FILE *out = NULL;
159 #ifndef OPENSSL_NO_POSIX_IO
160     struct stat sb;
161
162     if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
163         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE);
164         ERR_add_error_data(2, "Filename=", file);
165         return -1;
166     }
167 #endif
168
169     /* Collect enough random data. */
170     if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
171         return  -1;
172
173 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
174     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
175     {
176 # ifndef O_BINARY
177 #  define O_BINARY 0
178 # endif
179         /*
180          * chmod(..., 0600) is too late to protect the file, permissions
181          * should be restrictive from the start
182          */
183         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
184         if (fd != -1)
185             out = fdopen(fd, "wb");
186     }
187 #endif
188
189 #ifdef OPENSSL_SYS_VMS
190     /*
191      * VMS NOTE: Prior versions of this routine created a _new_ version of
192      * the rand file for each call into this routine, then deleted all
193      * existing versions named ;-1, and finally renamed the current version
194      * as ';1'. Under concurrent usage, this resulted in an RMS race
195      * condition in rename() which could orphan files (see vms message help
196      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
197      * the top-level version of the rand file. Note that there may still be
198      * conditions where the top-level rand file is locked. If so, this code
199      * will then create a new version of the rand file. Without the delete
200      * and rename code, this can result in ascending file versions that stop
201      * at version 32767, and this routine will then return an error. The
202      * remedy for this is to recode the calling application to avoid
203      * concurrent use of the rand file, or synchronize usage at the
204      * application level. Also consider whether or not you NEED a persistent
205      * rand file in a concurrent use situation.
206      */
207     out = openssl_fopen(file, "rb+");
208 #endif
209
210     if (out == NULL)
211         out = openssl_fopen(file, "wb");
212     if (out == NULL) {
213         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_CANNOT_OPEN_FILE);
214         ERR_add_error_data(2, "Filename=", file);
215         return -1;
216     }
217
218 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
219     /*
220      * Yes it's late to do this (see above comment), but better than nothing.
221      */
222     chmod(file, 0600);
223 #endif
224
225     ret = fwrite(buf, 1, RAND_FILE_SIZE, out);
226     fclose(out);
227     OPENSSL_cleanse(buf, RAND_FILE_SIZE);
228     return ret;
229 }
230
231 const char *RAND_file_name(char *buf, size_t size)
232 {
233     char *s = NULL;
234     size_t len;
235     int use_randfile = 1;
236
237 #if defined(_WIN32) && defined(CP_UTF8)
238     DWORD envlen;
239     WCHAR *var;
240
241     /* Look up various environment variables. */
242     if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
243         use_randfile = 0;
244         if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
245                 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
246                                                   NULL, 0)) == 0)
247             envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
248     }
249
250     /* If we got a value, allocate space to hold it and then get it. */
251     if (envlen != 0) {
252         int sz;
253         WCHAR *val = _alloca(envlen * sizeof(WCHAR));
254
255         if (GetEnvironmentVariableW(var, val, envlen) < envlen
256                 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
257                                              NULL, NULL)) != 0) {
258             s = _alloca(sz);
259             if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
260                                     NULL, NULL) == 0)
261                 s = NULL;
262         }
263     }
264 #else
265     if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
266         use_randfile = 0;
267         s = ossl_safe_getenv("HOME");
268     }
269 #endif
270
271 #ifdef DEFAULT_HOME
272     if (!use_randfile && s == NULL)
273         s = DEFAULT_HOME;
274 #endif
275     if (s == NULL || *s == '\0')
276         return NULL;
277
278     len = strlen(s);
279     if (use_randfile) {
280         if (len + 1 >= size)
281             return NULL;
282         strcpy(buf, s);
283     } else {
284         if (len + 1 + strlen(RFILE) + 1 >= size)
285             return NULL;
286         strcpy(buf, s);
287 #ifndef OPENSSL_SYS_VMS
288         strcat(buf, "/");
289 #endif
290         strcat(buf, RFILE);
291     }
292
293     return buf;
294 }