d024f69fe64ac56b562faf6a8b9e9e199d7a4a13
[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 #include <sys/types.h>
25 #ifndef OPENSSL_NO_POSIX_IO
26 # include <sys/stat.h>
27 # include <fcntl.h>
28 #endif
29
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_ISREG)
38 #   define S_ISREG(m) ((m) & S_IFREG)
39 # endif
40
41 #ifdef _WIN32
42 # define stat    _stat
43 # define chmod   _chmod
44 # define open    _open
45 # define fdopen  _fdopen
46 #endif
47
48 #define RAND_FILE_SIZE 1024
49 #define RFILE ".rnd"
50
51 #ifdef OPENSSL_SYS_VMS
52 /*
53  * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
54  * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
55  * stdio functions return this type (a study of stdio.h proves it).
56  *
57  * This declaration is a nasty hack to get around vms' extension to fopen for
58  * passing in sharing options being disabled by /STANDARD=ANSI89
59  */
60 static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
61         (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
62 # define VMS_OPEN_ATTRS \
63         "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
64 # define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
65 #endif
66
67 /*
68  * Note that these functions are intended for seed files only. Entropy
69  * devices and EGD sockets are handled in rand_unix.c  If |bytes| is
70  * -1 read the complete file; otherwise read the specified amount.
71  */
72 int RAND_load_file(const char *file, long bytes)
73 {
74     unsigned char buf[RAND_FILE_SIZE];
75 #ifndef OPENSSL_NO_POSIX_IO
76     struct stat sb;
77 #endif
78     int i, n, ret = 0;
79     FILE *in;
80
81     if (bytes == 0)
82         return 0;
83
84 #ifndef OPENSSL_NO_POSIX_IO
85     if (stat(file, &sb) < 0 || !S_ISREG(sb.st_mode)) {
86         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_NOT_A_REGULAR_FILE);
87         ERR_add_error_data(2, "Filename=", file);
88         return -1;
89     }
90 #endif
91     if ((in = openssl_fopen(file, "rb")) == NULL) {
92         RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE);
93         ERR_add_error_data(2, "Filename=", file);
94         return -1;
95     }
96
97     for ( ; ; ) {
98         if (bytes > 0)
99             n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE;
100         else
101             n = RAND_FILE_SIZE;
102         i = fread(buf, 1, n, in);
103         if (i <= 0)
104             break;
105         RAND_add(buf, i, (double)i);
106         ret += i;
107
108         /* If given a bytecount, and we did it, break. */
109         if (bytes > 0 && (bytes -= i) <= 0)
110             break;
111     }
112
113     OPENSSL_cleanse(buf, sizeof(buf));
114     fclose(in);
115     return ret;
116 }
117
118 int RAND_write_file(const char *file)
119 {
120     unsigned char buf[RAND_FILE_SIZE];
121     int ret = -1;
122     FILE *out = NULL;
123 #ifndef OPENSSL_NO_POSIX_IO
124     struct stat sb;
125
126     if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
127         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE);
128         ERR_add_error_data(2, "Filename=", file);
129         return -1;
130     }
131 #endif
132
133     /* Collect enough random data. */
134     if (RAND_bytes(buf, (int)sizeof(buf)) != 1)
135         return  -1;
136
137 #if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
138     !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
139     {
140 # ifndef O_BINARY
141 #  define O_BINARY 0
142 # endif
143         /*
144          * chmod(..., 0600) is too late to protect the file, permissions
145          * should be restrictive from the start
146          */
147         int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
148         if (fd != -1)
149             out = fdopen(fd, "wb");
150     }
151 #endif
152
153 #ifdef OPENSSL_SYS_VMS
154     /*
155      * VMS NOTE: Prior versions of this routine created a _new_ version of
156      * the rand file for each call into this routine, then deleted all
157      * existing versions named ;-1, and finally renamed the current version
158      * as ';1'. Under concurrent usage, this resulted in an RMS race
159      * condition in rename() which could orphan files (see vms message help
160      * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
161      * the top-level version of the rand file. Note that there may still be
162      * conditions where the top-level rand file is locked. If so, this code
163      * will then create a new version of the rand file. Without the delete
164      * and rename code, this can result in ascending file versions that stop
165      * at version 32767, and this routine will then return an error. The
166      * remedy for this is to recode the calling application to avoid
167      * concurrent use of the rand file, or synchronize usage at the
168      * application level. Also consider whether or not you NEED a persistent
169      * rand file in a concurrent use situation.
170      */
171     out = openssl_fopen(file, "rb+");
172 #endif
173
174     if (out == NULL)
175         out = openssl_fopen(file, "wb");
176     if (out == NULL) {
177         RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_CANNOT_OPEN_FILE);
178         ERR_add_error_data(2, "Filename=", file);
179         return -1;
180     }
181
182 #if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
183     /*
184      * Yes it's late to do this (see above comment), but better than nothing.
185      */
186     chmod(file, 0600);
187 #endif
188
189     ret = fwrite(buf, 1, RAND_FILE_SIZE, out);
190     fclose(out);
191     OPENSSL_cleanse(buf, RAND_FILE_SIZE);
192     return ret;
193 }
194
195 const char *RAND_file_name(char *buf, size_t size)
196 {
197     char *s = NULL;
198     size_t len;
199     int use_randfile = 1;
200
201 #if defined(_WIN32) && defined(CP_UTF8)
202     DWORD envlen;
203     WCHAR *var;
204
205     /* Look up various environment variables. */
206     if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
207         use_randfile = 0;
208         if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
209                 && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
210                                                   NULL, 0)) == 0)
211             envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
212     }
213
214     /* If we got a value, allocate space to hold it and then get it. */
215     if (envlen != 0) {
216         int sz;
217         WCHAR *val = _alloca(envlen * sizeof(WCHAR));
218
219         if (GetEnvironmentVariableW(var, val, envlen) < envlen
220                 && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
221                                              NULL, NULL)) != 0) {
222             s = _alloca(sz);
223             if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
224                                     NULL, NULL) == 0)
225                 s = NULL;
226         }
227     }
228 #else
229     if (OPENSSL_issetugid() != 0) {
230         use_randfile = 0;
231     } else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') {
232         use_randfile = 0;
233         s = getenv("HOME");
234     }
235 #endif
236
237 #ifdef DEFAULT_HOME
238     if (!use_randfile && s == NULL)
239         s = DEFAULT_HOME;
240 #endif
241     if (s == NULL || *s == '\0')
242         return NULL;
243
244     len = strlen(s);
245     if (use_randfile) {
246         if (len + 1 >= size)
247             return NULL;
248         strcpy(buf, s);
249     } else {
250         if (len + 1 + strlen(RFILE) + 1 >= size)
251             return NULL;
252         strcpy(buf, s);
253 #ifndef OPENSSL_SYS_VMS
254         strcat(buf, "/");
255 #endif
256         strcat(buf, RFILE);
257     }
258
259     return buf;
260 }