Path: blob/main/crypto/openssl/apps/lib/app_rand.c
34878 views
/*1* Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#include "internal/e_os.h" /* LIST_SEPARATOR_CHAR */10#include "apps.h"11#include <openssl/bio.h>12#include <openssl/err.h>13#include <openssl/rand.h>14#include <openssl/conf.h>1516static char *save_rand_file;17static STACK_OF(OPENSSL_STRING) *randfiles;1819void app_RAND_load_conf(CONF *c, const char *section)20{21const char *randfile = app_conf_try_string(c, section, "RANDFILE");2223if (randfile == NULL)24return;25if (RAND_load_file(randfile, -1) < 0) {26BIO_printf(bio_err, "Can't load %s into RNG\n", randfile);27ERR_print_errors(bio_err);28}29if (save_rand_file == NULL) {30save_rand_file = OPENSSL_strdup(randfile);31/* If some internal memory errors have occurred */32if (save_rand_file == NULL) {33BIO_printf(bio_err, "Can't duplicate %s\n", randfile);34ERR_print_errors(bio_err);35}36}37}3839static int loadfiles(char *name)40{41char *p;42int last, ret = 1;4344for (;;) {45last = 0;46for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++)47continue;48if (*p == '\0')49last = 1;50*p = '\0';51if (RAND_load_file(name, -1) < 0) {52BIO_printf(bio_err, "Can't load %s into RNG\n", name);53ERR_print_errors(bio_err);54ret = 0;55}56if (last)57break;58name = p + 1;59if (*name == '\0')60break;61}62return ret;63}6465int app_RAND_load(void)66{67char *p;68int i, ret = 1;6970for (i = 0; i < sk_OPENSSL_STRING_num(randfiles); i++) {71p = sk_OPENSSL_STRING_value(randfiles, i);72if (!loadfiles(p))73ret = 0;74}75sk_OPENSSL_STRING_free(randfiles);76return ret;77}7879int app_RAND_write(void)80{81int ret = 1;8283if (save_rand_file == NULL)84return 1;85if (RAND_write_file(save_rand_file) == -1) {86BIO_printf(bio_err, "Cannot write random bytes:\n");87ERR_print_errors(bio_err);88ret = 0;89}90OPENSSL_free(save_rand_file);91save_rand_file = NULL;92return ret;93}949596/*97* See comments in opt_verify for explanation of this.98*/99enum r_range { OPT_R_ENUM };100101int opt_rand(int opt)102{103switch ((enum r_range)opt) {104case OPT_R__FIRST:105case OPT_R__LAST:106break;107case OPT_R_RAND:108if (randfiles == NULL109&& (randfiles = sk_OPENSSL_STRING_new_null()) == NULL)110return 0;111if (!sk_OPENSSL_STRING_push(randfiles, opt_arg()))112return 0;113break;114case OPT_R_WRITERAND:115OPENSSL_free(save_rand_file);116save_rand_file = OPENSSL_strdup(opt_arg());117if (save_rand_file == NULL)118return 0;119break;120}121return 1;122}123124125