randfile.c 7.8 KB
Newer Older
R
Rich Salz 已提交
1 2
/*
 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3
 *
R
Rich Salz 已提交
4 5 6 7
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
8 9
 */

10
#include "internal/cryptlib.h"
D
Dr. Stephen Henson 已提交
11

U
Ulf Möller 已提交
12
#include <errno.h>
13
#include <stdio.h>
B
Ben Laurie 已提交
14 15
#include <stdlib.h>
#include <string.h>
16

17 18
#include <openssl/crypto.h>
#include <openssl/rand.h>
19
#include <openssl/buffer.h>
20

21
#ifdef OPENSSL_SYS_VMS
22
# include <unixio.h>
23
#endif
A
Andy Polyakov 已提交
24 25 26
#ifndef NO_SYS_TYPES_H
# include <sys/types.h>
#endif
27
#ifndef OPENSSL_NO_POSIX_IO
A
Andy Polyakov 已提交
28
# include <sys/stat.h>
29
# include <fcntl.h>
30 31
#endif

32 33 34 35 36 37 38
/*
 * Following should not be needed, and we could have been stricter
 * and demand S_IS*. But some systems just don't comply... Formally
 * below macros are "anatomically incorrect", because normally they
 * would look like ((m) & MASK == TYPE), but since MASK availability
 * is as questionable, we settle for this poor-man fallback...
 */
39 40
# if !defined(S_ISREG)
#   define S_ISREG(m) ((m) & S_IFREG)
41
# endif
A
Andy Polyakov 已提交
42

43
#ifdef _WIN32
44 45 46 47
# define stat    _stat
# define chmod   _chmod
# define open    _open
# define fdopen  _fdopen
48 49
#endif

50
#define RAND_FILE_SIZE 1024
51

52
#ifdef OPENSSL_SYS_VMS
53 54 55 56 57 58 59 60 61 62 63 64
/*
 * Misc hacks needed for specific cases.
 *
 * __FILE_ptr32 is a type provided by DEC C headers (types.h specifically)
 * to make sure the FILE* is a 32-bit pointer no matter what.  We know that
 * stdio function return this type (a study of stdio.h proves it).
 */
# if __INITIAL_POINTER_SIZE == 64
#  pragma pointer_size save
#  pragma pointer_size 32
typedef char *char_ptr32;
#  pragma pointer_size restore
65 66
# endif

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 73 74
        (__FILE_ptr32 (*)(const char *, const char *, ...))fopen;
# define VMS_OPEN_ATTRS \
        "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 78
#endif

R
Rich Salz 已提交
79
#define RFILE ".rnd"
80

81 82
/*
 * Note that these functions are intended for seed files only. Entropy
83 84
 * devices and EGD sockets are handled in rand_unix.c  If |bytes| is
 * -1 read the complete file; otherwise read the specified amount.
85
 */
U
Ulf Möller 已提交
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 93
    int i, n, ret = 0;
    FILE *in;
94 95

    if (bytes == 0)
96
        return 0;
97

98
#ifndef OPENSSL_NO_POSIX_IO
99 100 101 102 103
    if (stat(file, &sb) < 0 || !S_ISREG(sb.st_mode)) {
        RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_NOT_A_REGULAR_FILE);
        ERR_add_error_data(2, "Filename=", file);
        return -1;
    }
104
#endif
105 106 107 108 109 110 111
    if ((in = openssl_fopen(file, "rb")) == NULL) {
        RANDerr(RAND_F_RAND_LOAD_FILE, RAND_R_CANNOT_OPEN_FILE);
        ERR_add_error_data(2, "Filename=", file);
        return -1;
    }

    for ( ; ; ) {
112
        if (bytes > 0)
113
            n = (bytes < RAND_FILE_SIZE) ? (int)bytes : RAND_FILE_SIZE;
114
        else
115
            n = RAND_FILE_SIZE;
116 117 118 119 120
        i = fread(buf, 1, n, in);
        if (i <= 0)
            break;
        RAND_add(buf, i, (double)i);
        ret += i;
121 122 123 124

        /* If given a bytecount, and we did it, break. */
        if (bytes > 0 && (bytes -= i) <= 0)
            break;
125
    }
126 127 128

    OPENSSL_cleanse(buf, sizeof(buf));
    fclose(in);
129
    return ret;
130
}
131

U
Ulf Möller 已提交
132
int RAND_write_file(const char *file)
133
{
134 135
    unsigned char buf[RAND_FILE_SIZE];
    int ret = -1;
136
    FILE *out = NULL;
137
#ifndef OPENSSL_NO_POSIX_IO
138
    struct stat sb;
139

140 141 142 143 144
    if (stat(file, &sb) >= 0 && !S_ISREG(sb.st_mode)) {
        RANDerr(RAND_F_RAND_WRITE_FILE, RAND_R_NOT_A_REGULAR_FILE);
        ERR_add_error_data(2, "Filename=", file);
        return -1;
    }
P
Paul Hovey 已提交
145
#endif
146

147 148 149 150
    /* Collect enough random data. */
    if (RAND_bytes(buf, (int)sizeof(buf)) != 1)
        return  -1;

151 152
#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && \
    !defined(OPENSSL_SYS_VMS) && !defined(OPENSSL_SYS_WINDOWS)
153 154 155 156 157 158 159 160 161 162 163 164
    {
# ifndef O_BINARY
#  define O_BINARY 0
# endif
        /*
         * chmod(..., 0600) is too late to protect the file, permissions
         * should be restrictive from the start
         */
        int fd = open(file, O_WRONLY | O_CREAT | O_BINARY, 0600);
        if (fd != -1)
            out = fdopen(fd, "wb");
    }
A
Andy Polyakov 已提交
165
#endif
166 167

#ifdef OPENSSL_SYS_VMS
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    /*
     * VMS NOTE: Prior versions of this routine created a _new_ version of
     * the rand file for each call into this routine, then deleted all
     * existing versions named ;-1, and finally renamed the current version
     * as ';1'. Under concurrent usage, this resulted in an RMS race
     * condition in rename() which could orphan files (see vms message help
     * for RMS$_REENT). With the fopen() calls below, openssl/VMS now shares
     * the top-level version of the rand file. Note that there may still be
     * conditions where the top-level rand file is locked. If so, this code
     * will then create a new version of the rand file. Without the delete
     * and rename code, this can result in ascending file versions that stop
     * at version 32767, and this routine will then return an error. The
     * remedy for this is to recode the calling application to avoid
     * concurrent use of the rand file, or synchronize usage at the
     * application level. Also consider whether or not you NEED a persistent
     * rand file in a concurrent use situation.
     */
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

M
Matt Caswell 已提交
193
#if !defined(NO_CHMOD) && !defined(OPENSSL_NO_POSIX_IO)
194 195 196
    /*
     * Yes it's late to do this (see above comment), but better than nothing.
     */
197
    chmod(file, 0600);
A
Andy Polyakov 已提交
198
#endif
199

200
    ret = fwrite(buf, 1, RAND_FILE_SIZE, out);
201
    fclose(out);
202 203
    OPENSSL_cleanse(buf, RAND_FILE_SIZE);
    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 214 215 216 217 218 219 220 221 222
    DWORD envlen;
    WCHAR *var;

    /* Look up various environment variables. */
    if ((envlen = GetEnvironmentVariableW(var = L"RANDFILE", NULL, 0)) == 0) {
        use_randfile = 0;
        if ((envlen = GetEnvironmentVariableW(var = L"HOME", NULL, 0)) == 0
                && (envlen = GetEnvironmentVariableW(var = L"USERPROFILE",
                                                  NULL, 0)) == 0)
            envlen = GetEnvironmentVariableW(var = L"SYSTEMROOT", NULL, 0);
223 224
    }

225 226
    /* If we got a value, allocate space to hold it and then get it. */
    if (envlen != 0) {
227
        int sz;
228
        WCHAR *val = _alloca(envlen * sizeof(WCHAR));
229

230 231 232
        if (GetEnvironmentVariableW(var, val, envlen) < envlen
                && (sz = WideCharToMultiByte(CP_UTF8, 0, val, -1, NULL, 0,
                                             NULL, NULL)) != 0) {
233 234 235 236
            s = _alloca(sz);
            if (WideCharToMultiByte(CP_UTF8, 0, val, -1, s, sz,
                                    NULL, NULL) == 0)
                s = NULL;
237
        }
238
    }
239
#else
240
    if (OPENSSL_issetugid() != 0) {
241
        use_randfile = 0;
242 243 244
    } else if ((s = getenv("RANDFILE")) == NULL || *s == '\0') {
        use_randfile = 0;
        s = getenv("HOME");
245
    }
246
#endif
247

248
#ifdef DEFAULT_HOME
249
    if (!use_randfile && s == NULL)
250
        s = DEFAULT_HOME;
251
#endif
252 253 254 255 256 257 258 259 260 261 262 263
    if (s == NULL || *s == '\0')
        return NULL;

    len = strlen(s);
    if (use_randfile) {
        if (len + 1 >= size)
            return NULL;
        strcpy(buf, s);
    } else {
        if (len + 1 + strlen(RFILE) + 1 >= size)
            return NULL;
        strcpy(buf, s);
264
#ifndef OPENSSL_SYS_VMS
265
        strcat(buf, "/");
U
Ulf Möller 已提交
266
#endif
267
        strcat(buf, RFILE);
268
    }
269

270
    return buf;
271
}