blob: 1bceae405c94c0c4bdad0824828446bdaa637288 [file] [log] [blame]
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +02001// SPDX-License-Identifier: GPL-2.0 OR MIT
2/*
3 * Copyright (C) 2022 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4 *
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +02005 * 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.
19 *
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020020 * This is based on code from <https://git.zx2c4.com/seedrng/about/>.
21 */
22
23//config:config SEEDRNG
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +020024//config: bool "seedrng (2.5 kb)"
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020025//config: default y
26//config: help
27//config: Seed the kernel RNG from seed files, meant to be called
28//config: once during startup, once during shutdown, and optionally
29//config: at some periodic interval in between.
30
31//applet:IF_SEEDRNG(APPLET(seedrng, BB_DIR_USR_SBIN, BB_SUID_DROP))
32
33//kbuild:lib-$(CONFIG_SEEDRNG) += seedrng.o
34
35//usage:#define seedrng_trivial_usage
36//usage: "[-d SEED_DIRECTORY] [-l LOCK_FILE] [-n]"
37//usage:#define seedrng_full_usage "\n\n"
38//usage: "Seed the kernel RNG from seed files."
39//usage: "\n"
40//usage: "\n -d, --seed-dir DIR Use seed files from specified directory (default: /var/lib/seedrng)"
41//usage: "\n -l, --lock-file FILE Use file as exclusive lock (default: /var/run/seedrng.lock)"
42//usage: "\n -n, --skip-credit Skip crediting seeds, even if creditable"
43
44#include "libbb.h"
45
46#include <linux/random.h>
47#include <sys/random.h>
48#include <sys/ioctl.h>
49#include <sys/file.h>
50#include <sys/stat.h>
51#include <sys/types.h>
52#include <fcntl.h>
53#include <poll.h>
54#include <unistd.h>
55#include <time.h>
56#include <errno.h>
57#include <endian.h>
58#include <stdbool.h>
59#include <stdint.h>
60#include <string.h>
61#include <stdio.h>
62#include <stdlib.h>
63
64#ifndef GRND_INSECURE
65#define GRND_INSECURE 0x0004 /* Apparently some headers don't ship with this yet. */
66#endif
67
Jason A. Donenfeld45385782022-04-20 15:22:55 +020068#if ENABLE_PID_FILE_PATH
69#define PID_FILE_PATH CONFIG_PID_FILE_PATH
70#else
71#define PID_FILE_PATH "/var/run"
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020072#endif
73
Jason A. Donenfeld45385782022-04-20 15:22:55 +020074#define DEFAULT_SEED_DIR "/var/lib/seedrng"
75#define DEFAULT_LOCK_FILE PID_FILE_PATH "/seedrng.lock"
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020076#define CREDITABLE_SEED_NAME "seed.credit"
77#define NON_CREDITABLE_SEED_NAME "seed.no-credit"
78
79static char *seed_dir, *lock_file, *creditable_seed, *non_creditable_seed;
80
81enum seedrng_lengths {
Jason A. Donenfeld45385782022-04-20 15:22:55 +020082 MIN_SEED_LEN = SHA256_OUTSIZE,
83 MAX_SEED_LEN = 512
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020084};
85
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020086static size_t determine_optimal_seed_len(void)
87{
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020088 char poolsize_str[11] = { 0 };
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +020089 unsigned long poolsize;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020090
Jason A. Donenfeld45385782022-04-20 15:22:55 +020091 if (open_read_close("/proc/sys/kernel/random/poolsize", poolsize_str, sizeof(poolsize_str) - 1) < 0) {
92 bb_perror_msg("unable to determine pool size, falling back to %u bits", MIN_SEED_LEN * 8);
93 return MIN_SEED_LEN;
94 }
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +020095 poolsize = (bb_strtoul(poolsize_str, NULL, 10) + 7) / 8;
96 return MAX(MIN(poolsize, MAX_SEED_LEN), MIN_SEED_LEN);
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +020097}
98
99static int read_new_seed(uint8_t *seed, size_t len, bool *is_creditable)
100{
101 ssize_t ret;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200102
103 *is_creditable = false;
104 ret = getrandom(seed, len, GRND_NONBLOCK);
105 if (ret == (ssize_t)len) {
106 *is_creditable = true;
107 return 0;
108 } else if (ret < 0 && errno == ENOSYS) {
109 struct pollfd random_fd = {
110 .fd = open("/dev/random", O_RDONLY),
111 .events = POLLIN
112 };
113 if (random_fd.fd < 0)
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200114 return -1;
115 *is_creditable = safe_poll(&random_fd, 1, 0) == 1;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200116 close(random_fd.fd);
117 } else if (getrandom(seed, len, GRND_INSECURE) == (ssize_t)len)
118 return 0;
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200119 if (open_read_close("/dev/urandom", seed, len) == (ssize_t)len)
120 return 0;
121 if (!errno)
122 errno = EIO;
123 return -1;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200124}
125
126static int seed_rng(uint8_t *seed, size_t len, bool credit)
127{
128 struct {
129 int entropy_count;
130 int buf_size;
131 uint8_t buffer[MAX_SEED_LEN];
132 } req = {
133 .entropy_count = credit ? len * 8 : 0,
134 .buf_size = len
135 };
136 int random_fd, ret;
137
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200138 if (len > sizeof(req.buffer)) {
139 errno = EFBIG;
140 return -1;
141 }
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200142 memcpy(req.buffer, seed, len);
143
144 random_fd = open("/dev/random", O_RDWR);
145 if (random_fd < 0)
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200146 return -1;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200147 ret = ioctl(random_fd, RNDADDENTROPY, &req);
148 if (ret)
149 ret = -errno ? -errno : -EIO;
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200150 if (ENABLE_FEATURE_CLEAN_UP)
151 close(random_fd);
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200152 errno = -ret;
153 return ret ? -1 : 0;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200154}
155
156static int seed_from_file_if_exists(const char *filename, bool credit, sha256_ctx_t *hash)
157{
158 uint8_t seed[MAX_SEED_LEN];
159 ssize_t seed_len;
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200160 int dfd = -1, ret = 0;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200161
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200162 dfd = open(seed_dir, O_DIRECTORY | O_RDONLY);
163 if (dfd < 0) {
164 ret = -errno;
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200165 bb_simple_perror_msg("unable to open seed directory");
166 goto out;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200167 }
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200168 seed_len = open_read_close(filename, seed, sizeof(seed));
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200169 if (seed_len < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200170 if (errno != ENOENT) {
171 ret = -errno;
172 bb_simple_perror_msg("unable to read seed file");
173 }
174 goto out;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200175 }
176 if ((unlink(filename) < 0 || fsync(dfd) < 0) && seed_len) {
177 ret = -errno;
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200178 bb_simple_perror_msg("unable to remove seed after reading, so not seeding");
179 goto out;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200180 }
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200181 if (!seed_len)
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200182 goto out;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200183
184 sha256_hash(hash, &seed_len, sizeof(seed_len));
185 sha256_hash(hash, seed, seed_len);
186
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200187 printf("Seeding %zd bits %s crediting\n", seed_len * 8, credit ? "and" : "without");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200188 ret = seed_rng(seed, seed_len, credit);
189 if (ret < 0)
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200190 bb_simple_perror_msg("unable to seed");
191out:
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200192 if (ENABLE_FEATURE_CLEAN_UP && dfd >= 0)
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200193 close(dfd);
194 errno = -ret;
195 return ret ? -1 : 0;
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200196}
197
198int seedrng_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
199int seedrng_main(int argc UNUSED_PARAM, char *argv[])
200{
201 static const char seedrng_prefix[] = "SeedRNG v1 Old+New Prefix";
202 static const char seedrng_failure[] = "SeedRNG v1 No New Seed Failure";
203 int ret, fd = -1, lock, program_ret = 0;
204 uint8_t new_seed[MAX_SEED_LEN];
205 size_t new_seed_len;
206 bool new_seed_creditable;
207 bool skip_credit = false;
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200208 struct timespec timestamp = { 0 };
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200209 sha256_ctx_t hash;
210
211 int opt;
212 enum {
213 OPT_d = (1 << 0),
214 OPT_l = (1 << 1),
215 OPT_n = (1 << 2)
216 };
217#if ENABLE_LONG_OPTS
218 static const char longopts[] ALIGN1 =
219 "seed-dir\0" Required_argument "d"
220 "lock-file\0" Required_argument "l"
221 "skip-credit\0" No_argument "n"
222 ;
223#endif
224
225 opt = getopt32long(argv, "d:l:n", longopts, &seed_dir, &lock_file);
226 if (!(opt & OPT_d) || !seed_dir)
227 seed_dir = xstrdup(DEFAULT_SEED_DIR);
228 if (!(opt & OPT_l) || !lock_file)
229 lock_file = xstrdup(DEFAULT_LOCK_FILE);
230 skip_credit = opt & OPT_n;
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200231 creditable_seed = concat_path_file(seed_dir, CREDITABLE_SEED_NAME);
232 non_creditable_seed = concat_path_file(seed_dir, NON_CREDITABLE_SEED_NAME);
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200233
234 umask(0077);
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200235 if (getuid())
236 bb_simple_error_msg_and_die("this program requires root");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200237
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200238 if (mkdir(seed_dir, 0700) < 0 && errno != EEXIST)
239 bb_simple_perror_msg_and_die("unable to create seed directory");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200240
241 lock = open(lock_file, O_WRONLY | O_CREAT, 0000);
242 if (lock < 0 || flock(lock, LOCK_EX) < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200243 bb_simple_perror_msg("unable to open lock file");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200244 program_ret = 1;
245 goto out;
246 }
247
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200248 sha256_begin(&hash);
249 sha256_hash(&hash, seedrng_prefix, strlen(seedrng_prefix));
250 clock_gettime(CLOCK_REALTIME, &timestamp);
251 sha256_hash(&hash, &timestamp, sizeof(timestamp));
252 clock_gettime(CLOCK_BOOTTIME, &timestamp);
253 sha256_hash(&hash, &timestamp, sizeof(timestamp));
254
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200255 ret = seed_from_file_if_exists(non_creditable_seed, false, &hash);
256 if (ret < 0)
257 program_ret |= 1 << 1;
258 ret = seed_from_file_if_exists(creditable_seed, !skip_credit, &hash);
259 if (ret < 0)
260 program_ret |= 1 << 2;
261
262 new_seed_len = determine_optimal_seed_len();
263 ret = read_new_seed(new_seed, new_seed_len, &new_seed_creditable);
264 if (ret < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200265 bb_simple_perror_msg("unable to read new seed");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200266 new_seed_len = SHA256_OUTSIZE;
267 strncpy((char *)new_seed, seedrng_failure, new_seed_len);
268 program_ret |= 1 << 3;
269 }
270 sha256_hash(&hash, &new_seed_len, sizeof(new_seed_len));
271 sha256_hash(&hash, new_seed, new_seed_len);
272 sha256_end(&hash, new_seed + new_seed_len - SHA256_OUTSIZE);
273
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200274 printf("Saving %zu bits of %s seed for next boot\n", new_seed_len * 8, new_seed_creditable ? "creditable" : "non-creditable");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200275 fd = open(non_creditable_seed, O_WRONLY | O_CREAT | O_TRUNC, 0400);
276 if (fd < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200277 bb_simple_perror_msg("unable to open seed file for writing");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200278 program_ret |= 1 << 4;
279 goto out;
280 }
281 if (write(fd, new_seed, new_seed_len) != (ssize_t)new_seed_len || fsync(fd) < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200282 bb_simple_perror_msg("unable to write seed file");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200283 program_ret |= 1 << 5;
284 goto out;
285 }
286 if (new_seed_creditable && rename(non_creditable_seed, creditable_seed) < 0) {
Jason A. Donenfeld45385782022-04-20 15:22:55 +0200287 bb_simple_perror_msg("unable to make new seed creditable");
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200288 program_ret |= 1 << 6;
289 }
290out:
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200291 if (ENABLE_FEATURE_CLEAN_UP && fd >= 0)
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200292 close(fd);
Jason A. Donenfeld31ec4812022-04-20 15:27:29 +0200293 if (ENABLE_FEATURE_CLEAN_UP && lock >= 0)
Jason A. Donenfeld4b407ba2022-04-04 18:21:51 +0200294 close(lock);
295 return program_ret;
296}