libwebsockets icon indicating copy to clipboard operation
libwebsockets copied to clipboard

There are performance issues in the function of lws_get_random

Open springflower321 opened this issue 3 months ago • 1 comments

The lws_get_random method has a performance issue in the line (size_t)read(context->fd_random, (char *)buf, len). It can be modified as follows:

unsigned int GetURandomSeed(unsigned char *seed, unsigned int seedLen)
{
unsigned int dataSize;
char filePath[] = "/dev/urandom";
char realFdPath[PATH_MAX] = {0};
if (realpath(filePath, realFdPath) == 0) {
return 1;
}
int fd = open(realFdPath, O_RDONLY);
if (fd < 0) {
return 1;
}
dataSize = (unsigned int)read(fd, seed, seedLen);
if (dataSize!= seedLen) {
(void)close(fd);
return 1;
}
(void)close(fd);
return 0;
}
void SetGenerateRandomSeed(void)
{
static unsigned long cnt = 0;
const unsigned long seedMax = 1UL << 48;
if (cnt % seedMax == 0) {
unsigned char seed[MIN_RAND_SEED_NUM] = {0};
if (GetURandomSeed(seed, sizeof(seed))!= 0) {
return;
}
RAND_seed(seed, sizeof(seed));
cnt = 0;
}
cnt++;
}

unsigned int SysGenerateRandom(size_t len, void *pucRandNumbuf)
{
    SetGenerateRandomSeed();
    if (RAND_priv_bytes(pucRandNumbuf, (int)len) == 1) {
        return 0;
    }

    return (GetURandomSeed(pucRandNumbuf, (unsigned int)len) == 0 ? 0 : 1);
}

springflower321 avatar Oct 08 '25 09:10 springflower321

  1. What does it mean "performance issue"?

  2. It might have a "performance issue" on your platform. You can just use a different RNG and not the lws api?

  3. If "performace issue" means even for lws internal uses you can't find enough entropy, there are other steps you can take such as run rngd, see https://archive.is/75VCm you can also wire up your SoC HWRNG to feed it.

  4. Where did these magic imports RAND_priv_bytes() come from? I am pretty sure normal humans don't have that lying around.

  5. If you want a PRNG there's a seedable very high speed one in lws_xos already (build with LWS_WITH_SYS_FAULT_INJECTION)

lws-team avatar Oct 08 '25 11:10 lws-team