forked from sysprog21/lab0-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.c
293 lines (272 loc) · 8.8 KB
/
random.c
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
* Copyright (C) 2023 National Cheng Kung University, Taiwan.
* Copyright (c) 2017 Daan Sprenkels <[email protected]>
*
* 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.
*/
/* In the case that are compiling on linux, we need to define _GNU_SOURCE
* *before* random.h is included. Otherwise SYS_getrandom will not be declared.
*/
#if defined(__linux__) || defined(__GNU__)
#define _GNU_SOURCE
#endif
#include "random.h"
#if defined(__linux__) || defined(__GNU__)
/* We would need to include <linux/random.h>, but not every target has access
* to the linux headers. We only need RNDGETENTCNT, so we instead inline it.
* RNDGETENTCNT is originally defined in `include/uapi/linux/random.h` in the
* Linux kernel source.
*/
#define RNDGETENTCNT 0x80045200
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/ioctl.h>
#if (defined(__linux__) || defined(__GNU__)) && defined(__GLIBC__) && \
((__GLIBC__ > 2) || (__GLIBC_MINOR__ > 24))
#define USE_GLIBC
#include <sys/random.h>
#endif
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
/* We need SSIZE_MAX as the maximum read len from /dev/urandom */
#if !defined(SSIZE_MAX)
#include <bits/wordsize.h>
#if __WORDSIZE == 64
#define SSIZE_MAX LONG_MAX
#else
#define SSIZE_MAX INT_MAX
#endif
#endif
#endif /* defined(__linux__) || defined(__GNU__) */
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
/* Dragonfly, FreeBSD, NetBSD, OpenBSD (has arc4random) */
#include <sys/param.h>
#if defined(BSD)
#include <stdlib.h>
#endif
/* GNU/Hurd defines BSD in sys/param.h which causes problems later */
#if defined(__GNU__)
#undef BSD
#endif
#endif
#if (defined(__linux__) || defined(__GNU__)) && \
(defined(USE_GLIBC) || defined(SYS_getrandom))
#if defined(USE_GLIBC)
/* getrandom is declared in glibc. */
#elif defined(SYS_getrandom)
static ssize_t getrandom(void *buf, size_t buflen, unsigned int flags)
{
return syscall(SYS_getrandom, buf, buflen, flags);
}
#endif
static int linux_getrandom(void *buf, size_t n)
{
size_t offset = 0;
int ret;
while (n > 0) {
/* getrandom does not allow chunks larger than 33554431 */
size_t chunk = n <= 33554431 ? n : 33554431;
do {
ret = getrandom((char *) buf + offset, chunk, 0);
} while (ret == -1 && errno == EINTR);
if (ret < 0)
return ret;
offset += ret;
n -= ret;
}
assert(n == 0);
return 0;
}
#endif /* (defined(__linux__) || defined(__GNU__)) && (defined(USE_GLIBC) || \
defined(SYS_getrandom)) */
#if defined(__linux__) && !defined(SYS_getrandom)
#if defined(__linux__)
static inline int linux_read_entropy_ioctl(int device, int *entropy)
{
return ioctl(device, RNDGETENTCNT, entropy);
}
static int linux_read_entropy_proc(FILE *stream, int *entropy)
{
int retcode;
do {
rewind(stream);
retcode = fscanf(stream, "%d", entropy);
} while (retcode != 1 && errno == EINTR);
if (retcode != 1)
return -1;
return 0;
}
static int linux_wait_for_entropy(int device)
{
/* We will block on /dev/random, because any increase in the OS' entropy
* level will unblock the request. I use poll here (as does libsodium),
* because we don't *actually* want to read from the device.
*/
enum { IOCTL, PROC } strategy = IOCTL;
const int bits = 128;
FILE *proc_file;
int retcode_error = 0; /* Used as return codes */
int entropy = 0;
/* If the device has enough entropy already, we will want to return early */
int retcode = linux_read_entropy_ioctl(device, &entropy);
if (retcode != 0 && (errno == ENOTTY || errno == ENOSYS)) {
/* The ioctl call on /dev/urandom has failed due to a
* - ENOTTY (unsupported action), or
* - ENOSYS (invalid ioctl; this happens on MIPS).
*
* We will fall back to reading from
* /proc/sys/kernel/random/entropy_avail . This is less ideal,
* because it allocates a file descriptor, and it may not work
* in a chroot. But at this point it seems we have no better
* options left.
*/
strategy = PROC;
/* Open the entropy count file */
proc_file = fopen("/proc/sys/kernel/random/entropy_avail", "r");
if (!proc_file)
return -1;
} else if (retcode != 0) {
/* Unrecoverable ioctl error */
return -1;
}
if (entropy >= bits)
return 0;
int fd;
do {
fd = open("/dev/random", O_RDONLY);
} while (fd == -1 && errno == EINTR); /* EAGAIN will not occur */
if (fd == -1) {
/* Unrecoverable IO error */
return -1;
}
struct pollfd pfd = {.fd = fd, .events = POLLIN};
for (;;) {
retcode = poll(&pfd, 1, -1);
if (retcode == -1 && (errno == EINTR || errno == EAGAIN)) {
continue;
} else if (retcode == 1) {
if (strategy == IOCTL) {
retcode = linux_read_entropy_ioctl(device, &entropy);
} else if (strategy == PROC) {
retcode = linux_read_entropy_proc(proc_file, &entropy);
} else {
return -1; /* Unreachable */
}
if (retcode != 0) {
/* Unrecoverable I/O error */
retcode_error = retcode;
break;
}
if (entropy >= bits)
break;
} else {
/* Unreachable: poll() should only return -1 or 1 */
retcode_error = -1;
break;
}
}
do {
retcode = close(fd);
} while (retcode == -1 && errno == EINTR);
if (strategy == PROC) {
do {
retcode = fclose(proc_file);
} while (retcode == -1 && errno == EINTR);
}
if (retcode_error != 0)
return retcode_error;
return retcode;
}
#endif /* defined(__linux__) */
static int linux_urandom(void *buf, size_t n)
{
int fd;
do {
fd = open("/dev/urandom", O_RDONLY);
} while (fd == -1 && errno == EINTR);
if (fd == -1)
return -1;
#if defined(__linux__)
if (linux_wait_for_entropy(fd) == -1)
return -1;
#endif
size_t offset = 0;
while (n > 0) {
size_t count = n <= SSIZE_MAX ? n : SSIZE_MAX;
ssize_t tmp = read(fd, (char *) buf + offset, count);
if (tmp == -1 && (errno == EAGAIN || errno == EINTR))
continue;
if (tmp == -1)
return -1; /* Unrecoverable IO error */
offset += tmp;
n -= tmp;
}
close(fd);
assert(n == 0);
return 0;
}
#endif /* defined(__linux__) && !defined(SYS_getrandom) */
#if defined(BSD)
#if defined(__APPLE__)
#include <AvailabilityMacros.h>
#if defined(MAC_OS_X_VERSION_10_10) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_10
#include <CommonCrypto/CommonCryptoError.h>
#include <CommonCrypto/CommonRandom.h>
#endif
#endif
static int bsd_randombytes(void *buf, size_t n)
{
#if defined(MAC_OS_X_VERSION_10_15) && \
MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
/* We prefer CCRandomGenerateBytes as it returns an error code while
* arc4random_buf may fail silently on macOS.
*/
return (CCRandomGenerateBytes(buf, n) == kCCSuccess);
#else
arc4random_buf(buf, n);
return 0;
#endif
}
#endif
int randombytes(uint8_t *buf, size_t n)
{
#if defined(__linux__) || defined(__GNU__)
#if defined(USE_GLIBC)
/* Use getrandom system call */
return linux_getrandom(buf, n);
#elif defined(SYS_getrandom)
/* Use getrandom system call */
return linux_getrandom(buf, n);
#else
/* When we have enough entropy, we can read from /dev/urandom */
return linux_urandom(buf, n);
#endif
#elif defined(BSD)
return bsd_randombytes(buf, n);
#else
#error "randombytes(...) is not supported on this platform"
#endif
}