Undo commit de02ec2
[openssl.git] / crypto / rand / randfile.c
1 /*
2  * Copyright 1995-2016 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 #ifndef NO_SYS_TYPES_H
25 # include <sys/types.h>
26 #endif
27 #ifndef OPENSSL_NO_POSIX_IO
28 # include <sys/stat.h>
29 # include <fcntl.h>
30 /*
31  * Following should not be needed, and we could have been stricter
32  * and demand S_IS*. But some systems just don't comply... Formally
33  * below macros are "anatomically incorrect", because normally they
34  * would look like ((m) & MASK == TYPE), but since MASK availability
35  * is as questionable, we settle for this poor-man fallback...
36  */
37 # if !defined(S_ISBLK)
38 #  if defined(_S_IFBLK)
39 #   define S_ISBLK(m) ((m) & _S_IFBLK)
40 #  elif defined(S_IFBLK)
41 #   define S_ISBLK(m) ((m) & S_IFBLK)
42 #  elif defined(_WIN32)
43 #   define S_ISBLK(m) 0 /* no concept of block devices on Windows */
44 #  endif
45 # endif
46 # if !defined(S_ISCHR)
47 #  if defined(_S_IFCHR)
48 #   define S_ISCHR(m) ((m) & _S_IFCHR)
49 #  elif defined(S_IFCHR)
50 #   define S_ISCHR(m) ((m) & S_IFCHR)
51 #  endif
52 # endif
53 #endif
54
55 #ifdef _WIN32
56 # define stat    _stat
57 # define chmod   _chmod
58 # define open    _open
59 # define fdopen  _fdopen
60 # define fstat   _fstat
61 # define fileno  _fileno
62 #endif
63
64 #undef BUFSIZE
65 #define BUFSIZE 1024
66 #define RAND_DATA 1024
67
68 #ifdef OPENSSL_SYS_VMS
69 /*
70  * Misc hacks needed for specific cases.
71  *
72  * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
73  * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
74  * stdio function return this type (a study of stdio.h proves it).
75  * Additionally, we create a similar char pointer type for the sake of
76  * vms_setbuf below.
77  */
78 # if __INITIAL_POINTER_SIZE == 64
79 #  pragma pointer_size save
80 #  pragma pointer_size 32
81 typedef char *char_ptr32;
82 #  pragma pointer_size restore
83 /*
84  * On VMS, setbuf() will only take 32-bit pointers, and a compilation
85  * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
86  * Since we know that the FILE* really is a 32-bit pointer expanded to
87  * 64 bits, we also know it's safe to convert it back to a 32-bit pointer.
88  * As for the buffer parameter, we only use NULL here, so that passes as
89  * well...
90  */
91 #  define setbuf(fp,buf) (setbuf)((__FILE_ptr32)(fp), (char_ptr32)(buf))
92 # endif
93
94 /*
95  * This declaration is a nasty hack to get around vms' extension to fopen for
96  * passing in sharing options being disabled by /STANDARD=ANSI89
97  */
98 static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
99       (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
100 # define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
101
102 # define openssl_fopen(fname,mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
103 #endif
104
105 #define RFILE ".rnd"
106
107 /*
108  * Note that these functions are intended for seed files only. Entropy
109  * devices and EGD sockets are handled in rand_unix.c
110  */
111
112 int RAND_load_file(const char *file, long bytes)
113 {
114     /*-
115      * If bytes >= 0, read up to 'bytes' bytes.
116      * if bytes == -1, read complete file.
117      */
118
119     unsigned char buf[BUFSIZE];
120 #ifndef OPENSSL_NO_POSIX_IO
121     struct stat sb;
122 #endif
123     int i, ret = 0, n;
124     FILE *in = NULL;
125
126     if (file == NULL)
127         return 0;
128
129     if (bytes == 0)
130         return ret;
131
132     in = openssl_fopen(file, "rb");
133     if (in == NULL)
134         goto err;
135
136 #ifndef OPENSSL_NO_POSIX_IO
137     /*
138      * struct stat can have padding and unused fields that may not be
139      * initialized in the call to stat(). We need to clear the entire
140      * structure before calling RAND_add() to avoid complaints from
141      * applications such as Valgrind.
142      */
143     memset(&sb, 0, sizeof(sb));
144     if (fstat(fileno(in), &sb) < 0)
145         goto err;
146     RAND_add(&sb, sizeof(sb), 0.0);
147
148 #endif
149     for (;;) {
150         if (bytes > 0)
151             n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
152         else
153             n = BUFSIZE;
154         i = fread(buf, 1, n, in);
155         if (i <= 0)
156             break;
157
158         RAND_add(buf, i, (double)i);
159         ret += i;
160         if (bytes > 0) {
161             bytes -= n;
162             if (bytes <= 0)
163                 break;
164         }
165     }
166     OPENSSL_cleanse(buf, BUFSIZE);
167  err:
168     if (in != NULL)
169         fclose(in);
170     return ret;
171 }
172
173 int RAND_write_file(const char *file)
174 {
175     unsigned char buf[BUFSIZE];
176     int i, ret = 0, rand_err = 0;
177     FILE *out = NULL;
178     int n;
179 #ifndef OPENSSL_NO_POSIX_IO
180
181 # if defined(S_ISBLK) && defined(S_ISCHR)
182 # ifdef _WIN32
183     /*
184      * Check for |file| being a driver as "ASCII-safe" on Windows,
185      * because driver paths are always ASCII.
186      */
187 # endif
188 # endif
189 #endif
190
191 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
192     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
193     {
194 # ifndef O_BINARY
195 #  define O_BINARY 0
196 # endif
197         /*
198          * chmod(..., 0600) is too late to protect the file, permissions
199          * should be restrictive from the start
200          */
201         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
202         if (fd != -1)
203             out = fdopen(fd, "wb");
204     }
205 #endif
206
207 #ifdef OPENSSL_SYS_VMS
208     /*
209      * VMS NOTE: Prior versions of this routine created a _new_ version of
210      * the rand file for each call into this routine, then deleted all
211      * existing versions named ;-1, and finally renamed the current version
212      * as ';1'. Under concurrent usage, this resulted in an RMS race
213      * condition in rename() which could orphan files (see vms message help
214      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
215      * the top-level version of the rand file. Note that there may still be
216      * conditions where the top-level rand file is locked. If so, this code
217      * will then create a new version of the rand file. Without the delete
218      * and rename code, this can result in ascending file versions that stop
219      * at version 32767, and this routine will then return an error. The
220      * remedy for this is to recode the calling application to avoid
221      * concurrent use of the rand file, or synchronize usage at the
222      * application level. Also consider whether or not you NEED a persistent
223      * rand file in a concurrent use situation.
224      */
225
226     out = openssl_fopen(file, "rb+");
227 #endif
228     if (out == NULL)
229         out = openssl_fopen(file, "wb");
230     if (out == NULL)
231         goto err;
232
233 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
234     chmod(file, 0600);
235 #endif
236     n = RAND_DATA;
237     for (;;) {
238         i = (n > BUFSIZE) ? BUFSIZE : n;
239         n -= BUFSIZE;
240         if (RAND_bytes(buf, i) <= 0)
241             rand_err = 1;
242         i = fwrite(buf, 1, i, out);
243         if (i <= 0) {
244             ret = 0;
245             break;
246         }
247         ret += i;
248         if (n <= 0)
249             break;
250     }
251
252     fclose(out);
253     OPENSSL_cleanse(buf, BUFSIZE);
254  err:
255     return (rand_err ? -1 : ret);
256 }
257
258 const char *RAND_file_name(char *buf, size_t size)
259 {
260     char *s = NULL;
261     int use_randfile = 1;
262
263 #if defined(_WIN32) && defined(CP_UTF8)
264     DWORD len;
265     WCHAR *var, *val;
266
267     if ((var = L"RANDFILE",
268          len = GetEnvironmentVariableW(var, NULL, 0)) == 0
269         && (var = L"HOME", use_randfile = 0,
270             len = GetEnvironmentVariableW(var, NULL, 0)) == 0
271         && (var = L"USERPROFILE",
272             len = GetEnvironmentVariableW(var, NULL, 0)) == 0) {
273         var = L"SYSTEMROOT",
274         len = GetEnvironmentVariableW(var, NULL, 0);
275     }
276
277     if (len != 0) {
278         int sz;
279
280         val = _alloca(len * sizeof(WCHAR));
281
282         if (GetEnvironmentVariableW(var, val, len) < len
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 (OPENSSL_issetugid() != 0) {
293         use_randfile = 0;
294     } else {
295         s = getenv("RANDFILE");
296         if (s == NULL || *s == '\0') {
297             use_randfile = 0;
298             s = getenv("HOME");
299         }
300     }
301 #endif
302 #ifdef DEFAULT_HOME
303     if (!use_randfile && s == NULL) {
304         s = DEFAULT_HOME;
305     }
306 #endif
307     if (s != NULL && *s) {
308         size_t len = strlen(s);
309
310         if (use_randfile && len + 1 < size) {
311             if (OPENSSL_strlcpy(buf, s, size) >= size)
312                 return NULL;
313         } else if (len + strlen(RFILE) + 2 < size) {
314             OPENSSL_strlcpy(buf, s, size);
315 #ifndef OPENSSL_SYS_VMS
316             OPENSSL_strlcat(buf, "/", size);
317 #endif
318             OPENSSL_strlcat(buf, RFILE, size);
319         }
320     } else {
321         buf[0] = '\0';      /* no file name */
322     }
323
324     return buf[0] ? buf : NULL;
325 }