Copyright consolidation 09/10
[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 "e_os.h"
11
12 /* We need to define this to get macros like S_IFBLK and S_IFCHR */
13 #if !defined(OPENSSL_SYS_VXWORKS)
14 # define _XOPEN_SOURCE 500
15 #endif
16
17 #include <errno.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include <openssl/crypto.h>
23 #include <openssl/rand.h>
24 #include <openssl/buffer.h>
25
26 #ifdef OPENSSL_SYS_VMS
27 # include <unixio.h>
28 #endif
29 #ifndef NO_SYS_TYPES_H
30 # include <sys/types.h>
31 #endif
32 #ifndef OPENSSL_NO_POSIX_IO
33 # include <sys/stat.h>
34 # include <fcntl.h>
35 #endif
36
37 #ifdef _WIN32
38 # define stat    _stat
39 # define chmod   _chmod
40 # define open    _open
41 # define fdopen  _fdopen
42 #endif
43
44 #undef BUFSIZE
45 #define BUFSIZE 1024
46 #define RAND_DATA 1024
47
48 #ifdef OPENSSL_SYS_VMS
49 /*
50  * This declaration is a nasty hack to get around vms' extension to fopen for
51  * passing in sharing options being disabled by our /STANDARD=ANSI89
52  */
53 static FILE *(*const vms_fopen)(const char *, const char *, ...) =
54     (FILE *(*)(const char *, const char *, ...))fopen;
55 # define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
56 #endif
57
58 #define RFILE ".rnd"
59
60 /*
61  * Note that these functions are intended for seed files only. Entropy
62  * devices and EGD sockets are handled in rand_unix.c
63  */
64
65 int RAND_load_file(const char *file, long bytes)
66 {
67     /*-
68      * If bytes >= 0, read up to 'bytes' bytes.
69      * if bytes == -1, read complete file.
70      */
71
72     unsigned char buf[BUFSIZE];
73 #ifndef OPENSSL_NO_POSIX_IO
74     struct stat sb;
75 #endif
76     int i, ret = 0, n;
77     FILE *in;
78
79     if (file == NULL)
80         return (0);
81
82 #ifndef OPENSSL_NO_POSIX_IO
83     /*
84      * struct stat can have padding and unused fields that may not be
85      * initialized in the call to stat(). We need to clear the entire
86      * structure before calling RAND_add() to avoid complaints from
87      * applications such as Valgrind.
88      */
89     memset(&sb, 0, sizeof(sb));
90     if (stat(file, &sb) < 0)
91         return (0);
92     RAND_add(&sb, sizeof(sb), 0.0);
93 #endif
94     if (bytes == 0)
95         return (ret);
96
97 #ifdef OPENSSL_SYS_VMS
98     in = vms_fopen(file, "rb", VMS_OPEN_ATTRS);
99 #else
100     in = fopen(file, "rb");
101 #endif
102     if (in == NULL)
103         goto err;
104 #if defined(S_IFBLK) && defined(S_IFCHR) && !defined(OPENSSL_NO_POSIX_IO)
105     if (sb.st_mode & (S_IFBLK | S_IFCHR)) {
106         /*
107          * this file is a device. we don't want read an infinite number of
108          * bytes from a random device, nor do we want to use buffered I/O
109          * because we will waste system entropy.
110          */
111         bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
112         setbuf(stdin, NULL); /* don't do buffered reads */
113     }
114 #endif
115     for (;;) {
116         if (bytes > 0)
117             n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
118         else
119             n = BUFSIZE;
120         i = fread(buf, 1, n, in);
121         if (i <= 0)
122             break;
123
124         RAND_add(buf, i, (double)i);
125         ret += i;
126         if (bytes > 0) {
127             bytes -= n;
128             if (bytes <= 0)
129                 break;
130         }
131     }
132     fclose(in);
133     OPENSSL_cleanse(buf, BUFSIZE);
134  err:
135     return (ret);
136 }
137
138 int RAND_write_file(const char *file)
139 {
140     unsigned char buf[BUFSIZE];
141     int i, ret = 0, rand_err = 0;
142     FILE *out = NULL;
143     int n;
144 #ifndef OPENSSL_NO_POSIX_IO
145     struct stat sb;
146
147     i = stat(file, &sb);
148     if (i != -1) {
149 # if defined(S_ISBLK) && defined(S_ISCHR)
150         if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
151             /*
152              * this file is a device. we don't write back to it. we
153              * "succeed" on the assumption this is some sort of random
154              * device. Otherwise attempting to write to and chmod the device
155              * causes problems.
156              */
157             return (1);
158         }
159 # endif
160     }
161 #endif
162
163 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_SYS_VMS)
164     {
165 # ifndef O_BINARY
166 #  define O_BINARY 0
167 # endif
168         /*
169          * chmod(..., 0600) is too late to protect the file, permissions
170          * should be restrictive from the start
171          */
172         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
173         if (fd != -1)
174             out = fdopen(fd, "wb");
175     }
176 #endif
177
178 #ifdef OPENSSL_SYS_VMS
179     /*
180      * VMS NOTE: Prior versions of this routine created a _new_ version of
181      * the rand file for each call into this routine, then deleted all
182      * existing versions named ;-1, and finally renamed the current version
183      * as ';1'. Under concurrent usage, this resulted in an RMS race
184      * condition in rename() which could orphan files (see vms message help
185      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
186      * the top-level version of the rand file. Note that there may still be
187      * conditions where the top-level rand file is locked. If so, this code
188      * will then create a new version of the rand file. Without the delete
189      * and rename code, this can result in ascending file versions that stop
190      * at version 32767, and this routine will then return an error. The
191      * remedy for this is to recode the calling application to avoid
192      * concurrent use of the rand file, or synchronize usage at the
193      * application level. Also consider whether or not you NEED a persistent
194      * rand file in a concurrent use situation.
195      */
196
197     out = vms_fopen(file, "rb+", VMS_OPEN_ATTRS);
198     if (out == NULL)
199         out = vms_fopen(file, "wb", VMS_OPEN_ATTRS);
200 #else
201     if (out == NULL)
202         out = fopen(file, "wb");
203 #endif
204     if (out == NULL)
205         goto err;
206
207 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
208     chmod(file, 0600);
209 #endif
210     n = RAND_DATA;
211     for (;;) {
212         i = (n > BUFSIZE) ? BUFSIZE : n;
213         n -= BUFSIZE;
214         if (RAND_bytes(buf, i) <= 0)
215             rand_err = 1;
216         i = fwrite(buf, 1, i, out);
217         if (i <= 0) {
218             ret = 0;
219             break;
220         }
221         ret += i;
222         if (n <= 0)
223             break;
224     }
225
226     fclose(out);
227     OPENSSL_cleanse(buf, BUFSIZE);
228  err:
229     return (rand_err ? -1 : ret);
230 }
231
232 const char *RAND_file_name(char *buf, size_t size)
233 {
234     char *s = NULL;
235 #ifdef __OpenBSD__
236     struct stat sb;
237 #endif
238
239     if (OPENSSL_issetugid() == 0)
240         s = getenv("RANDFILE");
241     if (s != NULL && *s && strlen(s) + 1 < size) {
242         if (OPENSSL_strlcpy(buf, s, size) >= size)
243             return NULL;
244     } else {
245         if (OPENSSL_issetugid() == 0)
246             s = getenv("HOME");
247 #ifdef DEFAULT_HOME
248         if (s == NULL) {
249             s = DEFAULT_HOME;
250         }
251 #endif
252         if (s && *s && strlen(s) + strlen(RFILE) + 2 < size) {
253             OPENSSL_strlcpy(buf, s, size);
254 #ifndef OPENSSL_SYS_VMS
255             OPENSSL_strlcat(buf, "/", size);
256 #endif
257             OPENSSL_strlcat(buf, RFILE, size);
258         } else
259             buf[0] = '\0';      /* no file name */
260     }
261
262 #ifdef __OpenBSD__
263     /*
264      * given that all random loads just fail if the file can't be seen on a
265      * stat, we stat the file we're returning, if it fails, use /dev/arandom
266      * instead. this allows the user to use their own source for good random
267      * data, but defaults to something hopefully decent if that isn't
268      * available.
269      */
270
271     if (!buf[0])
272         if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) {
273             return (NULL);
274         }
275     if (stat(buf, &sb) == -1)
276         if (OPENSSL_strlcpy(buf, "/dev/arandom", size) >= size) {
277             return (NULL);
278         }
279 #endif
280     return (buf);
281 }