-
Notifications
You must be signed in to change notification settings - Fork 63
/
rngd.c
1288 lines (1129 loc) · 31.9 KB
/
rngd.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
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
/*
* rngd.c -- Random Number Generator daemon
*
* rngd reads data from a hardware random number generator, verifies it
* looks like random data, and adds it to /dev/random's entropy store.
*
* In theory, this should allow you to read very quickly from
* /dev/random; rngd also adds bytes to the entropy store periodically
* when it's full, which makes predicting the entropy store's contents
* harder.
*
* Copyright (C) 2001 Philipp Rumpf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*/
#define _GNU_SOURCE
#ifndef HAVE_CONFIG_H
#error Invalid or missing autoconf build environment
#endif
#include "rng-tools-config.h"
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <argp.h>
#include <syslog.h>
#include <signal.h>
#include <limits.h>
#include <ctype.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <sched.h>
#include "rngd.h"
#include "fips.h"
#include "exits.h"
#include "rngd_entsource.h"
#include "rngd_linux.h"
/*
* Globals
*/
int kent_pool_size;
/* Background/daemon mode */
bool am_daemon = false; /* True if we went daemon */
bool msg_squash = false; /* True if we want no messages on the console */
bool quiet = false; /* True if we want no console output at all */
volatile bool server_running = true; /* set to false, to stop daemon */
bool do_reseed = false; /* force a reseed event */
bool ignorefail = false; /* true if we ignore MAX_RNG_FAILURES */
/* Command line arguments and processing */
const char *rngd_program_version =
"rngd " VERSION "\n"
"Copyright 2001-2004 Jeff Garzik\n"
"Copyright 2017 Neil Horman\n"
"Copyright (c) 2001 by Philipp Rumpf\n"
"This is free software; see the source for copying conditions. There is NO "
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.";
const char *argp_program_bug_address = PACKAGE_BUGREPORT;
static char doc[] =
"Check and feed random data from hardware device to kernel entropy pool.\n";
static struct argp_option options[] = {
{ "debug", 'd', 0, 0, "Enable debug output" },
{ "foreground", 'f', 0, 0, "Do not fork and become a daemon" },
{ "ignorefail", 'i', 0, 0, "Ignore repeated fips failures" },
{ "background", 'b', 0, 0, "Become a daemon (default)" },
{ "exclude", 'x', "n", 0, "Disable the numbered entropy source specified" },
{ "include", 'n', "n", 0, "Enable the numbered entropy source specified" },
{ "list", 'l', 0, 0, "List the operational entropy sources on this system and exit" },
{ "option", 'O', "options", 0, "rng specific options in the form source:key:value"},
{ "random-device", 'o', "file", 0,
"Kernel device used for random number output (default: /dev/random)" },
{ "rng-device", 'r', "file", 0,
"Kernel device used for random number input (default: /dev/hwrng)" },
{ "test", 't', 0, 0, "Enter test mode and report entropy production rates" },
{ "pid-file", 'p', "file", 0,
"File used for recording daemon PID, and multiple exclusion (default: /var/run/rngd.pid)" },
{ "random-step", 's', "nnn", 0,
"Number of bytes written to random-device at a time (default: 64)" },
{ "fill-watermark", 'W', "n", 0,
"Do not stop feeding entropy to random-device until at least n bits of entropy are available in the pool (default: 3/4 of poolsize), 0 <= n <= 256" },
{ "quiet", 'q', 0, 0, "Suppress all messages" },
{ "version" ,'v', 0, 0, "List rngd version" },
{ "entropy-count", 'e', "n", 0, "Number of entropy bits to support (default: 8), 1 <= n <= 8" },
{ "force-reseed", 'R', "n", 0, "Time in seconds to force adding entropy to the random device" },
{ "use-slow-sources", 'u', 0, 0, "Always gather entropy from sources considered as \"slow\" too" },
{ "drop-privileges", 'D', "user:group", 0, "Drop privileges to a user and group specified" },
{ 0 },
};
static struct arguments default_arguments = {
.random_name = "/dev/random",
.pid_file = "/var/run/rngd.pid",
.random_step = 64,
.fill_watermark = -1,
.daemon = true,
.test = false,
.list = false,
.ignorefail = false,
.entropy_count = 8,
.force_reseed = 60 * 5,
.use_slow_sources = false,
.drop_privs = false,
};
struct arguments *arguments = &default_arguments;
static unsigned long ent_gathered = 0;
static unsigned long test_iterations = 0;
static double sum_entropy = 0;
static struct timespec start_test, end_test;
static bool test_running = false;
static enum {
ENT_HWRNG = 0,
ENT_TPM = 1,
ENT_RDRAND,
ENT_DARN,
ENT_RNDR,
ENT_NISTBEACON,
ENT_JITTER,
ENT_PKCS11,
ENT_RTLSDR,
ENT_QRYPT,
ENT_NAMEDPIPE,
ENT_MAX
} entropy_indexes __attribute__((used));
static struct rng_option drng_options[] = {
[DRNG_OPT_AES] = {
.key = "use_aes",
.type = VAL_INT,
.int_val = 0,
},
{
.key = NULL,
},
};
static struct rng_option darn_options[] = {
[DARN_OPT_AES] = {
.key = "use_aes",
.type = VAL_INT,
.int_val = 1,
},
{
.key = NULL,
}
};
static struct rng_option jitter_options[] = {
[JITTER_OPT_THREADS] = {
.key = "thread_count",
.type = VAL_INT,
.int_val = 4,
},
[JITTER_OPT_BUF_SZ] = {
.key = "buffer_size",
.type = VAL_INT,
.int_val = 16535,
},
[JITTER_OPT_REFILL] = {
.key = "refill_thresh",
.type = VAL_INT,
.int_val = 16535,
},
[JITTER_OPT_RETRY_COUNT] = {
.key = "retry_count",
.type = VAL_INT,
.int_val = 1,
},
[JITTER_OPT_RETRY_DELAY] = {
.key = "retry_delay",
.type = VAL_INT,
.int_val = -1,
},
[JITTER_OPT_USE_AES] = {
.key = "use_aes",
.type = VAL_INT,
.int_val = 1,
},
[JITTER_OPT_FORCE_INT_TIMER] = {
.key = "force_soft_timer",
.type = VAL_INT,
.int_val = 0,
},
[JITTER_OPT_TIMEOUT] = {
.key = "timeout",
.type = VAL_INT,
.int_val = 5,
},
{
.key = NULL,
}
};
#ifndef DEFAULT_PKCS11_ENGINE
#define DEFAULT_PKCS11_ENGINE "/usr/lib64/opensc-pkcs11.so"
#endif
static struct rng_option pkcs11_options[] = {
[PKCS11_OPT_ENGINE] = {
.key = "engine_path",
.type = VAL_STRING,
.str_val = DEFAULT_PKCS11_ENGINE,
},
[PKCS11_OPT_CHUNK] = {
.key = "chunk_size",
.type = VAL_INT,
.int_val = 1,
},
{
.key = NULL,
}
};
static struct rng_option nist_options[] = {
[NIST_OPT_USE_AES] = {
.key = "use_aes",
.type = VAL_INT,
.int_val = 1,
},
{
.key = NULL,
}
};
static struct rng_option rtlsdr_options[] = {
[RTLSDR_OPT_DEVID] = {
.key = "device_id",
.type = VAL_INT,
.int_val = 0,
},
[RTLSDR_OPT_FREQ_MIN] = {
.key = "freq_min",
.type = VAL_INT,
.int_val = 90000000,
},
[RTLSDR_OPT_FREQ_MAX] = {
.key = "freq_max",
.type = VAL_INT,
.int_val = 110000000,
},
[RTLSDR_OPT_SRATE_MIN] = {
.key = "sample_min",
.type = VAL_INT,
.int_val = 1000000,
},
[RTLSDR_OPT_SRATE_MAX] = {
.key = "sample_max",
.type = VAL_INT,
.int_val = 2800000,
},
{
.key = NULL,
}
};
static struct rng_option qrypt_options[] = {
[QRYPT_OPT_TOKEN_FILE] = {
.key = "tokenfile",
.type = VAL_STRING,
.str_val = "/etc/qrypt.token",
},
[QRYPT_OPT_MAX_ERROR_DELAY] {
.key = "delay",
.type = VAL_INT,
.int_val = 28800, /* 8 hours */
},
{
.key = NULL,
}
};
static struct rng_option namedpipe_options[] = {
[NAMEDPIPE_OPT_PATH] = {
.key = "path",
.type = VAL_STRING,
.str_val = "",
},
[NAMEDPIPE_OPT_TIMEOUT] {
.key = "timeout",
.type = VAL_INT,
.int_val = 5, /* 5 seconds */
},
{
.key = NULL,
}
};
static struct rng entropy_sources[ENT_MAX] = {
/* Note, the special char dev must be the first entry */
{
.rng_name = "Hardware RNG Device",
.rng_sname = "hwrng",
.rng_fname = "/dev/hwrng",
.rng_fd = -1,
.flags = { 0 },
.xread = xread,
.init = init_entropy_source,
.rng_options = NULL,
},
/* must be at index 1 */
{
.rng_name = "TPM RNG Device",
.rng_sname = "tpm",
.rng_fname = "/dev/tpm0",
.rng_fd = -1,
.flags = { 0 },
.xread = xread_tpm,
.init = init_tpm_entropy_source,
.rng_options = NULL,
.disabled = true,
},
{
.rng_name = "Intel RDRAND Instruction RNG",
.rng_sname = "rdrand",
.rng_fd = -1,
.flags = { 0 },
#ifdef HAVE_RDRAND
.xread = xread_drng,
.init = init_drng_entropy_source,
#else
.disabled = true,
#endif
.rng_options = drng_options,
},
{
.rng_name = "Power9 DARN Instruction RNG",
.rng_sname = "darn",
.rng_fd = -1,
.flags = { 0 },
#ifdef HAVE_DARN
.xread = xread_darn,
.init = init_darn_entropy_source,
#else
.disabled = true,
#endif
.rng_options = darn_options,
},
{
.rng_name = "ARM v8.5 RNDR Instruction RNG",
.rng_sname = "rndr",
.rng_fd = -1,
.flags = { 0 },
#ifdef HAVE_RNDR
.xread = xread_rndr,
.init = init_rndr_entropy_source,
#else
.disabled = true,
#endif
.rng_options = drng_options,
},
{
.rng_name = "NIST Network Entropy Beacon",
.rng_sname = "nist",
.rng_fd = -1,
.flags = {
.slow_source = 1,
.intermittent_source = 1,
},
#ifdef HAVE_NISTBEACON
.xread = xread_nist,
.init = init_nist_entropy_source,
#endif
.disabled = true,
.rng_options = nist_options,
},
{
.rng_name = "JITTER Entropy generator",
.rng_sname = "jitter",
.rng_fd = -1,
.flags = {
.slow_source = 1,
},
#ifdef HAVE_JITTER
.xread = xread_jitter,
.init = init_jitter_entropy_source,
.close = close_jitter_entropy_source,
#else
.disabled = true,
#endif
.rng_options = jitter_options,
},
{
.rng_name = "PKCS11 Entropy generator",
.rng_sname = "pkcs11",
.rng_fd = -1,
.flags = {
.slow_source = 1,
},
#ifdef HAVE_PKCS11
.xread = xread_pkcs11,
.init = init_pkcs11_entropy_source,
.close = close_pkcs11_entropy_source,
#else
.disabled = true,
#endif
.rng_options = pkcs11_options,
},
{
.rng_name = "RTLSDR software defined radio generator",
.rng_sname = "rtlsdr",
.rng_fd = -1,
.flags = { 0 },
#ifdef HAVE_RTLSDR
.xread = xread_rtlsdr,
.init = init_rtlsdr_entropy_source,
.close = close_rtlsdr_entropy_source,
#else
.disabled = true,
#endif
.rng_options = rtlsdr_options,
},
{
.rng_name = "Qrypt quantum entropy beacon",
.rng_sname = "qrypt",
.rng_fd = -1,
.flags = {
.intermittent_source = 1,
},
#ifdef HAVE_QRYPT
.xread = xread_qrypt,
.init = init_qrypt_entropy_source,
.close = close_qrypt_entropy_source,
#endif
.disabled = true,
.rng_options = qrypt_options,
},
{
.rng_name = "Named pipe entropy input",
.rng_sname = "namedpipe",
.rng_fd = -1,
.flags = { 0 },
.xread = xread_namedpipe,
.init = init_namedpipe_entropy_source,
.rng_options = namedpipe_options,
}
};
static int find_ent_src_idx_by_sname(const char *sname)
{
int i;
for (i = 0; i < ENT_MAX; i++) {
if (!strncmp(sname, entropy_sources[i].rng_sname,
strlen(entropy_sources[i].rng_sname)))
return i;
}
return -1;
}
static int find_ent_src_idx(const char *name_idx)
{
int idx;
if (isalpha(name_idx[0])) {
idx = find_ent_src_idx_by_sname(name_idx);
if (idx == -1) {
message(LOG_CONS|LOG_WARNING, "Unknown entropy source %s\n", name_idx);
return -EINVAL;
}
} else {
idx = strtoul(name_idx, NULL, 10);
if ((idx == LONG_MAX) || (idx >= ENT_MAX)) {
message(LOG_CONS|LOG_INFO, "option index out of range: %d\n", idx);
return -ERANGE;
}
message(LOG_CONS|LOG_INFO, "Note, reference of entropy sources by index "
"is deprecated, use entropy source short name instead\n");
}
return idx;
}
/*
* command line processing
*/
static error_t parse_opt (int key, char *arg, struct argp_state *state)
{
char *optkey;
long int idx;
long int val;
char *strval;
bool restore = false;
char *search, *last_search;
struct rng_option *options;
switch(key) {
case 'd':
arguments->debug = true;
break;
case 'o':
arguments->random_name = arg;
break;
case 'O':
search = strchrnul(arg, ':');
if (*search != '\0') {
*search = '\0';
restore = true;
}
idx = find_ent_src_idx(arg);
if (idx < 0)
return idx;
if (restore == true)
*search = ':';
if (*search == '\0') {
message(LOG_CONS|LOG_INFO, "Available options for %s (%s)\n",
entropy_sources[idx].rng_name, entropy_sources[idx].rng_sname);
options = entropy_sources[idx].rng_options;
while (options && options->key) {
if (options->type == VAL_INT)
message(LOG_CONS|LOG_INFO, "key: [%s]\tdefault value: [%d]\n", options->key, options->int_val);
else
message(LOG_CONS|LOG_INFO, "key: [%s]\tdefault value: [%s]\n", options->key, options->str_val);
options++;
}
return -ERANGE;
}
last_search = search = search + 1;
search = strchr(search, ':');
if (!search) {
message(LOG_CONS|LOG_ERR, "Options tuple not specified correctly\n");
return -EINVAL;
}
*search = '\0';
optkey = strdupa(last_search);
*search = ':';
last_search = search + 1;
strval = last_search;
val = strtoul(last_search, NULL, 10);
if (val == LONG_MAX) {
message(LOG_CONS|LOG_INFO, "rng option was not parsable\n");
return -ERANGE;
}
options = entropy_sources[idx].rng_options;
while (options && options->key) {
if (!strcmp(optkey, options->key)) {
if (options->type == VAL_INT)
options->int_val = val;
else
options->str_val = strdup(strval);
return 0;
}
options++;
}
message(LOG_CONS|LOG_INFO, "Option %s not found for source idx %ld\n", optkey, idx);
return -ERANGE;
break;
case 'x':
idx = find_ent_src_idx(arg);
if (idx < 0)
return idx;
entropy_sources[idx].disabled = true;
message(LOG_CONS|LOG_INFO, "Disabling %ld: %s (%s)\n", idx,
entropy_sources[idx].rng_name, entropy_sources[idx].rng_sname);
break;
case 'n':
idx = find_ent_src_idx(arg);
if (idx < 0)
return idx;
entropy_sources[idx].disabled = false;
message(LOG_CONS|LOG_INFO, "Enabling %ld: %s (%s)\n", idx,
entropy_sources[idx].rng_name, entropy_sources[idx].rng_sname);
break;
case 'l':
arguments->list = true;
break;
case 'p':
arguments->pid_file = arg;
break;
case 'r':
entropy_sources[ENT_HWRNG].rng_fname = arg;
break;
case 'f':
arguments->daemon = false;
break;
case 't':
arguments->daemon = false;
arguments->test = true;
break;
case 'b':
arguments->daemon = true;
break;
case 'i':
arguments->ignorefail = true;
break;
case 's':
if (sscanf(arg, "%i", &arguments->random_step) == 0)
argp_usage(state);
if (arguments->random_step > FIPS_RNG_BUFFER_SIZE || arguments->random_step < 0)
arguments->random_step = FIPS_RNG_BUFFER_SIZE;
break;
case 'W': {
int n;
if ((sscanf(arg, "%i", &n) == 0) || (n < 0) || (n > 256))
argp_usage(state);
else
arguments->fill_watermark = n;
break;
}
case 'q':
quiet = true;
break;
case 'v':
message(LOG_CONS|LOG_INFO, "%s\n", rngd_program_version);
exit(0);
break;
case 'e': {
int e;
if ((sscanf(arg,"%i", &e) == 0) || (e < 0) || (e > 8))
argp_usage(state);
else
arguments->entropy_count = e;
break;
}
case 'R': {
int R;
if ((sscanf(arg,"%i", &R) == 0) || (R < 0))
argp_usage(state);
else
arguments->force_reseed = R;
break;
}
case 'u': {
arguments->use_slow_sources = true;
break;
}
case 'D': {
struct passwd *usrent;
struct group *grpent;
char *endptr;
long int nuid, ngid;
search = strchr(arg, ':');
/* Check for corner cases */
if (search == NULL) {
message(LOG_CONS|LOG_ERR, "No colon found in user:group tuple\n");
return -EINVAL;
}
if (search == arg || search[1] == '\0') {
message(LOG_CONS|LOG_ERR, "No user or group name found in user:group tuple\n");
return -EINVAL;
}
*search = '\0';
/* Translate user argument into a user struct pointer.
* First, try to get it as specified. If that fails,
* try it as a number.
*/
usrent = getpwnam(arg);
if (usrent == NULL) {
/* Try as a number */
nuid = strtol(arg, &endptr, 10);
if (*endptr || !(usrent = getpwuid(nuid))) {
message(LOG_CONS|LOG_ERR, "User '%s' not found\n", arg);
*search = ':';
return -EINVAL;
}
}
*search = ':';
/* Do the same with a group name or number */
grpent = getgrnam(search + 1);
if (grpent == NULL) {
/* Try as a number */
ngid = strtol(search + 1, &endptr, 10);
if (*endptr || !(grpent = getgrgid(ngid))) {
message(LOG_CONS|LOG_ERR, "Group '%s' not found\n", search + 1);
return -EINVAL;
}
}
/* Found both user and group in a system */
arguments->drop_uid = usrent->pw_uid;
arguments->drop_gid = grpent->gr_gid;
arguments->drop_privs = true;
message(LOG_CONS|LOG_DEBUG, "Trying to drop privileges to %s(%d)/%s(%d)\n",
usrent->pw_name, usrent->pw_uid, grpent->gr_name, grpent->gr_gid);
break;
}
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = { options, parse_opt, NULL, doc };
static int update_kernel_random(int random_step)
{
unsigned char buf[FIPS_RNG_BUFFER_SIZE]; /* random_step was checked to be <= FIPS_RNG_BUFFER_SIZE */
int rc;
struct rng *iter;
message(LOG_DAEMON|LOG_DEBUG, "entropy successfully gathered, preparing it for the kernel\n");
while(true) {
if (!server_running)
return 0;
if (do_reseed) {
do_reseed = false;
alarm(arguments->force_reseed);
}
/* mix the sources on byte-level: ensure we always feed data from all available sources to the kernel
* helps to mitigate problems should a source not be as random as expected */
int p = 0;
while(p < random_step) {
int progress = p;
for (int i = 0; i < ENT_MAX; ++i) {
iter = &entropy_sources[i];
if (!iter->entropy_buf.valid)
continue;
buf[p++] = iter->entropy_buf.entropy[iter->entropy_buf.used_pos++];
if (iter->entropy_buf.used_pos == FIPS_RNG_BUFFER_SIZE)
iter->entropy_buf.valid = false;
if(p >= random_step)
break;
}
/* abort data preparation when no data was added to the buffer in one loop = no valid sources left
* this wastes a few bytes when FIPS_RNG_BUFFER_SIZE is not a multiple of random_step
* but it makes the logic easier to implement and read */
if (p == progress)
return 0;
}
rc = random_add_entropy(buf, random_step);
if (rc == -1) {
/* feeding the entropy to the kernel failed, not much we can do, wait and try again later */
random_sleep();
continue;
}
message(LOG_DAEMON|LOG_DEBUG, "Added %d/%d bits entropy\n", rc, kent_pool_size);
if (rc >= kent_pool_size-64) {
message(LOG_DAEMON|LOG_DEBUG, "Pool full at %d, sleeping!\n",
kent_pool_size);
random_sleep();
}
}
}
static int random_test_sink(int random_step)
{
struct rng *iter;
if (!ent_gathered)
alarm(1);
for (int i = 0; i < ENT_MAX; ++i) {
iter = &entropy_sources[i];
if (iter->entropy_buf.valid)
ent_gathered += FIPS_RNG_BUFFER_SIZE;
}
return 0;
}
static int drop_privileges(uid_t drop_uid, gid_t drop_gid)
{
cap_value_t ioctl_caps[1] = { CAP_SYS_ADMIN };
cap_t caps;
uid_t curr_uid = geteuid();
gid_t curr_gid = getegid(), supp_gid = drop_gid;
/* We need CAP_SYS_ADMIN capability to perform privileged
* ioctl(2) operations on the /dev/random device (see random(4)).
*/
if (!CAP_IS_SUPPORTED(CAP_SYS_ADMIN)) {
message(LOG_DAEMON|LOG_ERR, "Capability CAP_SYS_ADMIN is not present\n");
return 1;
}
/* We wish to retain the capabilities across the identity change,
* so we need to tell the kernel. See prctl(2).
*/
if (prctl(PR_SET_KEEPCAPS, 1L)) {
message(LOG_DAEMON|LOG_ERR, "Cannot keep capabilities after dropping privileges: %s\n",
strerror(errno));
return 1;
}
/* Actually try to drop privileges */
if (setgroups(1, &supp_gid)) {
message(LOG_DAEMON|LOG_ERR, "setgroups() failed: %s\n", strerror(errno));
return 1;
}
if (setresgid(drop_gid, drop_gid, drop_gid)) {
message(LOG_DAEMON|LOG_ERR, "setresgid() failed: %s\n", strerror(errno));
return 1;
}
if (setresuid(drop_uid, drop_uid, drop_uid)) {
message(LOG_DAEMON|LOG_ERR, "setresuid() failed: %s\n", strerror(errno));
return 1;
}
/* Drop all the capabilities except CAP_SYS_ADMIN. We can do this only
* if CAP_SYS_ADMIN is present in the PERMITTED subset initially.
*/
caps = cap_init();
if (caps == NULL) {
message(LOG_DAEMON|LOG_ERR, "cap_init() failed: %s\n", strerror(errno));
return 1;
}
/* We need CAP_SYS_ADMIN capability in the EFFECTIVE and PERMITTED subsets */
if (cap_set_flag(caps, CAP_PERMITTED, 1, ioctl_caps, CAP_SET) ||
cap_set_flag(caps, CAP_EFFECTIVE, 1, ioctl_caps, CAP_SET)) {
message(LOG_DAEMON|LOG_ERR, "Cannot manipulate capability data structure: %s\n",
strerror(errno));
cap_free(caps);
return 1;
}
/* Above, we just manipulated the data structure describing the flags,
* not the capabilities themselves. So, set those capabilities now.
*/
if (cap_set_proc(caps)) {
message(LOG_DAEMON|LOG_ERR, "Cannot set CAP_SYS_ADMIN capability: %s\n",
strerror(errno));
cap_free(caps);
return 1;
}
/* Free capabilities data */
if (cap_free(caps))
message(LOG_DAEMON|LOG_DEBUG, "cap_free() failed: %s\n", strerror(errno));
/* We can continue with this error */
/* Tell the kernel we do not want to retain the capability over
* any further identity changes (be paranoid)
*/
if (prctl(PR_SET_KEEPCAPS, 0L)) {
message(LOG_DAEMON|LOG_ERR, "prctl() failed: %s\n", strerror(errno));
return 1;
}
/* Be paranoid, verify that the changes were successful.
* Fail if current user or group is not ones to drop to
* or if older user or group can be obtained.
*/
if (curr_gid != drop_gid && (getegid() != drop_gid || setegid(curr_gid) >= 0)) {
message(LOG_DAEMON|LOG_ERR, "Group privileges drop was not successfull\n");
return 1;
}
if (curr_uid != drop_uid && (geteuid() != drop_uid || seteuid(curr_uid) >= 0)) {
message(LOG_DAEMON|LOG_ERR, "User privileges drop was not successfull\n");
return 1;
}
/* The same check for supplemental groups */
int ret = getgroups(1, &supp_gid);
if (ret < 0 || ret > 1 || (ret == 1 && supp_gid != drop_gid)) {
message(LOG_DAEMON|LOG_ERR, "Supplemental groups drop was not successfull\n");
return 1;
}
message(LOG_DAEMON|LOG_INFO, "Process privileges have been dropped to %d:%d\n",
geteuid(), getegid());
return 0;
}
static void do_loop(int random_step)
{
int buffers_filled;
int no_work;
bool work_done;
int sources_left;
int i;
int retval;
struct rng *iter;
bool try_slow_sources = false;
int (*random_add_fn)(int random_step);
random_add_fn = arguments->test ? random_test_sink : update_kernel_random;
continue_trying:
for (no_work = 0; no_work < 100; no_work = (work_done ? 0 : no_work+1)) {
work_done = false;
buffers_filled = 0;
/*
* Exclude slow sources when faster sources are working well
* sources like jitterentropy can provide some entropy when needed
* but can actually hinder performance when large amounts of entropy are needed
* owing to the fact that they may block while generating said entropy
* So, lets prioritize the faster sources. Start by only trying to collect
* entropy from the fast sources, then iff that fails, start including the slower
* sources as well. Once we get some entropy, return to only using fast sources
*/
if (no_work) {
message(LOG_DAEMON|LOG_DEBUG, "Couldn't get entropy in last loop, enabling slow sources\n");
try_slow_sources = true;
} else {
try_slow_sources = false;
}
for (i = 0; i < ENT_MAX; ++i) {
/*message(LOG_CONS|LOG_INFO, "I is %d\n", i);*/
iter = &entropy_sources[i];
/* empty the buffer for each source before gathering new entropy, even when some bytes are left */
iter->entropy_buf.valid = false;
iter->entropy_buf.used_pos = 0;
if (!try_slow_sources && !arguments->use_slow_sources && iter->flags.slow_source)
continue;
retry_same:
if (!server_running)
return;
if (iter->disabled)
continue; /* failed, no work */
message(LOG_DAEMON|LOG_DEBUG, "Reading entropy from %s\n", iter->rng_name);
retval = iter->xread(iter->entropy_buf.entropy, sizeof(iter->entropy_buf.entropy), iter);
if (retval)
continue; /* failed, no work */