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