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