rand/randfile.c: restore fallback to $HOME for non-setuid programs.
[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 # if defined(S_ISBLK) && defined(S_ISCHR)
149     if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
150         /*
151          * this file is a device. we don't want read an infinite number of
152          * bytes from a random device, nor do we want to use buffered I/O
153          * because we will waste system entropy.
154          */
155         bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
156         setbuf(in, NULL); /* don't do buffered reads */
157     }
158 # endif
159 #endif
160     for (;;) {
161         if (bytes > 0)
162             n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
163         else
164             n = BUFSIZE;
165         i = fread(buf, 1, n, in);
166         if (i <= 0)
167             break;
168
169         RAND_add(buf, i, (double)i);
170         ret += i;
171         if (bytes > 0) {
172             bytes -= n;
173             if (bytes <= 0)
174                 break;
175         }
176     }
177     OPENSSL_cleanse(buf, BUFSIZE);
178  err:
179     if (in != NULL)
180         fclose(in);
181     return ret;
182 }
183
184 int RAND_write_file(const char *file)
185 {
186     unsigned char buf[BUFSIZE];
187     int i, ret = 0, rand_err = 0;
188     FILE *out = NULL;
189     int n;
190 #ifndef OPENSSL_NO_POSIX_IO
191     struct stat sb;
192
193 # if defined(S_ISBLK) && defined(S_ISCHR)
194 # ifdef _WIN32
195     /*
196      * Check for |file| being a driver as "ASCII-safe" on Windows,
197      * because driver paths are always ASCII.
198      */
199 # endif
200     i = stat(file, &sb);
201     if (i != -1) {
202         if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
203             /*
204              * this file is a device. we don't write back to it. we
205              * "succeed" on the assumption this is some sort of random
206              * device. Otherwise attempting to write to and chmod the device
207              * causes problems.
208              */
209             return 1;
210         }
211 # endif
212     }
213 #endif
214
215 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
216     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
217     {
218 # ifndef O_BINARY
219 #  define O_BINARY 0
220 # endif
221         /*
222          * chmod(..., 0600) is too late to protect the file, permissions
223          * should be restrictive from the start
224          */
225         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
226         if (fd != -1)
227             out = fdopen(fd, "wb");
228     }
229 #endif
230
231 #ifdef OPENSSL_SYS_VMS
232     /*
233      * VMS NOTE: Prior versions of this routine created a _new_ version of
234      * the rand file for each call into this routine, then deleted all
235      * existing versions named ;-1, and finally renamed the current version
236      * as ';1'. Under concurrent usage, this resulted in an RMS race
237      * condition in rename() which could orphan files (see vms message help
238      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
239      * the top-level version of the rand file. Note that there may still be
240      * conditions where the top-level rand file is locked. If so, this code
241      * will then create a new version of the rand file. Without the delete
242      * and rename code, this can result in ascending file versions that stop
243      * at version 32767, and this routine will then return an error. The
244      * remedy for this is to recode the calling application to avoid
245      * concurrent use of the rand file, or synchronize usage at the
246      * application level. Also consider whether or not you NEED a persistent
247      * rand file in a concurrent use situation.
248      */
249
250     out = openssl_fopen(file, "rb+");
251 #endif
252     if (out == NULL)
253         out = openssl_fopen(file, "wb");
254     if (out == NULL)
255         goto err;
256
257 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
258     chmod(file, 0600);
259 #endif
260     n = RAND_DATA;
261     for (;;) {
262         i = (n > BUFSIZE) ? BUFSIZE : n;
263         n -= BUFSIZE;
264         if (RAND_bytes(buf, i) <= 0)
265             rand_err = 1;
266         i = fwrite(buf, 1, i, out);
267         if (i <= 0) {
268             ret = 0;
269             break;
270         }
271         ret += i;
272         if (n <= 0)
273             break;
274     }
275
276     fclose(out);
277     OPENSSL_cleanse(buf, BUFSIZE);
278  err:
279     return (rand_err ? -1 : ret);
280 }
281
282 const char *RAND_file_name(char *buf, size_t size)
283 {
284     char *s = NULL;
285     int use_randfile = 1;
286 #ifdef __OpenBSD__
287     struct stat sb;
288 #endif
289
290 #if defined(_WIN32) && defined(CP_UTF8)
291     DWORD len;
292     WCHAR *var, *val;
293
294     if ((var = L"RANDFILE",
295          len = GetEnvironmentVariableW(var, NULL, 0)) == 0
296         && (var = L"HOME", use_randfile = 0,
297             len = GetEnvironmentVariableW(var, NULL, 0)) == 0
298         && (var = L"USERPROFILE",
299             len = GetEnvironmentVariableW(var, NULL, 0)) == 0) {
300         var = L"SYSTEMROOT",
301         len = GetEnvironmentVariableW(var, NULL, 0);
302     }
303
304     if (len != 0) {
305         int sz;
306
307         val = _alloca(len * sizeof(WCHAR));
308
309         if (GetEnvironmentVariableW(var, val, len) < len
310             && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
311                                          NULL, NULL)) != 0) {
312             s = _alloca(sz);
313             if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
314                                     NULL, NULL) == 0)
315                 s = NULL;
316         }
317     }
318 #else
319     if (OPENSSL_issetugid() != 0) {
320         use_randfile = 0;
321     } else {
322         s = getenv("RANDFILE");
323         if (s == NULL || *s == '\0') {
324             use_randfile = 0;
325             s = getenv("HOME");
326         }
327     }
328 #endif
329 #ifdef DEFAULT_HOME
330     if (!use_randfile && s == NULL) {
331         s = DEFAULT_HOME;
332     }
333 #endif
334     if (s != NULL && *s) {
335         size_t len = strlen(s);
336
337         if (use_randfile && len + 1 < size) {
338             if (OPENSSL_strlcpy(buf, s, size) >= size)
339                 return NULL;
340         } else if (len + strlen(RFILE) + 2 < size) {
341             OPENSSL_strlcpy(buf, s, size);
342 #ifndef OPENSSL_SYS_VMS
343             OPENSSL_strlcat(buf, "/", size);
344 #endif
345             OPENSSL_strlcat(buf, RFILE, size);
346         }
347     } else {
348         buf[0] = '\0';      /* no file name */
349     }
350
351 #ifdef __OpenBSD__
352     /*
353      * given that all random loads just fail if the file can't be seen on a
354      * stat, we stat the file we're returning, if it fails, use /dev/arandom
355      * instead. this allows the user to use their own source for good random
356      * data, but defaults to something hopefully decent if that isn't
357      * available.
358      */
359
360     if (!buf[0])
361         if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) {
362             return NULL;
363         }
364     if (stat(buf, &sb) == -1)
365         if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) {
366             return NULL;
367         }
368 #endif
369     return buf;
370 }