155714Skris/* crypto/rand/randfile.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8296341Sdelphij *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15296341Sdelphij *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22296341Sdelphij *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37296341Sdelphij * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40296341Sdelphij *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52296341Sdelphij *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5855714Skris
59127128Snectar/* We need to define this to get macros like S_IFBLK and S_IFCHR */
60246772Sjkim#if !defined(OPENSSL_SYS_VXWORKS)
61296341Sdelphij# define _XOPEN_SOURCE 500
62246772Sjkim#endif
63127128Snectar
6455714Skris#include <errno.h>
6555714Skris#include <stdio.h>
6655714Skris#include <stdlib.h>
6755714Skris#include <string.h>
6855714Skris
69109998Smarkm#include "e_os.h"
70109998Smarkm#include <openssl/crypto.h>
71109998Smarkm#include <openssl/rand.h>
72127128Snectar#include <openssl/buffer.h>
73109998Smarkm
74109998Smarkm#ifdef OPENSSL_SYS_VMS
75296341Sdelphij# include <unixio.h>
7659191Skris#endif
7759191Skris#ifndef NO_SYS_TYPES_H
7859191Skris# include <sys/types.h>
7959191Skris#endif
80238405Sjkim#ifndef OPENSSL_NO_POSIX_IO
8159191Skris# include <sys/stat.h>
82269686Sjkim# include <fcntl.h>
8359191Skris#endif
8459191Skris
85194206Ssimon#ifdef _WIN32
86296341Sdelphij# define stat    _stat
87296341Sdelphij# define chmod   _chmod
88296341Sdelphij# define open    _open
89296341Sdelphij# define fdopen  _fdopen
90194206Ssimon#endif
91194206Ssimon
9255714Skris#undef BUFSIZE
93296341Sdelphij#define BUFSIZE 1024
9455714Skris#define RAND_DATA 1024
9555714Skris
96194206Ssimon#ifdef OPENSSL_SYS_VMS
97296341Sdelphij/*
98296341Sdelphij * This declaration is a nasty hack to get around vms' extension to fopen for
99296341Sdelphij * passing in sharing options being disabled by our /STANDARD=ANSI89
100296341Sdelphij */
101194206Ssimonstatic FILE *(*const vms_fopen)(const char *, const char *, ...) =
102194206Ssimon    (FILE *(*)(const char *, const char *, ...))fopen;
103296341Sdelphij# define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
104194206Ssimon#endif
105194206Ssimon
10659191Skris/* #define RFILE ".rnd" - defined in ../../e_os.h */
10755714Skris
108296341Sdelphij/*
109296341Sdelphij * Note that these functions are intended for seed files only. Entropy
110296341Sdelphij * devices and EGD sockets are handled in rand_unix.c
111296341Sdelphij */
11272613Skris
11355714Skrisint RAND_load_file(const char *file, long bytes)
114296341Sdelphij{
115296341Sdelphij    /*-
116296341Sdelphij     * If bytes >= 0, read up to 'bytes' bytes.
117296341Sdelphij     * if bytes == -1, read complete file.
118296341Sdelphij     */
11959191Skris
120296341Sdelphij    MS_STATIC unsigned char buf[BUFSIZE];
121238405Sjkim#ifndef OPENSSL_NO_POSIX_IO
122296341Sdelphij    struct stat sb;
123238405Sjkim#endif
124296341Sdelphij    int i, ret = 0, n;
125296341Sdelphij    FILE *in;
12655714Skris
127296341Sdelphij    if (file == NULL)
128296341Sdelphij        return (0);
12955714Skris
130238405Sjkim#ifndef OPENSSL_NO_POSIX_IO
131296341Sdelphij# ifdef PURIFY
132296341Sdelphij    /*
133296341Sdelphij     * struct stat can have padding and unused fields that may not be
134296341Sdelphij     * initialized in the call to stat(). We need to clear the entire
135296341Sdelphij     * structure before calling RAND_add() to avoid complaints from
136296341Sdelphij     * applications such as Valgrind.
137296341Sdelphij     */
138296341Sdelphij    memset(&sb, 0, sizeof(sb));
139296341Sdelphij# endif
140296341Sdelphij    if (stat(file, &sb) < 0)
141296341Sdelphij        return (0);
142296341Sdelphij    RAND_add(&sb, sizeof(sb), 0.0);
143205128Ssimon#endif
144296341Sdelphij    if (bytes == 0)
145296341Sdelphij        return (ret);
14655714Skris
147194206Ssimon#ifdef OPENSSL_SYS_VMS
148296341Sdelphij    in = vms_fopen(file, "rb", VMS_OPEN_ATTRS);
149194206Ssimon#else
150296341Sdelphij    in = fopen(file, "rb");
151194206Ssimon#endif
152296341Sdelphij    if (in == NULL)
153296341Sdelphij        goto err;
154238405Sjkim#if defined(S_IFBLK) && defined(S_IFCHR) && !defined(OPENSSL_NO_POSIX_IO)
155296341Sdelphij    if (sb.st_mode & (S_IFBLK | S_IFCHR)) {
156296341Sdelphij        /*
157296341Sdelphij         * this file is a device. we don't want read an infinite number of
158296341Sdelphij         * bytes from a random device, nor do we want to use buffered I/O
159296341Sdelphij         * because we will waste system entropy.
160296341Sdelphij         */
161296341Sdelphij        bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
162296341Sdelphij# ifndef OPENSSL_NO_SETVBUF_IONBF
163296341Sdelphij        setvbuf(in, NULL, _IONBF, 0); /* don't do buffered reads */
164296341Sdelphij# endif                         /* ndef OPENSSL_NO_SETVBUF_IONBF */
165296341Sdelphij    }
166127128Snectar#endif
167296341Sdelphij    for (;;) {
168296341Sdelphij        if (bytes > 0)
169296341Sdelphij            n = (bytes < BUFSIZE) ? (int)bytes : BUFSIZE;
170296341Sdelphij        else
171296341Sdelphij            n = BUFSIZE;
172296341Sdelphij        i = fread(buf, 1, n, in);
173296341Sdelphij        if (i <= 0)
174296341Sdelphij            break;
175194206Ssimon#ifdef PURIFY
176296341Sdelphij        RAND_add(buf, i, (double)i);
177194206Ssimon#else
178296341Sdelphij        /* even if n != i, use the full array */
179296341Sdelphij        RAND_add(buf, n, (double)i);
180194206Ssimon#endif
181296341Sdelphij        ret += i;
182296341Sdelphij        if (bytes > 0) {
183296341Sdelphij            bytes -= n;
184296341Sdelphij            if (bytes <= 0)
185296341Sdelphij                break;
186296341Sdelphij        }
187296341Sdelphij    }
188296341Sdelphij    fclose(in);
189296341Sdelphij    OPENSSL_cleanse(buf, BUFSIZE);
190296341Sdelphij err:
191296341Sdelphij    return (ret);
192296341Sdelphij}
19355714Skris
19455714Skrisint RAND_write_file(const char *file)
195296341Sdelphij{
196296341Sdelphij    unsigned char buf[BUFSIZE];
197296341Sdelphij    int i, ret = 0, rand_err = 0;
198296341Sdelphij    FILE *out = NULL;
199296341Sdelphij    int n;
200238405Sjkim#ifndef OPENSSL_NO_POSIX_IO
201296341Sdelphij    struct stat sb;
202296341Sdelphij
203296341Sdelphij    i = stat(file, &sb);
204296341Sdelphij    if (i != -1) {
205296341Sdelphij# if defined(S_ISBLK) && defined(S_ISCHR)
206296341Sdelphij        if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
207296341Sdelphij            /*
208296341Sdelphij             * this file is a device. we don't write back to it. we
209296341Sdelphij             * "succeed" on the assumption this is some sort of random
210296341Sdelphij             * device. Otherwise attempting to write to and chmod the device
211296341Sdelphij             * causes problems.
212296341Sdelphij             */
213296341Sdelphij            return (1);
214296341Sdelphij        }
215296341Sdelphij# endif
216296341Sdelphij    }
217127128Snectar#endif
218127128Snectar
219238405Sjkim#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_SYS_VMS)
220296341Sdelphij    {
221296341Sdelphij# ifndef O_BINARY
222296341Sdelphij#  define O_BINARY 0
223296341Sdelphij# endif
224296341Sdelphij        /*
225296341Sdelphij         * chmod(..., 0600) is too late to protect the file, permissions
226296341Sdelphij         * should be restrictive from the start
227296341Sdelphij         */
228296341Sdelphij        int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
229296341Sdelphij        if (fd != -1)
230296341Sdelphij            out = fdopen(fd, "wb");
231296341Sdelphij    }
232238405Sjkim#endif
233194206Ssimon
234194206Ssimon#ifdef OPENSSL_SYS_VMS
235296341Sdelphij    /*
236296341Sdelphij     * VMS NOTE: Prior versions of this routine created a _new_ version of
237296341Sdelphij     * the rand file for each call into this routine, then deleted all
238296341Sdelphij     * existing versions named ;-1, and finally renamed the current version
239296341Sdelphij     * as ';1'. Under concurrent usage, this resulted in an RMS race
240296341Sdelphij     * condition in rename() which could orphan files (see vms message help
241296341Sdelphij     * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
242296341Sdelphij     * the top-level version of the rand file. Note that there may still be
243296341Sdelphij     * conditions where the top-level rand file is locked. If so, this code
244296341Sdelphij     * will then create a new version of the rand file. Without the delete
245296341Sdelphij     * and rename code, this can result in ascending file versions that stop
246296341Sdelphij     * at version 32767, and this routine will then return an error. The
247296341Sdelphij     * remedy for this is to recode the calling application to avoid
248296341Sdelphij     * concurrent use of the rand file, or synchronize usage at the
249296341Sdelphij     * application level. Also consider whether or not you NEED a persistent
250296341Sdelphij     * rand file in a concurrent use situation.
251296341Sdelphij     */
252194206Ssimon
253296341Sdelphij    out = vms_fopen(file, "rb+", VMS_OPEN_ATTRS);
254296341Sdelphij    if (out == NULL)
255296341Sdelphij        out = vms_fopen(file, "wb", VMS_OPEN_ATTRS);
256194206Ssimon#else
257296341Sdelphij    if (out == NULL)
258296341Sdelphij        out = fopen(file, "wb");
259194206Ssimon#endif
260296341Sdelphij    if (out == NULL)
261296341Sdelphij        goto err;
26259191Skris
26359191Skris#ifndef NO_CHMOD
264296341Sdelphij    chmod(file, 0600);
26559191Skris#endif
266296341Sdelphij    n = RAND_DATA;
267296341Sdelphij    for (;;) {
268296341Sdelphij        i = (n > BUFSIZE) ? BUFSIZE : n;
269296341Sdelphij        n -= BUFSIZE;
270296341Sdelphij        if (RAND_bytes(buf, i) <= 0)
271296341Sdelphij            rand_err = 1;
272296341Sdelphij        i = fwrite(buf, 1, i, out);
273296341Sdelphij        if (i <= 0) {
274296341Sdelphij            ret = 0;
275296341Sdelphij            break;
276296341Sdelphij        }
277296341Sdelphij        ret += i;
278296341Sdelphij        if (n <= 0)
279296341Sdelphij            break;
280296341Sdelphij    }
28159191Skris
282296341Sdelphij    fclose(out);
283296341Sdelphij    OPENSSL_cleanse(buf, BUFSIZE);
284296341Sdelphij err:
285296341Sdelphij    return (rand_err ? -1 : ret);
286296341Sdelphij}
28755714Skris
28876866Skrisconst char *RAND_file_name(char *buf, size_t size)
289296341Sdelphij{
290296341Sdelphij    char *s = NULL;
291215697Ssimon#ifdef __OpenBSD__
292296341Sdelphij    struct stat sb;
293127128Snectar#endif
29455714Skris
295296341Sdelphij    if (OPENSSL_issetugid() == 0)
296296341Sdelphij        s = getenv("RANDFILE");
297296341Sdelphij    if (s != NULL && *s && strlen(s) + 1 < size) {
298296341Sdelphij        if (BUF_strlcpy(buf, s, size) >= size)
299296341Sdelphij            return NULL;
300296341Sdelphij    } else {
301296341Sdelphij        if (OPENSSL_issetugid() == 0)
302296341Sdelphij            s = getenv("HOME");
30379998Skris#ifdef DEFAULT_HOME
304296341Sdelphij        if (s == NULL) {
305296341Sdelphij            s = DEFAULT_HOME;
306296341Sdelphij        }
30779998Skris#endif
308296341Sdelphij        if (s && *s && strlen(s) + strlen(RFILE) + 2 < size) {
309296341Sdelphij            BUF_strlcpy(buf, s, size);
310109998Smarkm#ifndef OPENSSL_SYS_VMS
311296341Sdelphij            BUF_strlcat(buf, "/", size);
31255714Skris#endif
313296341Sdelphij            BUF_strlcat(buf, RFILE, size);
314296341Sdelphij        } else
315296341Sdelphij            buf[0] = '\0';      /* no file name */
316296341Sdelphij    }
317127128Snectar
318127128Snectar#ifdef __OpenBSD__
319296341Sdelphij    /*
320296341Sdelphij     * given that all random loads just fail if the file can't be seen on a
321296341Sdelphij     * stat, we stat the file we're returning, if it fails, use /dev/arandom
322296341Sdelphij     * instead. this allows the user to use their own source for good random
323296341Sdelphij     * data, but defaults to something hopefully decent if that isn't
324296341Sdelphij     * available.
325296341Sdelphij     */
326127128Snectar
327296341Sdelphij    if (!buf[0])
328296341Sdelphij        if (BUF_strlcpy(buf, "/dev/arandom", size) >= size) {
329296341Sdelphij            return (NULL);
330296341Sdelphij        }
331296341Sdelphij    if (stat(buf, &sb) == -1)
332296341Sdelphij        if (BUF_strlcpy(buf, "/dev/arandom", size) >= size) {
333296341Sdelphij            return (NULL);
334296341Sdelphij        }
335127128Snectar#endif
336296341Sdelphij    return (buf);
337296341Sdelphij}
338