-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathjitterentropy-rngd.c
More file actions
1447 lines (1230 loc) · 37.6 KB
/
Copy pathjitterentropy-rngd.c
File metadata and controls
1447 lines (1230 loc) · 37.6 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Non-physical true random number generator based on timing jitter.
*
* Copyright Stephan Mueller <smueller@chronox.de>, 2014 - 2026
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* ALTERNATIVELY, this product may be distributed under the terms of
* the GNU General Public License, in which case the provisions of the GPL are
* required INSTEAD OF the above restrictions. (This clause is
* necessary due to a potential bad interaction between the GPL and
* the restrictions contained in a BSD-style copyright.)
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <asm/types.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/utsname.h>
#include <getopt.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <syslog.h>
#include <linux/random.h>
#include <linux/version.h>
#include <signal.h>
#include "jitterentropy.h"
#define MAJVERSION 1 /* API / ABI incompatible changes, functional changes that
* require consumer to be updated (as long as this number
* is zero, the API is not considered stable and can
* change without a bump of the major version) */
#define MINVERSION 3 /* API compatible, ABI may change, functional
* enhancements only, consumer can be left unchanged if
* enhancements are not considered */
#define PATCHLEVEL 3 /* API / ABI compatible, no functional changes, no
* enhancements, bug fixes only */
static int Verbosity = 0;
static int force_sp80090b = 0;
static int status = 0;
/*
* When set, log messages are handed to syslog(3) instead of being printed to
* stdout. This is what makes logging useful for a backgrounded daemon at all:
* daemonize() redirects stdout and stderr to /dev/null, so without syslog
* every message is discarded once the daemon detaches.
*/
static int use_syslog = 0;
/*
* When set, the daemon does not detach from the invoking terminal. Whether the
* daemon forks is decided by this flag alone - it is deliberately independent
* of the log verbosity.
*/
static int foreground = 0;
/*
* When set, the daemon will exit on any error it encounters. The goal is that
* a wrapping monitor will pick up the errors and handle it as it sees fit, such
* as creating audit logs and possibly restart the daemon.
*
* The following errors are returned:
*
* * EOPNOTSUPP - the Jitter RNG triggered a fatal health test error
* * Errors reported by IOCTLs of RNDADDENTROPY and RNDRESEEDCRNG to /dev/random
* * Errors triggered by system calls including select(2), open(2), truncate(2),
* write(2), fork(2), as well as errors from library functions including
* lockf(3).
*/
static int exit_on_error = 0;
struct kernel_rng {
int fd;
struct rand_data *ec;
struct rand_pool_info *rpi;
const char *dev;
};
static struct kernel_rng Random = {
/*.fd = */ -1,
/*.ec = */ NULL,
/*.rpi = */ NULL,
/*.dev = */ "/dev/random"
};
/*
* handler for /dev/urandom not needed as used IOCTL alters input_pool
static struct kernel_rng Urandom = {
.fd = 0,
.ec = NULL,
.rpi = NULL,
.dev = "/dev/urandom"
};
*/
static int Pidfile_fd = -1;
/* "/var/run/jitterentropy-rngd.pid" */
static char *Pidfile = NULL;
static int Entropy_avail_fd = -1;
static int Entropy_thresh_fd = -1;
static unsigned int jent_flags = 0;
static unsigned int jent_osr = 1;
#define ENTROPYBYTES 32
#define OVERSAMPLINGFACTOR 2
/*
* Amount of data handed to the kernel in one RNDADDENTROPY operation, and thus
* the size of the payload buffer trailing struct rand_pool_info.
*
* This is the single definition of that quantity: the buffer that is allocated,
* the block of entropy that is gathered and the bound that is enforced before
* copying into the buffer all have to agree, so they all derive from here.
*/
#define RNDADDENTROPY_BUFSIZE (ENTROPYBYTES * OVERSAMPLINGFACTOR)
/* Total allocation size of struct rand_pool_info including its payload */
#define RNDADDENTROPY_ALLOCSIZE (sizeof(struct rand_pool_info) + \
RNDADDENTROPY_BUFSIZE)
/*
* After (force reseed wakeups), the installed alarm handler will unconditionally
* trigger a reseed irrespective of the seed level in two phases. This ensures
* that new seed is added after every (force reseed wakeups) * (alarm period).
* PHASE1: 120(force reseed wakeups) * 5(alarm period) == 600s
* PHASE2: 12(force reseed wakeups) * 50(alarm period) == 600s
*/
#define FORCE_RESEED_WAKEUPS_PHASE1 120
#define ALARM_PERIOD_PHASE1 5
#define FORCE_RESEED_WAKEUPS_PHASE2 12
#define ALARM_PERIOD_PHASE2 50
#define ENTROPYAVAIL "/proc/sys/kernel/random/entropy_avail"
#define ENTROPYTHRESH "/proc/sys/kernel/random/write_wakeup_threshold"
#define LRNG_FILE "/proc/lrng_type"
#define JENT_LOG_DEBUG 3
#define JENT_LOG_VERBOSE 2
#define JENT_LOG_WARN 1
#define JENT_LOG_ERR 0
static void install_alarm(unsigned int secs);
static void dealloc(void);
static int alloc(void);
static void dealloc_rng(struct kernel_rng *rng);
static void dolog(int severity, const char *fmt, ...)
__attribute__((format(printf, 2, 3)));
static unsigned long kern_maj = ULONG_MAX, kern_minor, kern_patchlevel;
static void jentrng_versionstring(char *buf, size_t buflen)
{
snprintf(buf, buflen, "jitterentropy-rngd %d.%d.%d",
MAJVERSION, MINVERSION, PATCHLEVEL);
}
/* Is the LRNG present instead of the legacy /dev/random? */
static int lrng_present(void)
{
struct stat buf;
static int lrng_present = -1;
if (lrng_present < 0) {
int ret = stat(LRNG_FILE, &buf);
if (ret == -1 && errno == ENOENT)
lrng_present = 0;
else
lrng_present = 1;
}
return lrng_present;
}
static int get_kernver(void)
{
struct utsname kernel;
char *saveptr = NULL;
char *res = NULL;
unsigned long maj, minor, patchlevel;
if (kern_maj != ULONG_MAX)
return 0;
if (uname(&kernel))
return -errno;
/*
* Parse into local variables and only publish them once all three
* components were obtained. Otherwise a partial parse would leave
* kern_maj set, which makes all subsequent calls report success while
* kern_minor / kern_patchlevel hold bogus values.
*/
/* 5.11.2 */
res = strtok_r(kernel.release, ".", &saveptr);
if (!res)
goto err;
maj = strtoul(res, NULL, 10);
res = strtok_r(NULL, ".", &saveptr);
if (!res)
goto err;
minor = strtoul(res, NULL, 10);
res = strtok_r(NULL, ".", &saveptr);
if (!res)
goto err;
patchlevel = strtoul(res, NULL, 10);
if (maj == ULONG_MAX)
goto err;
kern_maj = maj;
kern_minor = minor;
kern_patchlevel = patchlevel;
return 0;
err:
dolog(JENT_LOG_WARN, "Could not parse kernel version \"%s\"", kernel.release);
return -EFAULT;
}
/* return true if kernel is greater or equal to given values, otherwise false */
static int kernver_ge(unsigned int maj, unsigned int minor,
unsigned int patchlevel)
{
if (get_kernver())
return 0;
if (maj < kern_maj)
return 1;
if (maj == kern_maj) {
if (minor < kern_minor)
return 1;
if (minor == kern_minor) {
if (patchlevel <= kern_patchlevel)
return 1;
}
}
return 0;
}
static void usage(void)
{
unsigned int ver = jent_version();
char version[30];
memset(version, 0, sizeof(version));
jentrng_versionstring(version, sizeof(version));
fprintf(stderr, "\njitterentropy rngd feeding entropy to input_pool of Linux RNG\n");
fprintf(stderr, "Version %s\n\n", version);
fprintf(stderr, "Reported numeric version number of jent library %u\n\n", ver);
fprintf(stderr, "Usage:\n");
fprintf(stderr, "\t-h --help\tThis help information\n");
fprintf(stderr, "\t --version\tPrint version\n");
fprintf(stderr, "\t-v --verbose\tVerbose logging, multiple options increase verbosity\n");
fprintf(stderr, "\t-F --foreground\tDo not detach, keep running in the foreground\n");
fprintf(stderr, "\t-l --syslog\tLog to syslog instead of stdout - required to see\n");
fprintf(stderr, "\t\t\tany log output when the daemon detaches\n");
fprintf(stderr, "\t-p --pid\tWrite daemon PID to file\n");
fprintf(stderr, "\t-s --sp800-90b\tForce SP800-90B compliance\n");
fprintf(stderr, "\t-f --flags\tInteger with flags used to allocate Jitter RNG\n");
fprintf(stderr, "\t-o --osr\tInteger with OSR used to allocate Jitter RNG\n");
fprintf(stderr, "\t --status\tStatus information of the Jitter RNG - invoke with\n");
fprintf(stderr, "\t \tsame flags as used for runtime\n");
fprintf(stderr, "\t --exit-on-error\tCause the daemon to exit on errors\n");
fprintf(stderr, "\nLRNG presence %sdetected\n",
lrng_present() ? "" : "not ");
exit(1);
}
/* Convert a command line argument into an unsigned int or bail out */
static unsigned int parse_uint(const char *str)
{
char *endptr = NULL;
unsigned long val;
errno = 0;
val = strtoul(str, &endptr, 10);
/* Reject empty strings, trailing garbage and out-of-range values */
if (errno || endptr == str || *endptr != '\0')
usage();
#if ULONG_MAX > UINT_MAX
if (val > UINT_MAX)
usage();
#endif
return (unsigned int)val;
}
static void parse_opts(int argc, char *argv[])
{
int c = 0;
char version[30];
while (1) {
int opt_index = 0;
static struct option opts[] = {
{"verbose", 0, 0, 0},
{"pid", 1, 0, 0},
{"help", 0, 0, 0},
{"version", 0, 0, 0},
{"sp800-90b", 0, 0, 0},
{"flags", 1, 0, 0},
{"osr", 1, 0, 0},
{"status", 0, 0, 0},
{"exit-on-error", 0, 0, 0},
{"syslog", 0, 0, 0},
{"foreground", 0, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "svp:hf:o:lF", opts, &opt_index);
if (-1 == c)
break;
switch (c) {
case 0:
switch (opt_index) {
/* verbose */
case 0:
Verbosity++;
break;
/* pid */
case 1:
Pidfile = optarg;
break;
/* help */
case 2:
usage();
break;
/* version */
case 3:
jentrng_versionstring(version, sizeof(version));
fprintf(stderr, "Version %s\n", version);
fprintf(stderr, "Version Jitterentropy Core %u\n", jent_version());
exit(0);
break;
/* sp800-90b */
case 4:
force_sp80090b = 1;
break;
/* flags */
case 5:
jent_flags = parse_uint(optarg);
break;
/* osr */
case 6:
jent_osr = parse_uint(optarg);
break;
/* status */
case 7:
status = 1;
break;
/* exit-on-error */
case 8:
exit_on_error = 1;
break;
/* syslog */
case 9:
use_syslog = 1;
break;
/* foreground */
case 10:
foreground = 1;
break;
default:
usage();
}
break;
case 'v':
Verbosity++;
break;
case 'p':
Pidfile = optarg;
break;
case 'h':
usage();
break;
case 's':
force_sp80090b = 1;
break;
case 'l':
use_syslog = 1;
break;
case 'F':
foreground = 1;
break;
case 'f':
jent_flags = parse_uint(optarg);
break;
case 'o':
jent_osr = parse_uint(optarg);
break;
default:
usage();
}
}
}
/* ANSI SGR sequences used to colorize the log on a capable terminal */
#define COL_RESET "\033[0m"
#define COL_DIM "\033[2m"
#define COL_CYAN "\033[36m"
#define COL_YELLOW "\033[33m"
#define COL_RED "\033[1;31m"
static int use_color = 0;
/*
* Determine whether the log may carry ANSI escape sequences.
*
* Colors are only emitted when stdout is a terminal that is expected to
* interpret them. Writing escape sequences into a file or a pipe would corrupt
* the log for anything that later reads it, which is why this is detected
* rather than enabled unconditionally.
*
* This is re-evaluated after daemonize() redirects stdout to /dev/null.
*/
static void detect_color(void)
{
const char *term = getenv("TERM");
use_color = 0;
/* Escape sequences are meaningless unless a terminal reads them */
if (!isatty(STDOUT_FILENO))
return;
/* Honour the NO_COLOR convention, see https://no-color.org/ */
if (getenv("NO_COLOR"))
return;
/* A terminal that announces itself as incapable is taken at its word */
if (!term || !strcmp(term, "dumb"))
return;
use_color = 1;
}
/*
* Render the current wall clock time into buf.
*
* CLOCK_REALTIME is deliberate: the log is read alongside other system logs,
* so the entries have to carry the actual time of day rather than an offset
* from some arbitrary start point. Note this means the printed times follow
* adjustments of the system clock, which is the right trade-off for a log but
* makes them unsuitable for measuring intervals.
*
* Only the messages printed to stdout are stamped here - syslog records its
* own timestamp, so adding one there would just duplicate it.
*/
static void logtime(char *buf, size_t buflen)
{
struct timespec ts;
struct tm tm;
size_t len;
if (clock_gettime(CLOCK_REALTIME, &ts) || !localtime_r(&ts.tv_sec, &tm))
goto unknown;
len = strftime(buf, buflen, "%Y-%m-%d %H:%M:%S", &tm);
if (0 == len)
goto unknown;
/* Millisecond resolution keeps closely spaced events distinguishable */
snprintf(buf + len, buflen - len, ".%03ld", ts.tv_nsec / 1000000);
return;
unknown:
snprintf(buf, buflen, "<no timestamp>");
}
static void dolog(int severity, const char *fmt, ...)
{
va_list args;
char msg[1024];
const char *sev, *col;
char now[32];
if (severity <= Verbosity) {
int prio;
va_start(args, fmt);
vsnprintf(msg, sizeof(msg), fmt, args);
va_end(args);
switch (severity) {
case JENT_LOG_DEBUG:
sev = "Debug";
col = COL_DIM;
prio = LOG_DEBUG;
break;
case JENT_LOG_VERBOSE:
sev = "Verbose";
col = COL_CYAN;
prio = LOG_INFO;
break;
case JENT_LOG_WARN:
sev = "Warning";
col = COL_YELLOW;
prio = LOG_WARNING;
break;
case JENT_LOG_ERR:
sev = "Error";
col = COL_RED;
prio = LOG_ERR;
break;
default:
sev = "Unknown";
col = COL_RESET;
prio = LOG_NOTICE;
}
if (use_syslog) {
/*
* The identity and the priority already convey the
* program name and the severity, so only the bare
* message is handed over. The message is passed as an
* argument rather than as the format string so that a
* percent sign in it cannot be interpreted.
*/
syslog(prio, "%s", msg);
} else {
logtime(now, sizeof(now));
if (use_color) {
printf("[%s%s%s - jitterentropy-rngd - %s%s%s] %s\n",
COL_DIM, now, COL_RESET,
col, sev, COL_RESET, msg);
} else {
printf("[%s - jitterentropy-rngd - %s] %s\n",
now, sev, msg);
}
}
}
if (JENT_LOG_ERR == severity) {
dealloc();
exit(1);
}
}
static inline void memset_secure(void *s, int c, size_t n)
{
memset(s, c, n);
__asm__ __volatile__("" : : "r" (s) : "memory");
}
/*******************************************************************
* service manager notification
*******************************************************************/
/*
* Send a status notification to the service manager following the protocol
* documented in sd_notify(3): a single datagram written to the AF_UNIX socket
* named by the NOTIFY_SOCKET environment variable.
*
* The protocol is implemented directly rather than by linking against
* libsystemd. The daemon is started very early during boot, deliberately
* depends on almost nothing, and must keep building on systems without
* systemd - all of which a library dependency would work against.
*
* If NOTIFY_SOCKET is not set, no service manager is waiting for us and the
* call does nothing. Failures are logged but never fatal: not being able to
* talk to the service manager is no reason to stop delivering entropy.
*/
static void notify_service_manager(const char *state)
{
const char *socket_path = getenv("NOTIFY_SOCKET");
struct sockaddr_un addr;
size_t path_len;
int fd;
if (!socket_path)
return;
path_len = strlen(socket_path);
if (0 == path_len || path_len > sizeof(addr.sun_path)) {
dolog(JENT_LOG_WARN,
"NOTIFY_SOCKET holds an unusable path of %zu bytes",
path_len);
return;
}
fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (0 > fd) {
dolog(JENT_LOG_WARN, "Cannot create notification socket: %s",
strerror(errno));
return;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, socket_path, path_len);
/*
* A leading '@' denotes a socket in the abstract namespace, whose name
* begins with a NULL byte instead. The length passed to sendto(2) must
* then cover exactly the name, without a terminating NULL byte.
*/
if ('@' == addr.sun_path[0])
addr.sun_path[0] = '\0';
if (0 > sendto(fd, state, strlen(state), MSG_NOSIGNAL,
(struct sockaddr *)&addr,
(socklen_t)(offsetof(struct sockaddr_un, sun_path) +
path_len))) {
dolog(JENT_LOG_WARN, "Cannot notify service manager: %s",
strerror(errno));
} else {
dolog(JENT_LOG_DEBUG, "Notified service manager: %s", state);
}
close(fd);
}
/*
* Report readiness once. The daemon is only truly operational after it has
* seeded the kernel for the first time, so this is deliberately not called at
* startup - a service ordered after us can then rely on the kernel having been
* seeded by the time it runs.
*/
static void notify_ready(void)
{
static int notified = 0;
if (notified)
return;
notified = 1;
notify_service_manager("READY=1");
}
/*******************************************************************
* entropy handler functions
*******************************************************************/
static ssize_t write_random(struct kernel_rng *rng, char *buf, size_t len,
size_t entropy_bytes, int force_reseed)
{
ssize_t written = 0;
int ret;
if (len > SSIZE_MAX)
return -EOVERFLOW;
/*
* rpi->buf is allocated with exactly RNDADDENTROPY_BUFSIZE bytes -
* guard the memcpy below against a caller asking for more.
*/
if (len > RNDADDENTROPY_BUFSIZE) {
dolog(JENT_LOG_WARN, "Injection of %zu bytes requested, buffer holds only %u bytes",
len, (unsigned int)RNDADDENTROPY_BUFSIZE);
return -EOVERFLOW;
}
/* value is in bits */
rng->rpi->entropy_count = (entropy_bytes * 8);
rng->rpi->buf_size = len;
memcpy(rng->rpi->buf, buf, len);
ret = ioctl(rng->fd, RNDADDENTROPY, rng->rpi);
if (0 > ret) {
int errsv = errno;
dolog(JENT_LOG_WARN, "Error injecting entropy: %s", strerror(errsv));
return -errsv;
} else {
dolog(JENT_LOG_DEBUG, "Injected %zu bytes with an entropy count of %zu bytes of entropy",
len, entropy_bytes);
written = len;
}
rng->rpi->entropy_count = 0;
rng->rpi->buf_size = 0;
memset(rng->rpi->buf, 0, len);
/*
* The LRNG does not require this IOCTL as the reseed is automatically
* triggered.
*/
if (force_reseed && !lrng_present()) {
if (ioctl(rng->fd, RNDRESEEDCRNG) < 0) {
static int logged = 0;
written = -errno;
if (errno == EINVAL)
goto out;
if (!logged) {
dolog(JENT_LOG_WARN,
"Error triggering a reseed of the kernel DRNG: %s",
strerror(errno));
logged = 1;
}
} else {
dolog(JENT_LOG_DEBUG, "Reseeding of kernel DRNG triggered");
}
}
out:
return written;
}
static ssize_t read_jent(struct kernel_rng *rng, char *buf, size_t buflen)
{
ssize_t ret;
/*
*jent_read_entropy_safe implies a changing H_submitter which is not
* allowed in SP800-90B.
*/
if (force_sp80090b)
ret = jent_read_entropy(rng->ec, buf, buflen);
else
ret = jent_read_entropy_safe(&rng->ec, buf, buflen);
if (ret >= 0)
return ret;
dolog(JENT_LOG_WARN, "Cannot read entropy");
return -EOPNOTSUPP;
}
static ssize_t gather_entropy(struct kernel_rng *rng)
{
sigset_t blocking_set, previous_set;
/*
* Maximum numbers of blocks is determined by numbers of reseed IOCTLs: if
* the reseed IOCTL is used, we call ceil(256 / 80) numbers of IOCTLs. As
* each IOCTL may drain the entropy pool by 256 bits, we need to ensure that
* after the numbers of IOCTLs, we finally inject more blocks than the numbers
* of IOCTLs into the input_pool. Otherwise the entropy estimator will never
* rise and we encounter an endless loop.
*/
#define ENTBLOCKS (4 + 2 + 1)
char buf[(RNDADDENTROPY_BUFSIZE * ENTBLOCKS)];
ssize_t buflen = RNDADDENTROPY_BUFSIZE;
ssize_t ret = 0;
sigemptyset(&previous_set);
sigemptyset(&blocking_set);
sigaddset(&blocking_set, SIGALRM);
sigprocmask(SIG_BLOCK, &blocking_set, &previous_set);
if (lrng_present()) {
/*
* The LRNG operates fully 90B compliant, no special handling
* is necessary.
*/
ret = read_jent(rng, buf, buflen);
if (ret < 0)
goto out;
dolog(JENT_LOG_DEBUG, "LRNG: Inject %zd bits of data with %zd bits of entropy into BLAKE2s state",
buflen << 3, ret << 3);
/*
* Write the entropy, LRNG seeds automatically - the Jitter RNG
* provides full entropy so, we tell the Linux RNG the amount of
* entropy.
*/
ret = write_random(rng, buf, buflen, ret, 0);
} else {
if (!kernver_ge(5, 18, 0)) {
static int reported = 0;
if (!reported) {
dolog(JENT_LOG_WARN, "Kernel older than 5.18 detected - DRT.1 status unclear");
reported = 1;
}
}
/*
* AIS 20/31 DRT.1, no special handling is necessary.
*/
ret = read_jent(rng, buf, buflen);
if (ret < 0)
goto out;
dolog(JENT_LOG_DEBUG, "Linux kernel >= 5.18: Inject %zd bits of data with %zd bits of entropy into BLAKE2s state",
buflen << 3, ret << 3);
/*
* Write the entropy and trigger reseed - the Jitter RNG provides
* full entropy so, we tell the Linux RNG the amount of entropy.
*/
ret = write_random(rng, buf, buflen, ret, 1);
}
if (ret >= 0 && buflen != ret) {
dolog(JENT_LOG_WARN, "Injected %zd bytes into %s, expected %zd",
ret, rng->dev, buflen);
ret = 0;
}
out:
memset_secure(buf, 0, sizeof(buf));
if (exit_on_error && ret < 0) {
/* We now exit as requested by caller */
dealloc();
exit(-ret);
}
sigprocmask(SIG_SETMASK, &previous_set, NULL);
/*
* A full injection means the kernel has been seeded. Announcing
* readiness from here rather than from the startup path covers every
* caller: should the very first seeding attempt fail, the daemon stays
* alive and retries, and the service manager is told about the success
* whenever it eventually happens.
*/
if (ret > 0)
notify_ready();
return ret;
}
/*
* Number of times the Jitter RNG is torn down and re-initialized when the
* gathering of entropy reports an error.
*
* The retry has to be bounded: an error that does not heal (say, the
* RNDADDENTROPY IOCTL being rejected) would otherwise make the caller spin in
* a tight loop, burning a CPU indefinitely while re-allocating the entropy
* collector on every iteration.
*/
#define GATHER_RETRIES 5
static ssize_t gather_entropy_retry(struct kernel_rng *rng)
{
unsigned int i;
ssize_t written = gather_entropy(rng);
for (i = 0; written < 0 && i < GATHER_RETRIES; i++) {
int ret;
dolog(JENT_LOG_DEBUG, "Re-initializing rngd");
dealloc();
ret = alloc();
if (ret < 0) {
dolog(JENT_LOG_WARN,
"Re-initialization of rngd failed with %d", ret);
return ret;
}
written = gather_entropy(rng);
}
if (written < 0) {
struct timespec delay;
dolog(JENT_LOG_WARN,
"Gathering of entropy still failing after %u retries",
GATHER_RETRIES);
/*
* Back off before returning to the caller so that a permanent
* error does not translate into a hot loop.
*/
delay.tv_sec = 1;
delay.tv_nsec = 0;
nanosleep(&delay, NULL);
}
return written;
}
static int read_entropy_value(int fd)
{
ssize_t data = 0;
/* Room for the largest value ("4096") plus the trailing NULL byte */
char buf[8];
char *endptr = NULL;
long entropy = 0;
data = read(fd, buf, sizeof(buf) - 1);
lseek(fd, 0, SEEK_SET);
if (0 > data) {
dolog(JENT_LOG_WARN, "Error reading data from entropy fd: %s",
strerror(errno));
return 0;
}
if (0 == data) {
dolog(JENT_LOG_WARN, "Could not read data from entropy fd");
return 0;
}
/*
* read(2) does not NULL-terminate - do it here, as the conversion
* below would otherwise read beyond the buffer.
*/
buf[data] = '\0';
errno = 0;
entropy = strtol(buf, &endptr, 10);
if (errno || endptr == buf) {
dolog(JENT_LOG_WARN, "Cannot parse value read from entropy fd");
return 0;
}
if (0 > entropy || 4096 < entropy) {
dolog(JENT_LOG_WARN, "Entropy read from entropy fd (%ld) is outside of range",
entropy);
return 0;
}
return (int)entropy;
}
/*******************************************************************
* Signal handling functions
*******************************************************************/
/*
* Signal handlers must restrict themselves to the functions listed as
* async-signal-safe in POSIX.1 signal-safety(7). Writing a flag of type
* volatile sig_atomic_t is permitted, so the handlers below do nothing but
* that - the actual work is carried out by the process_*() counterparts
* invoked from the main loop in select_fd().
*
* The previous implementation performed the entire entropy gathering from
* within the handler, which calls printf(3), malloc(3) and free(3). Should
* such a signal arrive while the interrupted code holds the malloc arena lock
* or is in the middle of a stdio operation, the daemon deadlocks or corrupts
* its heap.
*/
static volatile sig_atomic_t Alarm_pending = 0;
static volatile sig_atomic_t Term_pending = 0;
static void sig_entropy_avail(int sig)
{
(void)sig;
Alarm_pending = 1;
}
/* terminate the daemon cleanly */
static void sig_term(int sig)
{
(void)sig;
Term_pending = 1;
}