1132166Snjl/*
2140469Simp * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3131767Simp *
4131767Simp * Licensed under the Apache License 2.0 (the "License").  You may not use
5131767Simp * this file except in compliance with the License.  You can obtain a copy
6131767Simp * in the file LICENSE in the source distribution or at
7131767Simp * https://www.openssl.org/source/license.html
8131767Simp */
9140040Simp
10131767Simp#if defined (__TANDEM) && defined (_SPT_MODEL_)
11140040Simp/*
12140040Simp * These definitions have to come first in SPT due to scoping of the
13131767Simp * declarations in c99 associated with SPT use of stat.
14131767Simp */
15131767Simp# include <sys/types.h>
16131767Simp# include <sys/stat.h>
17140040Simp#endif
18140040Simp
19131767Simp#include "internal/cryptlib.h"
20131767Simp
21131767Simp#include <errno.h>
22131767Simp#include <stdio.h>
23131767Simp#include <stdlib.h>
24131767Simp#include <string.h>
25131767Simp
26131767Simp#include <openssl/crypto.h>
27131767Simp#include <openssl/rand.h>
28131767Simp#include <openssl/buffer.h>
29131767Simp
30131767Simp#ifdef OPENSSL_SYS_VMS
31131767Simp# include <unixio.h>
32131767Simp#endif
33131767Simp#include <sys/types.h>
34134081Sphk#ifndef OPENSSL_NO_POSIX_IO
35131767Simp# include <sys/stat.h>
36134081Sphk# include <fcntl.h>
37131767Simp# if defined(_WIN32) && !defined(_WIN32_WCE)
38131767Simp#  include <windows.h>
39132137Simp#  include <io.h>
40131767Simp#  define stat    _stat
41131767Simp#  define chmod   _chmod
42132137Simp#  define open    _open
43132137Simp#  define fdopen  _fdopen
44131767Simp#  define fstat   _fstat
45131767Simp#  define fileno  _fileno
46132137Simp# endif
47131767Simp#endif
48132137Simp
49147580Simp/*
50132137Simp * Following should not be needed, and we could have been stricter
51132137Simp * and demand S_IS*. But some systems just don't comply... Formally
52131767Simp * below macros are "anatomically incorrect", because normally they
53132137Simp * would look like ((m) & MASK == TYPE), but since MASK availability
54132137Simp * is as questionable, we settle for this poor-man fallback...
55140469Simp */
56140469Simp# if !defined(S_ISREG)
57140469Simp#   define S_ISREG(m) ((m) & S_IFREG)
58140469Simp# endif
59140469Simp
60140469Simp#define RAND_BUF_SIZE 1024
61140469Simp#define RFILE ".rnd"
62132137Simp
63132137Simp#ifdef OPENSSL_SYS_VMS
64132137Simp/*
65140469Simp * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
66140469Simp * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
67140469Simp * stdio functions return this type (a study of stdio.h proves it).
68140469Simp *
69140469Simp * This declaration is a nasty hack to get around vms' extension to fopen for
70140469Simp * passing in sharing options being disabled by /STANDARD=ANSI89
71140469Simp */
72132137Simpstatic __FILE_ptr32 (*const vms_fopen)(const char *, const char *, ...) =
73132137Simp        (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
74132137Simp# define VMS_OPEN_ATTRS \
75132137Simp        "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
76132137Simp# define openssl_fopen(fname, mode) vms_fopen((fname), (mode), VMS_OPEN_ATTRS)
77132137Simp#endif
78132137Simp
79132137Simp/*
80132137Simp * Note that these functions are intended for seed files only. Entropy
81132137Simp * devices and EGD sockets are handled in rand_unix.c  If |bytes| is
82132137Simp * -1 read the complete file; otherwise read the specified amount.
83132137Simp */
84131767Simpint RAND_load_file(const char *file, long bytes)
85131767Simp{
86185235Simp    /*
87185235Simp     * The load buffer size exceeds the chunk size by the comfortable amount
88135212Simp     * of 'RAND_DRBG_STRENGTH' bytes (not bits!). This is done on purpose
89132137Simp     * to avoid calling RAND_add() with a small final chunk. Instead, such
90132137Simp     * a small final chunk will be added together with the previous chunk
91132137Simp     * (unless it's the only one).
92132137Simp     */
93132137Simp#define RAND_LOAD_BUF_SIZE (RAND_BUF_SIZE + RAND_DRBG_STRENGTH)
94132137Simp    unsigned char buf[RAND_LOAD_BUF_SIZE];
95132137Simp
96132137Simp#ifndef OPENSSL_NO_POSIX_IO
97132216Snjl    struct stat sb;
98131767Simp#endif
99135212Simp    int i, n, ret = 0;
100131767Simp    FILE *in;
101131767Simp
102140469Simp    if (bytes == 0)
103131767Simp        return 0;
104132216Snjl
105134081Sphk    if ((in = openssl_fopen(file, "rb")) == NULL) {
106134081Sphk        ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
107135212Simp                       "Filename=%s", file);
108135212Simp        return -1;
109135212Simp    }
110135212Simp
111135212Simp#ifndef OPENSSL_NO_POSIX_IO
112132216Snjl    if (fstat(fileno(in), &sb) < 0) {
113132216Snjl        ERR_raise_data(ERR_LIB_RAND, RAND_R_INTERNAL_ERROR,
114132216Snjl                       "Filename=%s", file);
115131767Simp        fclose(in);
116131767Simp        return -1;
117131767Simp    }
118131767Simp
119131767Simp    if (bytes < 0) {
120132137Simp        if (S_ISREG(sb.st_mode))
121131767Simp            bytes = sb.st_size;
122131767Simp        else
123131767Simp            bytes = RAND_DRBG_STRENGTH;
124131767Simp    }
125131767Simp#endif
126131767Simp    /*
127131767Simp     * On VMS, setbuf() will only take 32-bit pointers, and a compilation
128131767Simp     * with /POINTER_SIZE=64 will give off a MAYLOSEDATA2 warning here.
129132048Snjl     * However, we trust that the C RTL will never give us a FILE pointer
130131767Simp     * above the first 4 GB of memory, so we simply turn off the warning
131131767Simp     * temporarily.
132131767Simp     */
133131767Simp#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
134131767Simp# pragma environment save
135131767Simp# pragma message disable maylosedata2
136131767Simp#endif
137131767Simp    /*
138131767Simp     * Don't buffer, because even if |file| is regular file, we have
139131767Simp     * no control over the buffer, so why would we want a copy of its
140131767Simp     * contents lying around?
141131767Simp     */
142    setbuf(in, NULL);
143#if defined(OPENSSL_SYS_VMS) && defined(__DECC)
144# pragma environment restore
145#endif
146
147    for ( ; ; ) {
148        if (bytes > 0)
149            n = (bytes <= RAND_LOAD_BUF_SIZE) ? (int)bytes : RAND_BUF_SIZE;
150        else
151            n = RAND_LOAD_BUF_SIZE;
152        i = fread(buf, 1, n, in);
153#ifdef EINTR
154        if (ferror(in) && errno == EINTR){
155            clearerr(in);
156            if (i == 0)
157                continue;
158        }
159#endif
160        if (i == 0)
161            break;
162
163        RAND_add(buf, i, (double)i);
164        ret += i;
165
166        /* If given a bytecount, and we did it, break. */
167        if (bytes > 0 && (bytes -= i) <= 0)
168            break;
169    }
170
171    OPENSSL_cleanse(buf, sizeof(buf));
172    fclose(in);
173    if (!RAND_status()) {
174        ERR_raise_data(ERR_LIB_RAND, RAND_R_RESEED_ERROR, "Filename=%s", file);
175        return -1;
176    }
177
178    return ret;
179}
180
181int RAND_write_file(const char *file)
182{
183    unsigned char buf[RAND_BUF_SIZE];
184    int ret = -1;
185    FILE *out = NULL;
186#ifndef OPENSSL_NO_POSIX_IO
187    struct stat sb;
188
189    if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
190        ERR_raise_data(ERR_LIB_RAND, RAND_R_NOT_A_REGULAR_FILE,
191                       "Filename=%s", file);
192        return -1;
193    }
194#endif
195
196    /* Collect enough random data. */
197    if (RAND_priv_bytes(buf, (int)sizeof(buf)) != 1)
198        return  -1;
199
200#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
201    !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
202    {
203# ifndef O_BINARY
204#  define O_BINARY 0
205# endif
206        /*
207         * chmod(..., 0600) is too late to protect the file, permissions
208         * should be restrictive from the start
209         */
210        int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
211        if (fd != -1)
212            out = fdopen(fd, "wb");
213    }
214#endif
215
216#ifdef OPENSSL_SYS_VMS
217    /*
218     * VMS NOTE: Prior versions of this routine created a _new_ version of
219     * the rand file for each call into this routine, then deleted all
220     * existing versions named ;-1, and finally renamed the current version
221     * as ';1'. Under concurrent usage, this resulted in an RMS race
222     * condition in rename() which could orphan files (see vms message help
223     * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
224     * the top-level version of the rand file. Note that there may still be
225     * conditions where the top-level rand file is locked. If so, this code
226     * will then create a new version of the rand file. Without the delete
227     * and rename code, this can result in ascending file versions that stop
228     * at version 32767, and this routine will then return an error. The
229     * remedy for this is to recode the calling application to avoid
230     * concurrent use of the rand file, or synchronize usage at the
231     * application level. Also consider whether or not you NEED a persistent
232     * rand file in a concurrent use situation.
233     */
234    out = openssl_fopen(file, "rb+");
235#endif
236
237    if (out == NULL)
238        out = openssl_fopen(file, "wb");
239    if (out == NULL) {
240        ERR_raise_data(ERR_LIB_RAND, RAND_R_CANNOT_OPEN_FILE,
241                       "Filename=%s", file);
242        return -1;
243    }
244
245#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
246    /*
247     * Yes it's late to do this (see above comment), but better than nothing.
248     */
249    chmod(file, 0600);
250#endif
251
252    ret = fwrite(buf, 1, RAND_BUF_SIZE, out);
253    fclose(out);
254    OPENSSL_cleanse(buf, RAND_BUF_SIZE);
255    return ret;
256}
257
258const char *RAND_file_name(char *buf, size_t size)
259{
260    char *s = NULL;
261    size_t len;
262    int use_randfile = 1;
263
264#if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
265    DWORD envlen;
266    WCHAR *var;
267
268    /* Look up various environment variables. */
269    if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
270        use_randfile = 0;
271        if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
272                && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
273                                                  NULL, 0)) == 0)
274            envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
275    }
276
277    /* If we got a value, allocate space to hold it and then get it. */
278    if (envlen != 0) {
279        int sz;
280        WCHAR *val = _alloca(envlen * sizeof(WCHAR));
281
282        if (GetEnvironmentVariableW(var, val, envlen) < envlen
283                && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
284                                             NULL, NULL)) != 0) {
285            s = _alloca(sz);
286            if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
287                                    NULL, NULL) == 0)
288                s = NULL;
289        }
290    }
291#else
292    if ((s = ossl_safe_getenv("RANDFILE")) == NULL || *s == '\0') {
293        use_randfile = 0;
294        s = ossl_safe_getenv("HOME");
295    }
296#endif
297
298#ifdef DEFAULT_HOME
299    if (!use_randfile && s == NULL)
300        s = DEFAULT_HOME;
301#endif
302    if (s == NULL || *s == '\0')
303        return NULL;
304
305    len = strlen(s);
306    if (use_randfile) {
307        if (len + 1 >= size)
308            return NULL;
309        strcpy(buf, s);
310    } else {
311        if (len + 1 + strlen(RFILE) + 1 >= size)
312            return NULL;
313        strcpy(buf, s);
314#ifndef OPENSSL_SYS_VMS
315        strcat(buf, "/");
316#endif
317        strcat(buf, RFILE);
318    }
319
320    return buf;
321}
322