cut: code shrink
[busybox-git.git] / miscutils / seedrng.c
blob7a2331cb18b96b00116de54a21ebbd401fa1e3f2
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3 * Copyright (C) 2022 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
5 * SeedRNG is a simple program made for seeding the Linux kernel random number
6 * generator from seed files. It is is useful in light of the fact that the
7 * Linux kernel RNG cannot be initialized from shell scripts, and new seeds
8 * cannot be safely generated from boot time shell scripts either. It should
9 * be run once at init time and once at shutdown time. It can be run at other
10 * times on a timer as well. Whenever it is run, it writes existing seed files
11 * into the RNG pool, and then creates a new seed file. If the RNG is
12 * initialized at the time of creating a new seed file, then that new seed file
13 * is marked as "creditable", which means it can be used to initialize the RNG.
14 * Otherwise, it is marked as "non-creditable", in which case it is still used
15 * to seed the RNG's pool, but will not initialize the RNG. In order to ensure
16 * that entropy only ever stays the same or increases from one seed file to the
17 * next, old seed values are hashed together with new seed values when writing
18 * new seed files.
20 * This is based on code from <https://git.zx2c4.com/seedrng/about/>.
22 //config:config SEEDRNG
23 //config: bool "seedrng (9.1 kb)"
24 //config: default y
25 //config: help
26 //config: Seed the kernel RNG from seed files, meant to be called
27 //config: once during startup, once during shutdown, and optionally
28 //config: at some periodic interval in between.
30 //applet:IF_SEEDRNG(APPLET(seedrng, BB_DIR_USR_SBIN, BB_SUID_DROP))
32 //kbuild:lib-$(CONFIG_SEEDRNG) += seedrng.o
34 //usage:#define seedrng_trivial_usage
35 //usage: "[-d DIR] [-n]"
36 //usage:#define seedrng_full_usage "\n\n"
37 //usage: "Seed the kernel RNG from seed files"
38 //usage: "\n"
39 //usage: "\n -d DIR Use seed files in DIR (default: /var/lib/seedrng)"
40 //usage: "\n -n Do not credit randomness, even if creditable"
42 #include "libbb.h"
44 #include <linux/random.h>
45 #include <sys/file.h>
47 /* Fix up glibc <= 2.24 not having getrandom() */
48 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 24
49 #include <sys/syscall.h>
50 static ssize_t getrandom(void *buffer, size_t length, unsigned flags)
52 # if defined(__NR_getrandom)
53 return syscall(__NR_getrandom, buffer, length, flags);
54 # else
55 errno = ENOSYS;
56 return -1;
57 # endif
59 #else
60 #include <sys/random.h>
61 #endif
63 /* Apparently some headers don't ship with this yet. */
64 #ifndef GRND_NONBLOCK
65 #define GRND_NONBLOCK 0x0001
66 #endif
68 #ifndef GRND_INSECURE
69 #define GRND_INSECURE 0x0004
70 #endif
72 #define DEFAULT_SEED_DIR "/var/lib/seedrng"
73 #define CREDITABLE_SEED_NAME "seed.credit"
74 #define NON_CREDITABLE_SEED_NAME "seed.no-credit"
76 enum {
77 MIN_SEED_LEN = SHA256_OUTSIZE,
78 /* kernels < 5.18 could return short reads from getrandom()
79 * if signal is pending and length is > 256.
80 * Let's limit our reads to 256 bytes.
82 MAX_SEED_LEN = 256,
85 static size_t determine_optimal_seed_len(void)
87 char poolsize_str[12];
88 unsigned poolsize;
89 int n;
91 n = open_read_close("/proc/sys/kernel/random/poolsize", poolsize_str, sizeof(poolsize_str) - 1);
92 if (n < 0) {
93 bb_perror_msg("can't determine pool size, assuming %u bits", MIN_SEED_LEN * 8);
94 return MIN_SEED_LEN;
96 poolsize_str[n] = '\0';
97 poolsize = (bb_strtou(poolsize_str, NULL, 10) + 7) / 8;
98 return MAX(MIN(poolsize, MAX_SEED_LEN), MIN_SEED_LEN);
101 static bool read_new_seed(uint8_t *seed, size_t len)
103 bool is_creditable;
104 ssize_t ret;
106 ret = getrandom(seed, len, GRND_NONBLOCK);
107 if (ret == (ssize_t)len) {
108 return true;
110 if (ret < 0 && errno == ENOSYS) {
111 int fd = xopen("/dev/random", O_RDONLY);
112 struct pollfd random_fd;
113 random_fd.fd = fd;
114 random_fd.events = POLLIN;
115 is_creditable = poll(&random_fd, 1, 0) == 1;
116 //This is racy. is_creditable can be set to true here, but other process
117 //can consume "good" random data from /dev/urandom before we do it below.
118 close(fd);
119 } else {
120 if (getrandom(seed, len, GRND_INSECURE) == (ssize_t)len)
121 return false;
122 is_creditable = false;
125 /* Either getrandom() is not implemented, or
126 * getrandom(GRND_INSECURE) did not give us LEN bytes.
127 * Fallback to reading /dev/urandom.
129 errno = 0;
130 if (open_read_close("/dev/urandom", seed, len) != (ssize_t)len)
131 bb_perror_msg_and_die("can't read '%s'", "/dev/urandom");
132 return is_creditable;
135 static void seed_from_file_if_exists(const char *filename, int dfd, bool credit, sha256_ctx_t *hash)
137 struct {
138 int entropy_count;
139 int buf_size;
140 uint8_t buf[MAX_SEED_LEN];
141 } req;
142 ssize_t seed_len;
144 seed_len = open_read_close(filename, req.buf, sizeof(req.buf));
145 if (seed_len < 0) {
146 if (errno != ENOENT)
147 bb_perror_msg_and_die("can't read '%s'", filename);
148 return;
150 xunlink(filename);
151 if (seed_len != 0) {
152 int fd;
154 /* We are going to use this data to seed the RNG:
155 * we believe it to genuinely containing entropy.
156 * If this just-unlinked file survives
157 * (if machine crashes before deletion is recorded on disk)
158 * and we reuse it after reboot, this assumption
159 * would be violated, and RNG may end up generating
160 * the same data. fsync the directory
161 * to make sure file is gone:
163 if (fsync(dfd) != 0)
164 bb_simple_perror_msg_and_die("I/O error");
166 //Length is not random, and taking its address spills variable to stack
167 // sha256_hash(hash, &seed_len, sizeof(seed_len));
168 sha256_hash(hash, req.buf, seed_len);
170 req.buf_size = seed_len;
171 seed_len *= 8;
172 req.entropy_count = credit ? seed_len : 0;
173 printf("Seeding %u bits %s crediting\n",
174 (unsigned)seed_len, credit ? "and" : "without");
175 fd = xopen("/dev/urandom", O_RDONLY);
176 xioctl(fd, RNDADDENTROPY, &req);
177 if (ENABLE_FEATURE_CLEAN_UP)
178 close(fd);
182 int seedrng_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
183 int seedrng_main(int argc UNUSED_PARAM, char **argv)
185 const char *seed_dir;
186 int fd, dfd;
187 int i;
188 unsigned opts;
189 uint8_t new_seed[MAX_SEED_LEN];
190 size_t new_seed_len;
191 bool new_seed_creditable;
192 struct timespec timestamp[2];
193 sha256_ctx_t hash;
195 enum {
196 OPT_n = (1 << 0), /* must be 1 */
197 OPT_d = (1 << 1),
199 #if ENABLE_LONG_OPTS
200 static const char longopts[] ALIGN1 =
201 "skip-credit\0" No_argument "n"
202 "seed-dir\0" Required_argument "d"
204 #endif
206 seed_dir = DEFAULT_SEED_DIR;
207 opts = getopt32long(argv, "nd:", longopts, &seed_dir);
208 umask(0077);
209 if (getuid() != 0)
210 bb_simple_error_msg_and_die(bb_msg_you_must_be_root);
212 if (mkdir(seed_dir, 0700) < 0 && errno != EEXIST)
213 bb_perror_msg_and_die("can't create directory '%s'", seed_dir);
214 dfd = xopen(seed_dir, O_DIRECTORY | O_RDONLY);
215 xfchdir(dfd);
216 /* Concurrent runs of this tool might feed the same data to RNG twice.
217 * Avoid concurrent runs by taking a blocking lock on the directory.
218 * Not checking for errors. Looking at manpage,
219 * ENOLCK "The kernel ran out of memory for allocating lock records"
220 * seems to be the only one which is possible - and if that happens,
221 * machine is OOMing (much worse problem than inability to lock...).
222 * Also, typically configured Linux machines do not fail GFP_KERNEL
223 * allocations (they trigger memory reclaim instead).
225 flock(dfd, LOCK_EX); /* blocks while another instance runs */
227 sha256_begin(&hash);
228 //Hashing in a constant string doesn't add any entropy
229 // sha256_hash(&hash, "SeedRNG v1 Old+New Prefix", 25);
230 clock_gettime(CLOCK_REALTIME, &timestamp[0]);
231 clock_gettime(CLOCK_BOOTTIME, &timestamp[1]);
232 sha256_hash(&hash, timestamp, sizeof(timestamp));
234 for (i = 0; i <= 1; i++) {
235 seed_from_file_if_exists(
236 i == 0 ? NON_CREDITABLE_SEED_NAME : CREDITABLE_SEED_NAME,
237 dfd,
238 /*credit?*/ (opts ^ OPT_n) & i, /* 0, then 1 unless -n */
239 &hash);
242 new_seed_len = determine_optimal_seed_len();
243 new_seed_creditable = read_new_seed(new_seed, new_seed_len);
244 //Length is not random, and taking its address spills variable to stack
245 // sha256_hash(&hash, &new_seed_len, sizeof(new_seed_len));
246 sha256_hash(&hash, new_seed, new_seed_len);
247 sha256_end(&hash, new_seed + new_seed_len - SHA256_OUTSIZE);
249 printf("Saving %u bits of %screditable seed for next boot\n",
250 (unsigned)new_seed_len * 8, new_seed_creditable ? "" : "non-");
251 fd = xopen3(NON_CREDITABLE_SEED_NAME, O_WRONLY | O_CREAT | O_TRUNC, 0400);
252 xwrite(fd, new_seed, new_seed_len);
253 if (new_seed_creditable) {
254 /* More paranoia when we create a file which we believe contains
255 * genuine entropy: make sure disk is not full, quota isn't exceeded, etc:
257 if (fsync(fd) < 0)
258 bb_perror_msg_and_die("can't write '%s'", NON_CREDITABLE_SEED_NAME);
259 xrename(NON_CREDITABLE_SEED_NAME, CREDITABLE_SEED_NAME);
261 return EXIT_SUCCESS;