File: urandom.c

package info (click to toggle)
finit 4.14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,216 kB
  • sloc: ansic: 17,060; sh: 6,281; makefile: 532
file content (226 lines) | stat: -rw-r--r-- 4,986 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/* Setup and save random seed at boot/shutdown
 *
 * Copyright (c) 2012-2025  Joachim Wiberg <troglobit@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>		/* gettimeofday() */
#include <sys/types.h>
#include <sys/resource.h>	/* getrusage() */
#ifdef _LIBITE_LITE
# include <libite/lite.h>
#else
# include <lite/lite.h>
#endif
#include <linux/random.h>

#include "config.h"
#include "finit.h"
#include "helpers.h"
#include "plugin.h"
#include "conf.h"
#include "log.h"

#ifndef RANDOM_BYTES
#define RANDOM_BYTES (32*1024)
#endif

#ifdef RANDOMSEED
/*
 * This is the fallback seed function, please make sure you have drivers
 * enabling /dev/hwrng instead.
 */
static void fallback(FILE *fp)
{
	unsigned long seed;
	struct timeval tv;
	struct rusage ru;
	int iter = 128;

	gettimeofday(&tv, NULL);
	getrusage(RUSAGE_SELF, &ru);

	/* Mix multiple sources of "randomness" */
	seed = tv.tv_sec ^ (tv.tv_usec << 16);
	seed ^= ru.ru_utime.tv_sec ^ (ru.ru_utime.tv_usec << 16);
	seed ^= ru.ru_stime.tv_sec ^ (ru.ru_stime.tv_usec << 16);
	seed ^= getpid() << 8;

	srandom(seed);
	while (iter--) {
		uint32_t i, prng = random();

		for (i = 0; i < sizeof(prng); i++)
			fputc((prng >> (i * CHAR_BIT)) & UCHAR_MAX, fp);
	}
}
#endif

static void setup(void *arg)
{
#ifdef RANDOMSEED
	struct rand_pool_info *rpi;
	unsigned char *rpi_buf;
	ssize_t len = 0;
	struct stat st;
	int rc = -1;
	int fd, err;

	if (rescue) {
		dbg("Skipping %s plugin in rescue mode.", __FILE__);
		return;
	}

	if (stat(RANDOMSEED, &st) || st.st_size < 512) {
		int ret = 1;
		mode_t prev;
		FILE *fp;

		print_desc("Bootstrapping random seed", NULL);
		prev = umask(077);
		fp = fopen(RANDOMSEED, "w");
		if (fp) {
			const char *hwrng = "/dev/hwrng";
			FILE *hw;

			hw = fopen(hwrng, "r");
			if (hw) {
				char buf[512];
				size_t num;

				num = fread(buf, sizeof(buf[0]), sizeof(buf), hw);
				if (num == 0)
					fallback(fp);
				else
					fwrite(buf, sizeof(buf[0]), num, fp);

				fclose(hw);
			} else {
				fallback(fp);
			}
			ret = fclose(fp);
		}
		print_result(ret);
		umask(prev);
	}

	print_desc("Seeding random number generator", NULL);

	/*
	 * Simply copying our saved entropy to /dev/urandom doesn't
	 * increment the kernel "entropy count", instead we must use
	 * the ioctl below.
	 */
	fd = open(RANDOMSEED, O_RDONLY);
	if (fd < 0)
		goto fallback;

	rpi = malloc(sizeof(*rpi) + RANDOM_BYTES);
	if (!rpi) {
		close(fd);
		goto fallback;
	}

	rpi_buf = (unsigned char *)rpi->buf;
	do {
		ssize_t num;

		num = read(fd, &rpi_buf[len], RANDOM_BYTES - len);
		if (num <= 0) {
			if (num == -1 && errno == EINTR)
				continue;
			if (len > 0)
				break;

			close(fd);
			free(rpi);
			goto fallback;
		}

		len += num;
	} while (len < RANDOM_BYTES);
	close(fd);

	fd = open("/dev/urandom", O_WRONLY);
	if (fd < 0) {
		free(rpi);
		goto fallback;
	}

	rpi->buf_size = len;
	rpi->entropy_count = len * 8;
	rc = ioctl(fd, RNDADDENTROPY, rpi);
	err = errno;
	close(fd);
	free(rpi);
	if (rc < 0)
		logit(LOG_WARNING, "Failed adding entropy to kernel random pool: %s", strerror(err));
	print_result(rc < 0);
	return;
fallback:
	print_result(512 > copyfile(RANDOMSEED, "/dev/urandom", 0, 0));
#endif
}

static void save(void *arg)
{
#ifdef RANDOMSEED
	mode_t prev;

	if (rescue) {
		dbg("Skipping %s plugin in rescue mode.", __FILE__);
		return;
	}

	prev = umask(077);

	print_desc("Saving random seed", NULL);
	print_result(RANDOM_BYTES != copyfile("/dev/urandom", RANDOMSEED, RANDOM_BYTES, 0));

	umask(prev);
#endif
}

static plugin_t plugin = {
	.name = __FILE__,
	.hook[HOOK_BASEFS_UP] = { .cb  = setup },
	.hook[HOOK_SHUTDOWN]  = { .cb  = save  },
	.depends = { "bootmisc", }
};

PLUGIN_INIT(__init)
{
	plugin_register(&plugin);
}

PLUGIN_EXIT(__exit)
{
	plugin_unregister(&plugin);
}

/**
 * Local Variables:
 *  indent-tabs-mode: t
 *  c-file-style: "linux"
 * End:
 */