paint-brush
Hack: How to Use SecureRandom with Kubernetes and Dockerby@TamasPolgar
4,159 reads
4,159 reads

Hack: How to Use SecureRandom with Kubernetes and Docker

by Tamas PolgarMarch 13th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<em>Cryptographically secure pseudo-random number generator depends on good entropy; however from </em><a href="https://hackernoon.com/tagged/docker" target="_blank"><em>Docker</em></a><em> containers we don’t always get this. This can cause the random generation be to block the execution of the application.</em>

Company Mentioned

Mention Thumbnail
featured image - Hack: How to Use SecureRandom with Kubernetes and Docker
Tamas Polgar HackerNoon profile picture

Cryptographically secure pseudo-random number generator depends on good entropy; however from Docker containers we don’t always get this. This can cause the random generation be to block the execution of the application.

Bone die found at Cantonment Clinch (1823–1834). (source: Kolby Kirk on Wikimedia Commons)

The Problem

I had a simple piece of Scala code generating random user ids by using java.security.SecureRandom.getInstanceStrong(). Something like:

It worked perfectly on local environment with the official O_penJDK_ docker image. However after deploying the application to Google Container Engine the application was just hanging, no exception thrown.

After some investigation I found the cause; /dev/random source is not gathering enough entropy in Google Container Engine environment.

Solution

In O_penJDK_ docker image (and most installations) the strong secure random algorithm is NativePRNGBlocking:SUN. This algorithm is using /dev/random source to get entropy, if there’s not enough entropy it blocks until enough entropy is gathered. On average this algorithm needs 21 seconds to generate a single random byte in my Google Container Engine cluster.

Other alternative to this source is /dev/urandom (“unlimited” random) source. This source uses a pool of entropy already gathered but it generates pseudorandom numbers if it runs out of entropy. It is still intended for most cryptographic purposes. See the sources below.

One option to use /dev/urandom as random source is to explicitly get NativePRNGNonBlocking SecureRandom instance instead of using the getInstanceStrong() method. After applying the following change my problem was fixed:

Sources

Thanks for reading, your comments are appreciated.