]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/app_rand.c
Fix use-after-free
[thirdparty/openssl.git] / apps / app_rand.c
1 /*
2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (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
18 void app_RAND_load_conf(CONF *c, const char *section)
19 {
20 const char *randfile = NCONF_get_string(c, section, "RANDFILE");
21
22 if (randfile == NULL) {
23 ERR_clear_error();
24 return;
25 }
26 if (RAND_load_file(randfile, -1) < 0) {
27 BIO_printf(bio_err, "Can't load %s into RNG\n", randfile);
28 ERR_print_errors(bio_err);
29 return;
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 void app_RAND_write(void)
62 {
63 if (save_rand_file == NULL)
64 return;
65 if (RAND_write_file(save_rand_file) == -1) {
66 BIO_printf(bio_err, "Cannot write random bytes:\n");
67 ERR_print_errors(bio_err);
68 }
69 OPENSSL_free(save_rand_file);
70 save_rand_file = NULL;
71 }
72
73
74 /*
75 * See comments in opt_verify for explanation of this.
76 */
77 enum r_range { OPT_R_ENUM };
78
79 int opt_rand(int opt)
80 {
81 switch ((enum r_range)opt) {
82 case OPT_R__FIRST:
83 case OPT_R__LAST:
84 break;
85 case OPT_R_RAND:
86 return loadfiles(opt_arg());
87 break;
88 case OPT_R_WRITERAND:
89 OPENSSL_free(save_rand_file);
90 save_rand_file = OPENSSL_strdup(opt_arg());
91 break;
92 }
93 return 1;
94 }