Skip to content

Commit

Permalink
Fixes #1298: use entropy pool to generate PRNG seed
Browse files Browse the repository at this point in the history
If entropy pool not available use a nano-second clock and process id
to generate the seed value.

(cherry picked from commit f25fffe)
  • Loading branch information
kgiusti committed Dec 18, 2023
1 parent 586f97e commit e72e399
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ target_link_libraries(skupper-router PUBLIC ${qpid_dispatch_LIBRARIES})

# check for various function availability
check_symbol_exists(getrlimit sys/resource.h QD_HAVE_GETRLIMIT)
check_symbol_exists(getrandom sys/random.h QD_HAVE_GETRANDOM)

# https://stackoverflow.com/questions/54771452/expanding-a-variable-cmakedefine-and-generator-expression-in-template-file
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/config.h.in" CONFIG_H_IN)
Expand Down
1 change: 1 addition & 0 deletions src/config.h.in
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@
#define QPID_DISPATCH_VERSION "${QPID_DISPATCH_VERSION}"
#define QPID_DISPATCH_HTTP_ROOT_DIR "${QPID_DISPATCH_HTML_DIR}"
#cmakedefine01 QD_HAVE_GETRLIMIT
#cmakedefine01 QD_HAVE_GETRANDOM
#endif // __src_config_h_in__
22 changes: 18 additions & 4 deletions src/dispatch.c
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#include <dlfcn.h>
#include <inttypes.h>
#include <stdlib.h>
#include <sys/random.h>

/**
* Private Function Prototypes
Expand Down Expand Up @@ -89,11 +90,24 @@ qd_dispatch_t *qd_dispatch(const char *python_pkgdir, bool test_hooks)
_test_hooks = test_hooks;

//
// Seed the random number generator
// Seed the random number generator. The router does not need crypto-grade randomness so a Pseudo-RNG is acceptable.
//
struct timeval time;
gettimeofday(&time, NULL);
srandom((unsigned int)time.tv_sec + ((unsigned int)time.tv_usec << 11));
unsigned int seed = 0;
#if QD_HAVE_GETRANDOM
while (getrandom(&seed, sizeof(seed), 0) == -1 && errno == EINTR) {
// EINTR will occur only if a signal arrives while blocking for
// the entropy pool to initialize. Non-fatal, try again.
}
#endif
if (seed == 0) { // getrandom() not supported
struct timespec tspec;
clock_gettime(CLOCK_MONOTONIC, &tspec);
// rotate lower (more random) bits to make them more significant
unsigned int timestamp = (unsigned int) (tspec.tv_sec + tspec.tv_nsec);
timestamp = (timestamp<<11) | (timestamp>>(sizeof(timestamp) * CHAR_BIT - 11));
seed = (unsigned int)(getpid() ^ timestamp);
}
srandom(seed);

qd = NEW(qd_dispatch_t);
ZERO(qd);
Expand Down

0 comments on commit e72e399

Please sign in to comment.