Random number seed on CF workers


We have a workers wasm that needs to generate a random number during starup. The number does not have to be secure in the crypto sense as it is only used as a random seed to our CSPRNG.

The code works locally but fails on CF workers platform where the generated seed is always 0 (zero). Further investigation shows the CF worker failing on srand (specifically time()) but not raising an exception and failing quietly. It seems to be related to 64-bit support in wasm.

We could use workers crypto api (getRandomValues) but the api is different from nodejs crypto api; we will prefer to avoid juggling this if possible. Furthermore, our random number package has siblings in Java, C, and lua where the generated sequence agree when started with the same seed in support of consistent test result.

So, what is your source of random data on the Workers platform? LavaRand does not qualify :smiley:
Thank you for your help.

I think https://drand.cloudflare.com/info
There was a function to retrieve a random from Cloudflare source.

Checked my notes and old code. fetch to https://csprng.xyz/ is one option

Time access in workers is extremely limited for security reasons as documented in https://developers.cloudflare.com/workers/runtime-apis/web-standards and discussed more at length in https://blog.cloudflare.com/mitigating-spectre-and-other-security-threats-the-cloudflare-workers-security-model/. Anyway, i see you are feeding in to a CSPRNG. This suggests that you want the numbers to be strongly unpredictable, which means the seed needs to be unpredictable. time() is not a good solution as the attacker has a pretty good idea of what time it is.

I would use the workers crypto API on workers and wrap it in a function that uses the appropriate function for the environment to seed your CSPRNG. You can implement whatever algorithm you need in your workers code.


Hmm @watson I never said I was feeding it to a CSPRNG - it was to be a one time seed to a CSPRNG. Please read request carefully.

I suggest you remove the solution check on your response because your response does not solve the problem. The response from @adaptive is better suited as a solution and should be the accepted solution.
Thank you.

1 Like

Hi @adaptive,

That works, and the latency is next to none.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.