]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/lib/app_rand.c
APPS: make apps strict on app_RAND_load() and app_RAND_write() failure
[thirdparty/openssl.git] / apps / lib / app_rand.c
1 /*
2 * Copyright 1995-2021 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 #include "apps.h"
11 #include <openssl/bio.h>
12 #include <openssl/err.h>
13 #include <openssl/rand.h>
14 #include <openssl/conf.h>
15
16 static char *save_rand_file;
17 static STACK_OF(OPENSSL_STRING) *randfiles;
18
19 void app_RAND_load_conf(CONF *c, const char *section)
20 {
21 const char *randfile = NCONF_get_string(c, section, "RANDFILE");
22
23 if (randfile == NULL) {
24 ERR_clear_error();
25 return;
26 }
27 if (RAND_load_file(randfile, -1) < 0) {
28 BIO_printf(bio_err, "Can't load %s into RNG\n", randfile);
29 ERR_print_errors(bio_err);
30 }
31 if (save_rand_file == NULL)
32 save_rand_file = OPENSSL_strdup(randfile);
33 }
34
35 static int loadfiles(char *name)
36 {
37 char *p;
38 int last, ret = 1;
39
40 for ( ; ; ) {
41 last = 0;
42 for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++)
43 continue;
44 if (*p == '\0')
45 last = 1;
46 *p = '\0';
47 if (RAND_load_file(name, -1) < 0) {
48 BIO_printf(bio_err, "Can't load %s into RNG\n", name);
49 ERR_print_errors(bio_err);
50 ret = 0;
51 }
52 if (last)
53 break;
54 name = p + 1;
55 if (*name == '\0')
56 break;
57 }
58 return ret;
59 }
60
61 int app_RAND_load(void)
62 {
63 char *p;
64 int i, ret = 1;
65
66 for (i = 0; i < sk_OPENSSL_STRING_num(randfiles); i++) {
67 p = sk_OPENSSL_STRING_value(randfiles, i);
68 if (!loadfiles(p))
69 ret = 0;
70 }
71 sk_OPENSSL_STRING_free(randfiles);
72 return ret;
73 }
74
75 int app_RAND_write(void)
76 {
77 int ret = 1;
78
79 if (save_rand_file == NULL)
80 return 1;
81 if (RAND_write_file(save_rand_file) == -1) {
82 BIO_printf(bio_err, "Cannot write random bytes:\n");
83 ERR_print_errors(bio_err);
84 ret = 0;
85 }
86 OPENSSL_free(save_rand_file);
87 save_rand_file = NULL;
88 return ret;
89 }
90
91
92 /*
93 * See comments in opt_verify for explanation of this.
94 */
95 enum r_range { OPT_R_ENUM };
96
97 int opt_rand(int opt)
98 {
99 switch ((enum r_range)opt) {
100 case OPT_R__FIRST:
101 case OPT_R__LAST:
102 break;
103 case OPT_R_RAND:
104 if (randfiles == NULL
105 && (randfiles = sk_OPENSSL_STRING_new_null()) == NULL)
106 return 0;
107 if (!sk_OPENSSL_STRING_push(randfiles, opt_arg()))
108 return 0;
109 break;
110 case OPT_R_WRITERAND:
111 OPENSSL_free(save_rand_file);
112 save_rand_file = OPENSSL_strdup(opt_arg());
113 break;
114 }
115 return 1;
116 }