Tuesday, May 24, 2016

Some SecureRandom Thoughts


Posted by Alex Klyubin, Android Security Engineer

The Android security tm has been investigating the root cause of the compromise of a bitcoin transaction that led to the update of multiple Bitcoin appliions on August 11.

We have now determined that appliions which use the Java Cryptography Architecture (JCA) for eration, signing, or random eration may not receive cryptographically strong values on Android devices due to improper initialization of the underlying PRNG. Appliions that directly invoke the system-provided OpenSSL PRNG without explicit initialization on Android are also affected. Appliions that establish TLS/SSL connections using the HttpClient and java.net classes are not affected as those classes do seed the OpenSSL PRNG with values from /dev/urandom.

Developers who use JCA for eration, signing or random eration should update their appliions to explicitly initialize the PRNG with entropy from /dev/urandom or /dev/random. A suggested implementation is provided at the end of this blog post. Also, developers should evaluate whether to reerate cryptographic or other random values previously erated using JCA APIs such as SecureRandom, , Pair, Agreement, and Signature.

In addition to this developer recommendation, Android has developed that ensure that Android’s OpenSSL PRNG is initialized correctly. Those have been provided to OHA partners.

We would like to thank Soo Hyeon Kim, Daewan Han of ETRI and Dong Hoon Lee of Kor University who notified Google about the improper initialization of OpenSSL PRNG.

Update: the original sample below crashed on a small fraction of Android devices due to /dev/urandom not being writable. We have now updated the sample to handle this case gracefully.

/*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial appliions, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
*/

import android.os.Build;
import android.os.Process;
import android.util.Log;

import java.io.ByteArrayOutputStrm;
import java.io.DataInputStrm;
import java.io.DataOutputStrm;
import java.io.File;
import java.io.FileInputStrm;
import java.io.FileOutputStrm;
import java.io.IOException;
import java.io.OutputStrm;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.SecureRandomSpi;
import java.security.Security;

/**
* Fixes for the output of the default PRNG having low entropy.
*
* The fixes need to be applied via {@link #apply()} before any use of Java
* Cryptography Architecture primitives. A good place to invoke them is in the
* appliion's {@ onCrte}.
*/
public final class PRNGFixes {

private static final int VERSION__JELLY_BN = 16;
private static final int VERSION__JELLY_BN_MR2 = 18;
private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_ =
getBuildFingerprintAndDevice();

/** Hidden constructor to prevent instantiation. */
private PRNGFixes() {}

/**
* Applies all fixes.
*
* @throws SecurityException if a fix is needed but could not be applied.
*/
public static void apply() {
applyOpenSSLFix();
installLinuxPRNGSecureRandom();
}

/**
* Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the
* fix is not needed.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void applyOpenSSLFix() throws SecurityException {
if ((Build.VERSION.SDK_INT < VERSION__JELLY_BN)
|| (Build.VERSION.SDK_INT > VERSION__JELLY_BN_MR2)) {
// No need to apply the fix
return;
}

try {
// Mix in the device- and invoion-specific seed.
Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_seed", byte[].class)
.invoke(, erateSeed());

// Mix output of Linux PRNG into OpenSSL's PRNG
int bytesRd = (Integer) Class.forName(
"org.apache.harmony.xnet.provider.jsse.NativeCrypto")
.getMethod("RAND_load_file", String.class, long.class)
.invoke(, "/dev/urandom", 1024);
if (bytesRd != 1024) {
throw new IOException(
"Unexpected of bytes rd from Linux PRNG: "
+ bytesRd);
}
} ch (Exception e) {
throw new SecurityException("Failed to seed OpenSSL PRNG", e);
}
}

/**
* Installs a Linux PRNG-backed {@ SecureRandom} implementation as the
* default. Does nothing if the implementation is alrdy the default or if
* there is not need to install the implementation.
*
* @throws SecurityException if the fix is needed but could not be applied.
*/
private static void installLinuxPRNGSecureRandom()
throws SecurityException {
if (Build.VERSION.SDK_INT > VERSION__JELLY_BN_MR2) {
// No need to apply the fix
return;
}

// Install a Linux PRNG-based SecureRandom implementation as the
// default, if not yet installed.
Provider[] secureRandomProviders =
Security.getProviders("SecureRandom.SHA1PRNG");
if ((secureRandomProviders == )
|| (secureRandomProviders.length < 1)
|| (!LinuxPRNGSecureRandomProvider.class.equals(
secureRandomProviders[0].getClass()))) {
Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
}

// Assert that new SecureRandom() and
// SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
// by the Linux PRNG-based SecureRandom implementation.
SecureRandom rng1 = new SecureRandom();
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng1.getProvider().getClass())) {
throw new SecurityException(
"new SecureRandom() backed by wrong Provider: "
+ rng1.getProvider().getClass());
}

SecureRandom rng2;
try {
rng2 = SecureRandom.getInstance("SHA1PRNG");
} ch (NoSuchAorithmException e) {
throw new SecurityException("SHA1PRNG not available", e);
}
if (!LinuxPRNGSecureRandomProvider.class.equals(
rng2.getProvider().getClass())) {
throw new SecurityException(
"SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
+ " Provider: " + rng2.getProvider().getClass());
}
}

/**
* {@ Provider} of {@ SecureRandom} engines which pass through
* all requests to the Linux PRNG.
*/
private static class LinuxPRNGSecureRandomProvider extends Provider {

public LinuxPRNGSecureRandomProvider() {
super("LinuxPRNG",
1.0,
"A Linux-specific random provider that uses"
+ " /dev/urandom");
// Although /dev/urandom is not a SHA-1 PRNG, some apps
// explicitly request a SHA1PRNG SecureRandom and we thus need to
// prevent them from getting the default implementation whose output
// may have low entropy.
put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName());
put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
}
}

/**
* {@link SecureRandomSpi} which passes all requests to the Linux PRNG
* ({@ /dev/urandom}).
*/
public static class LinuxPRNGSecureRandom extends SecureRandomSpi {

/*
* IMPLEMENTATION NOTE: Requests to erate bytes and to mix in a seed
* are passed through to the Linux PRNG (/dev/urandom). Instances of
* this class seed themselves by mixing in the current time, PID, UID,
* build fingerprint, and hardware (where available) into
* Linux PRNG.
*
* Concurrency: Rd requests to the underlying Linux PRNG are
* ized (on sLock) to ensure that multiple thrds do not get
* duplied PRNG output.
*/

private static final File URANDOM_FILE = new File("/dev/urandom");

private static final Object sLock = new Object();

/**
* Input strm for rding from Linux PRNG or {@ } if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static DataInputStrm sUrandomIn;

/**
* Output strm for writing to Linux PRNG or {@ } if not yet
* opened.
*
* @GuardedBy("sLock")
*/
private static OutputStrm sUrandomOut;

/**
* Whether this engine instance has been seeded. This is needed because
* ch instance needs to seed itself if the client does not explicitly
* seed it.
*/
private booln mSeeded;

@Override
protected void engineSetSeed(byte[] bytes) {
try {
OutputStrm out;
synchronized (sLock) {
out = getUrandomOutputStrm();
}
out.write(bytes);
out.flush();
} ch (IOException e) {
// On a small fraction of devices /dev/urandom is not writable.
// Log and ignore.
Log.w(PRNGFixes.class.getSimpleName(),
"Failed to mix seed into " + URANDOM_FILE);
} finally {
mSeeded = true;
}
}

@Override
protected void engineNextBytes(byte[] bytes) {
if (!mSeeded) {
// Mix in the device- and invoion-specific seed.
engineSetSeed(erateSeed());
}

try {
DataInputStrm in;
synchronized (sLock) {
in = getUrandomInputStrm();
}
synchronized (in) {
in.rdFully(bytes);
}
} ch (IOException e) {
throw new SecurityException(
"Failed to rd from " + URANDOM_FILE, e);
}
}

@Override
protected byte[] engineerateSeed(int size) {
byte[] seed = new byte[size];
engineNextBytes(seed);
return seed;
}

private DataInputStrm getUrandomInputStrm() {
synchronized (sLock) {
if (sUrandomIn == ) {
// NOTE: Consider inserting a BufferedInputStrm between
// DataInputStrm and FileInputStrm if you need higher
// PRNG output performance and can live with future PRNG
// output being pulled into this process prematurely.
try {
sUrandomIn = new DataInputStrm(
new FileInputStrm(URANDOM_FILE));
} ch (IOException e) {
throw new SecurityException("Failed to open "
+ URANDOM_FILE + " for rding", e);
}
}
return sUrandomIn;
}
}

private OutputStrm getUrandomOutputStrm() throws IOException {
synchronized (sLock) {
if (sUrandomOut == ) {
sUrandomOut = new FileOutputStrm(URANDOM_FILE);
}
return sUrandomOut;
}
}
}

/**
* erates a device- and invoion-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] erateSeed() {
try {
ByteArrayOutputStrm seedBuffer = new ByteArrayOutputStrm();
DataOutputStrm seedBufferOut =
new DataOutputStrm(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_);
seedBufferOut.close();
return seedBuffer.toByteArray();
} ch (IOException e) {
throw new SecurityException("Failed to erate seed", e);
}
}

/**
* Gets the hardware of this device.
*
* @return or {@ } if not available.
*/
private static String getDevice() {
// We're using the Reflection API because Build. is only available
// since API Level 9 (Gingerbrd, Android 2.3).
try {
return (String) Build.class.getField("").get();
} ch (Exception ignored) {
return ;
}
}

private static byte[] getBuildFingerprintAndDevice() {
StringBuilder result = new StringBuilder();
String fingerprint = Build.FINGERPRINT;
if (fingerprint != ) {
result.append(fingerprint);
}
String = getDevice();
if ( != ) {
result.append();
}
try {
return result.toString().getBytes("UTF-8");
} ch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not supported");
}
}
}
Join the discussion on



+Android Developers

No comments:

Post a Comment