Coverage Report

Created: 2025-04-22 06:18

/src/openssl/crypto/rand/randfile.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (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
#if defined (__TANDEM) && defined (_SPT_MODEL_)
11
/*
12
 * These definitions have to come first in SPT due to scoping of the
13
 * declarations in c99 associated with SPT use of stat.
14
 */
15
# include <sys/types.h>
16
# include <sys/stat.h>
17
#endif
18
19
#include "e_os.h"
20
#include "internal/cryptlib.h"
21
22
#include <errno.h>
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
27
#include <openssl/crypto.h>
28
#include <openssl/rand.h>
29
#include <openssl/buffer.h>
30
31
#ifdef OPENSSL_SYS_VMS
32
# include <unixio.h>
33
#endif
34
#include <sys/types.h>
35
#ifndef OPENSSL_NO_POSIX_IO
36
# include <sys/stat.h>
37
# include <fcntl.h>
38
# if defined(_WIN32) && !defined(_WIN32_WCE)
39
#  include <windows.h>
40
#  include <io.h>
41
#  define stat    _stat
42
#  define chmod   _chmod
43
#  define open    _open
44
#  define fdopen  _fdopen
45
#  define fstat   _fstat
46
#  define fileno  _fileno
47
# endif
48
#endif
49
50
/*
51
 * Following should not be needed, and we could have been stricter
52
 * and demand S_IS*. But some systems just don't comply... Formally
53
 * below macros are "anatomically incorrect", because normally they
54
 * would look like ((m) & MASK == TYPE), but since MASK availability
55
 * is as questionable, we settle for this poor-man fallback...
56
 */
57
# if !defined(S_ISREG)
58
#   define S_ISREG(m) ((m) & S_IFREG)
59
# endif
60
61
0
#define RAND_BUF_SIZE 1024
62
0
#define RFILE ".rnd"
63
64
#ifdef OPENSSL_SYS_VMS
65
/*
66
 * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
67
 * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
68
 * stdio functions return this type (a study of stdio.h proves it).
69
 *
70
 * This declaration is a nasty hack to get around vms' extension to fopen for
71
 * passing in sharing options being disabled by /STANDARD=ANSI89
72
 */
73
static __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
74
        (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
75
# define VMS_OPEN_ATTRS \
76
        "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
77
# define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
78
#endif
79
80
/*
81
 * Note that these functions are intended for seed files only. Entropy
82
 * devices and EGD sockets are handled in rand_unix.c  If |bytes| is
83
 * -1 read the complete file; otherwise read the specified amount.
84
 */
85
int RAND_load_file(const char *file, long bytes)
86
0
{
87
    /*
88
     * The load buffer size exceeds the chunk size by the comfortable amount
89
     * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose
90
     * to avoid calling RAND_add() with a small final chunk. Instead, such
91
     * a small final chunk will be added together with the previous chunk
92
     * (unless it's the only one).
93
     */
94
0
#define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH)
95
0
    unsigned char buf[RAND_LOAD_BUF_SIZE];
96
97
0
#ifndef OPENSSL_NO_POSIX_IO
98
0
    struct stat sb;
99
0
#endif
100
0
    int i, n, ret = 0;
101
0
    FILE *in;
102
103
0
    if (bytes == 0)
104
0
        return 0;
105
106
0
    if ((in = openssl_fopen(file, "rb")) == NULL) {
107
0
        ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
108
0
                       "Filename=%s", file);
109
0
        return -1;
110
0
    }
111
112
0
#ifndef OPENSSL_NO_POSIX_IO
113
0
    if (fstat(fileno(in), &sb) < 0) {
114
0
        ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR,
115
0
                       "Filename=%s", file);
116
0
        fclose(in);
117
0
        return -1;
118
0
    }
119
120
0
    if (bytes < 0) {
121
0
        if (S_ISREG(sb.st_mode))
122
0
            bytes = sb.st_size;
123
0
        else
124
0
            bytes = RAND_DRBG_STRENGTH;
125
0
    }
126
0
#endif
127
    /*
128
     * On VMS, setbuf() will only take 32-bit pointers, and a compilation
129
     * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
130
     * However, we trust that the C RTL will never give us a FILE pointer
131
     * above the first 4 GB of memory, so we simply turn off the warning
132
     * temporarily.
133
     */
134
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
135
# pragma environment save
136
# pragma message disable maylosedata2
137
#endif
138
    /*
139
     * Don't buffer, because even if |file| is regular file, we have
140
     * no control over the buffer, so why would we want a copy of its
141
     * contents lying around?
142
     */
143
0
    setbuf(in, NULL);
144
#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
145
# pragma environment restore
146
#endif
147
148
0
    for ( ; ; ) {
149
0
        if (bytes > 0)
150
0
            n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE;
151
0
        else
152
0
            n = RAND_LOAD_BUF_SIZE;
153
0
        i = fread(buf, 1, n, in);
154
0
#ifdef EINTR
155
0
        if (ferror(in) && errno == EINTR){
156
0
            clearerr(in);
157
0
            if (i == 0)
158
0
                continue;
159
0
        }
160
0
#endif
161
0
        if (i == 0)
162
0
            break;
163
164
0
        RAND_add(buf, i, (double)i);
165
0
        ret += i;
166
167
        /* If given a bytecount, and we did it, break. */
168
0
        if (bytes > 0 && (bytes -= i) <= 0)
169
0
            break;
170
0
    }
171
172
0
    OPENSSL_cleanse(buf, sizeof(buf));
173
0
    fclose(in);
174
0
    if (!RAND_status()) {
175
0
        ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
176
0
        return -1;
177
0
    }
178
179
0
    return ret;
180
0
}
181
182
int RAND_write_file(const char *file)
183
0
{
184
0
    unsigned char buf[RAND_BUF_SIZE];
185
0
    int ret = -1;
186
0
    FILE *out = NULL;
187
0
#ifndef OPENSSL_NO_POSIX_IO
188
0
    struct stat sb;
189
190
0
    if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
191
0
        ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
192
0
                       "Filename=%s", file);
193
0
        return -1;
194
0
    }
195
0
#endif
196
197
    /* Collect enough random data. */
198
0
    if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
199
0
        return  -1;
200
201
0
#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
202
0
    !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
203
0
    {
204
0
# ifndef O_BINARY
205
0
#  define O_BINARY 0
206
0
# endif
207
        /*
208
         * chmod(..., 0600) is too late to protect the file, permissions
209
         * should be restrictive from the start
210
         */
211
0
        int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
212
213
0
        if (fd != -1) {
214
0
            out = fdopen(fd, "wb");
215
0
            if (out == NULL) {
216
0
                close(fd);
217
0
                ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
218
0
                               "Filename=%s", file);
219
0
                return -1;
220
0
            }
221
0
        }
222
0
    }
223
0
#endif
224
225
#ifdef OPENSSL_SYS_VMS
226
    /*
227
     * VMS NOTE: Prior versions of this routine created a _new_ version of
228
     * the rand file for each call into this routine, then deleted all
229
     * existing versions named ;-1, and finally renamed the current version
230
     * as ';1'. Under concurrent usage, this resulted in an RMS race
231
     * condition in rename() which could orphan files (see vms message help
232
     * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
233
     * the top-level version of the rand file. Note that there may still be
234
     * conditions where the top-level rand file is locked. If so, this code
235
     * will then create a new version of the rand file. Without the delete
236
     * and rename code, this can result in ascending file versions that stop
237
     * at version 32767, and this routine will then return an error. The
238
     * remedy for this is to recode the calling application to avoid
239
     * concurrent use of the rand file, or synchronize usage at the
240
     * application level. Also consider whether or not you NEED a persistent
241
     * rand file in a concurrent use situation.
242
     */
243
    out = openssl_fopen(file, "rb+");
244
#endif
245
246
0
    if (out == NULL)
247
0
        out = openssl_fopen(file, "wb");
248
0
    if (out == NULL) {
249
0
        ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
250
0
                       "Filename=%s", file);
251
0
        return -1;
252
0
    }
253
254
0
#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
255
    /*
256
     * Yes it's late to do this (see above comment), but better than nothing.
257
     */
258
0
    chmod(file, 0600);
259
0
#endif
260
261
0
    ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
262
0
    fclose(out);
263
0
    OPENSSL_cleanse(buf, RAND_BUF_SIZE);
264
0
    return ret;
265
0
}
266
267
const char *RAND_file_name(char *buf, size_t size)
268
0
{
269
0
    char *s = NULL;
270
0
    size_t len;
271
0
    int use_randfile = 1;
272
273
#if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
274
    DWORD envlen;
275
    WCHAR *var;
276
277
    /* Look up various environment variables. */
278
    if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
279
        use_randfile = 0;
280
        if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
281
                && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
282
                                                  NULL, 0)) == 0)
283
            envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
284
    }
285
286
    /* If we got a value, allocate space to hold it and then get it. */
287
    if (envlen != 0) {
288
        int sz;
289
        WCHAR *val = _alloca(envlen * sizeof(WCHAR));
290
291
        if (GetEnvironmentVariableW(var, val, envlen) < envlen
292
                && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
293
                                             NULL, NULL)) != 0) {
294
            s = _alloca(sz);
295
            if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
296
                                    NULL, NULL) == 0)
297
                s = NULL;
298
        }
299
    }
300
#else
301
0
    if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
302
0
        use_randfile = 0;
303
0
        s = ossl_safe_getenv("HOME");
304
0
    }
305
0
#endif
306
307
#ifdef DEFAULT_HOME
308
    if (!use_randfile && s == NULL)
309
        s = DEFAULT_HOME;
310
#endif
311
0
    if (s == NULL || *s == '\0')
312
0
        return NULL;
313
314
0
    len = strlen(s);
315
0
    if (use_randfile) {
316
0
        if (len + 1 >= size)
317
0
            return NULL;
318
0
        strcpy(buf, s);
319
0
    } else {
320
0
        if (len + 1 + strlen(RFILE) + 1 >= size)
321
0
            return NULL;
322
0
        strcpy(buf, s);
323
0
#ifndef OPENSSL_SYS_VMS
324
0
        strcat(buf, "/");
325
0
#endif
326
0
        strcat(buf, RFILE);
327
0
    }
328
329
0
    return buf;
330
0
}