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