3 * Acquisition of environmental noise (Unix-specific)
5 * (c) 1998 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
39 #include <sys/types.h>
50 #if defined(HAVE_LINUX_RANDOM_H)
51 # include <linux/random.h>
52 # include <sys/syscall.h>
55 #include <mLib/bits.h>
56 #include <mLib/mdup.h>
64 /*----- Magical numbers ---------------------------------------------------*/
66 #define NOISE_KIDLIFE 100000 /* @noise_filter@ child lifetime */
68 # define TIMESTRUCT timeval
69 # define tv_SEC tv_sec
70 # define tv_FRAC tv_usec
71 # define TIMERES 1000000
72 # define GETTIME(tv) (gettimeofday((tv), 0))
73 # define TOTIMEVAL(tv, xx) (*(tv) = *(xx))
75 /*----- Noise source definition -------------------------------------------*/
77 const rand_source noise_source
= { noise_acquire
, noise_timer
};
79 /*----- Static variables --------------------------------------------------*/
81 /* --- Timer differences --- */
83 static unsigned long noise_last
; /* Last time recorded */
84 static unsigned long noise_diff
; /* Last first order difference */
86 /* --- Setuid program handling --- */
88 static uid_t noise_uid
= NOISE_NOSETUID
; /* Uid to set to spawn processes */
89 static gid_t noise_gid
= NOISE_NOSETGID
; /* Gid to set to spawn processes */
91 /*----- Main code ---------------------------------------------------------*/
93 /* --- @bitcount@ --- *
95 * Arguments: @unsigned long x@ = a word containing bits
97 * Returns: The number of bits set in the word.
100 static int bitcount(unsigned long x
)
102 static const char ctab
[] = { 0, 1, 1, 2, 1, 2, 2, 3,
103 1, 2, 2, 3, 2, 3, 3, 4 };
106 count
+= ctab
[x
& 0xfu
];
114 * Arguments: @rand_pool *r@ = pointer to randomness pool
115 * @const struct TIMESTRUCT *tv@ = pointer to time block
117 * Returns: Nonzero if some randomness was contributed.
119 * Use: Low-level timer contributor.
122 static int timer(rand_pool
*r
, const struct TIMESTRUCT
*tv
)
124 unsigned long x
, d
, dd
;
128 x
= tv
->tv_FRAC
+ TIMERES
*tv
->tv_SEC
;
135 rand_add(r
, tv
, sizeof(*tv
), de
<= dde ? de
: dde
);
137 BURN(tv
); x
= d
= dd
= de
= dde
= 0;
141 /* --- @noise_timer@ --- *
143 * Arguments: @rand_pool *r@ = pointer to a randomness pool
145 * Returns: Nonzero if some randomness was contributed.
147 * Use: Contributes the current time to the randomness pool.
148 * A guess at the number of useful bits contributed is made,
149 * based on first and second order bit differences. This isn't
150 * ever-so reliable, but it's better than nothing.
153 int noise_timer(rand_pool
*r
)
155 struct TIMESTRUCT tv
;
156 GETTIME(&tv
); return (timer(r
, &tv
));
159 /* --- @noise_devrandom@ --- *
161 * Arguments: @rand_pool *r@ = pointer to a randomness pool
163 * Returns: Nonzero if some randomness was contributed.
165 * Use: Attempts to obtain some randomness from the system entropy
166 * pool. All bits from the device are assumed to be good.
169 int noise_devrandom(rand_pool
*r
)
172 octet buf
[RAND_POOLSZ
];
178 struct timeval tv
= { 0, 0 };
180 #ifdef HAVE_GETENTROPY
184 #if defined(HAVE_LINUX_RANDOM_H) && \
185 defined(GRND_NONBLOCK) && \
186 defined(SYS_getrandom)
187 /* --- Use the new shinies if available --- */
189 while (n
< sizeof(buf
)) {
190 if ((len
= syscall(SYS_getrandom
, buf
+ n
, sizeof(buf
) - n
,
191 GRND_NONBLOCK
)) <= 0) {
192 if (errno
== ENOSYS
) break;
197 if (n
== sizeof(buf
)) goto win
;
200 #ifdef HAVE_GETENTROPY
201 /* --- OpenBSD-flavoured shinies --- */
203 while (n
< sizeof(buf
)) {
204 nn
= sizeof(buf
) - nn
;
205 if (nn
> 256) nn
= 256;
206 if (getentropy(buf
+ n
, nn
)) break;
209 if (n
== sizeof(buf
)) goto win
;
213 /* --- Don't take from `/dev/urandom' if `/dev/random' would block --- */
215 if ((fd
= open("/dev/random", O_RDONLY
| O_NONBLOCK
)) < 0) goto done
;
218 if (select(fd
+ 1, &infd
, 0, 0, &tv
) < 0 || !FD_ISSET(fd
, &infd
))
223 /* --- Be nice to other clients of the random device --- *
225 * Attempt to open the device nonblockingly. If that works, take up to
226 * one bufferful and then close again. If there's no data to be read,
227 * then that's tough and we go away again, on the grounds that the device
228 * needs to get some more entropy from somewhere.
232 (fd
= open("/dev/urandom", O_RDONLY
| O_NONBLOCK
)) >= 0 ||
233 (fd
= open("/dev/arandom", O_RDONLY
| O_NONBLOCK
)) >= 0 ||
234 (fd
= open("/dev/random", O_RDONLY
| O_NONBLOCK
)) >= 0) {
235 while (n
< sizeof(buf
)) {
236 if ((len
= read(fd
, buf
+ n
, sizeof(buf
) - n
)) <= 0) break;
239 if (n
== sizeof(buf
)) goto win
;
246 if (fd
>= 0) close(fd
);
247 rand_add(r
, buf
, n
, 8*n
);
253 /* --- @noise_setid@ --- *
255 * Arguments: @uid_t uid@ = uid to set
256 * @gid_t gid@ = gid to set
260 * Use: Sets the user and group ids to be used by @noise_filter@
261 * when running child processes. This is useful to avoid
262 * giving shell commands (even carefully written ones) undue
263 * privileges. This interface is Unix-specific
266 void noise_setid(uid_t uid
, gid_t gid
)
272 /* --- @noise_filter@ --- *
274 * Arguments: @rand_pool *r@ = pointer to a randomness pool
275 * @int good@ = number of good bits per 1024 bits
276 * @const char *c@ = shell command to run
278 * Returns: Nonzero if some randomness was contributed.
280 * Use: Attempts to execute a shell command, and dump it into the
281 * randomness pool. A very rough estimate of the number of
282 * good bits is made, based on the size of the command's output.
283 * This function calls @waitpid@, so be careful. Before execing
284 * the command, the process uid and gid are set to the values
285 * given to @noise_setid@, and an attempt is made to reset the
286 * list of supplementary groups. The environment passed to
287 * the command has been severly lobotimized. If the command
288 * fails to complete within a short time period, it is killed.
289 * Paranoid use of close-on-exec flags for file descriptors is
292 * This interface is Unix-specific.
303 static void kid_read(int fd
, unsigned mode
, void *p
)
305 struct noisekid
*nk
= p
;
310 if ((sz
= read(fd
, nk
->buf
, sizeof(nk
->buf
))) <= 0)
313 goodbits
= (sz
* nk
->good
) / 128;
314 rand_add(nk
->r
, nk
->buf
, sz
, goodbits
);
319 static void kid_dead(struct timeval
*tv
, void *p
)
320 { struct noisekid
*nk
= p
; nk
->donep
= 1; }
322 int noise_filter(rand_pool
*r
, int good
, const char *c
)
327 struct TIMESTRUCT now
;
329 struct noisekid nk
= { 0 };
333 const char *env
[] = {
334 "PATH=/bin:/usr/bin:/sbin:/usr/sbin:/etc",
338 /* --- Remember when this business started --- */
340 GETTIME(&now
); timer(r
, &now
);
341 TOTIMEVAL(&dead
, &now
);
343 /* --- Create a pipe --- */
348 /* --- Fork a child off --- */
358 /* --- Handle the child end of the deal --- */
364 /* --- Set the pipe as standard output, close standard input --- */
366 if ((f
= open("/dev/null", O_RDONLY
)) < 0) _exit(127);
367 mfd
[i
].cur
= f
; mfd
[i
].want
= 0; i
++;
368 mfd
[i
].cur
= fd
[1]; mfd
[i
].want
= 1; i
++;
369 mfd
[i
].cur
= f
; mfd
[i
].want
= 2; i
++;
370 if (mdup(mfd
, i
)) _exit(127);
372 /* --- Play games with uids --- */
374 if (noise_gid
!= NOISE_NOSETGID
) {
377 #ifdef HAVE_SETGROUPS
378 setgroups(1, &noise_gid
);
382 if (noise_uid
!= NOISE_NOSETUID
) {
387 /* --- Start the process up --- */
389 execle("/bin/sh", "sh", "-c", c
, (char *)0, env
);
393 /* --- Sort out my end of the deal --- */
397 nk
.r
= r
; nk
.good
= good
;
398 TV_ADDL(&dead
, &dead
, 0, NOISE_KIDLIFE
);
399 sel_initfile(&sel
, &sf
, fd
[0], SEL_READ
, kid_read
, &nk
);
401 sel_addtimer(&sel
, &st
, &dead
, kid_dead
, &nk
);
402 while (!nk
.donep
&& !sel_select(&sel
));
404 /* --- We've finished with it: kill the child process --- *
406 * This is morally questionable. On the other hand, I don't want to be
407 * held up in the @waitpid@ call if I can possibly help it. Maybe a
408 * double-fork is worth doing here.
419 /* --- @noise_freewheel@ --- *
421 * Arguments: @rand_pool *r@ = pointer to a randomness pool
423 * Returns: Nonzero if some randomness was contributed.
425 * Use: Runs a free counter for a short while as a desparate attempt
426 * to get randomness from somewhere. This is actually quite
432 static sigjmp_buf fwjmp
;
434 static void fwalarm(int sig
)
436 siglongjmp(fwjmp
, 1);
439 int noise_freewheel(rand_pool
*r
)
441 void (*sigal
)(int) = 0;
442 struct itimerval oitv
, itv
= { { 0, 0 }, { 0, 5000 } };
444 volatile uint32 fwcount
= 0;
446 if (!sigsetjmp(fwjmp
, 1)) {
447 if ((sigal
= signal(SIGALRM
, fwalarm
)) == SIG_ERR
)
449 if (setitimer(ITIMER_REAL
, &itv
, &oitv
))
455 STORE32(buf
, fwcount
);
456 rand_add(r
, buf
, sizeof(buf
), 16);
461 signal(SIGALRM
, sigal
);
462 if (oitv
.it_value
.tv_sec
|| oitv
.it_value
.tv_usec
)
463 TV_SUB(&oitv
.it_value
, &oitv
.it_value
, &itv
.it_value
);
464 setitimer(ITIMER_REAL
, &oitv
, 0);
470 int noise_freewheel(rand_pool
*r
)
477 /* --- @noise_enquire@ --- *
479 * Arguments: @rand_pool *r@ = pointer to a randomness pool
481 * Returns: Nonzero if some randomness was contributed.
483 * Use: Runs some shell commands to enquire about the prevailing
484 * environment. This can gather quite a lot of low-quality
488 int noise_enquire(rand_pool
*r
)
494 { "ps alxww || ps -elf", 16 },
496 { "ifconfig -a", 8 },
499 { "ls -align /tmp/.", 10 },
504 for (i
= 0; tab
[i
].cmd
; i
++)
505 noise_filter(r
, tab
[i
].rate
, tab
[i
].cmd
);
509 /* --- @noise_acquire@ --- *
511 * Arguments: @rand_pool *r@ = pointer to a randomness pool
515 * Use: Acquires some randomness from somewhere.
518 void noise_acquire(rand_pool
*r
)
521 for (i
= 0; i
< 8; i
++)
523 if (!noise_devrandom(r
) || getenv("CATACOMB_FORCE_ESOTERIC_SOURCES")) {
525 for (i
= 0; i
< 8; i
++)
530 /*----- That's all, folks -------------------------------------------------*/