Replace Entropy with RAND_bytes

/dev/urandom is not an approved random number generator
for NIAP certification. Changing to use BoringSSL's
RAND_bytes(), which is approved.

Bug: 121272336
Test: Ran Keystore CTS tests against Walleye
Change-Id: I579d140ef56c90b477b0d8989e3b02375681aee8
diff --git a/keystore/Android.bp b/keystore/Android.bp
index 366f591..fd24979 100644
--- a/keystore/Android.bp
+++ b/keystore/Android.bp
@@ -26,7 +26,6 @@
         "auth_token_table.cpp",
         "blob.cpp",
         "confirmation_manager.cpp",
-        "entropy.cpp",
         "grant_store.cpp",
         "key_config.proto",
         "key_proto_handler.cpp",
diff --git a/keystore/KeyStore.cpp b/keystore/KeyStore.cpp
index ac3ab5f..6e8a4b2 100644
--- a/keystore/KeyStore.cpp
+++ b/keystore/KeyStore.cpp
@@ -49,10 +49,9 @@
 
 using android::String8;
 
-KeyStore::KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+KeyStore::KeyStore(const KeymasterDevices& kmDevices,
                    SecurityLevel minimalAllowedSecurityLevelForNewKeys)
-    : mEntropy(entropy),
-      mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE),
+    : mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE),
       mConfirmationManager(new ConfirmationManager(this)) {
     memset(&mMetaData, '\0', sizeof(mMetaData));
 
@@ -81,7 +80,7 @@
 
 ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->initialize(pw, mEntropy);
+    return userState->initialize(pw);
 }
 
 ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
@@ -92,12 +91,12 @@
 
 ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->writeMasterKey(pw, mEntropy);
+    return userState->writeMasterKey(pw);
 }
 
 ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->readMasterKey(pw, mEntropy);
+    return userState->readMasterKey(pw);
 }
 
 LockedKeyBlobEntry KeyStore::getLockedBlobEntryIfNotExists(const std::string& alias, uid_t uid) {
@@ -285,7 +284,7 @@
                            Blob characteristicsBlob) {
     auto userState = mUserStateDB.getUserStateByUid(blobfile->uid());
     return blobfile.writeBlobs(std::move(keyBlob), std::move(characteristicsBlob),
-                               userState->getEncryptionKey(), userState->getState(), mEntropy);
+                               userState->getEncryptionKey(), userState->getState());
 }
 
 ResponseCode KeyStore::del(const LockedKeyBlobEntry& blobfile) {
diff --git a/keystore/KeyStore.h b/keystore/KeyStore.h
index d2049a4..25ff3a5 100644
--- a/keystore/KeyStore.h
+++ b/keystore/KeyStore.h
@@ -75,7 +75,7 @@
 
 class KeyStore : public ::android::IBinder::DeathRecipient {
   public:
-    KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+    KeyStore(const KeymasterDevices& kmDevices,
              SecurityLevel minimalAllowedSecurityLevelForNewKeys);
     ~KeyStore();
 
@@ -148,7 +148,6 @@
     static const char* kMetaDataFile;
     static const android::String16 kRsaKeyType;
     static const android::String16 kEcKeyType;
-    Entropy* mEntropy;
 
     KeymasterWorkers mKmDevices;
 
diff --git a/keystore/blob.cpp b/keystore/blob.cpp
index f887e80..8633635 100644
--- a/keystore/blob.cpp
+++ b/keystore/blob.cpp
@@ -24,11 +24,11 @@
 #include <log/log.h>
 
 #include "blob.h"
-#include "entropy.h"
 
 #include "keystore_utils.h"
 
 #include <openssl/evp.h>
+#include <openssl/rand.h>
 
 #include <istream>
 #include <ostream>
@@ -296,7 +296,7 @@
 }
 
 static ResponseCode writeBlob(const std::string& filename, Blob blob, blobv3* rawBlob,
-                              const uint8_t* aes_key, State state, Entropy* entropy) {
+                              const uint8_t* aes_key, State state) {
     ALOGV("writing blob %s", filename.c_str());
 
     const size_t dataLength = rawBlob->length;
@@ -309,7 +309,7 @@
         }
 
         memset(rawBlob->initialization_vector, 0, AES_BLOCK_SIZE);
-        if (!entropy->generate_random_data(rawBlob->initialization_vector, kGcmIvSizeBytes)) {
+        if (!RAND_bytes(rawBlob->initialization_vector, kGcmIvSizeBytes)) {
             ALOGW("Could not read random data for: %s", filename.c_str());
             return ResponseCode::SYSTEM_ERROR;
         }
@@ -341,16 +341,14 @@
 }
 
 ResponseCode LockedKeyBlobEntry::writeBlobs(Blob keyBlob, Blob characteristicsBlob,
-                                            const uint8_t* aes_key, State state,
-                                            Entropy* entropy) const {
+                                            const uint8_t* aes_key, State state) const {
     if (entry_ == nullptr) {
         return ResponseCode::SYSTEM_ERROR;
     }
     ResponseCode rc;
     if (keyBlob) {
         blobv3* rawBlob = keyBlob.mBlob.get();
-        rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state,
-                       entropy);
+        rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state);
         if (rc != ResponseCode::NO_ERROR) {
             return rc;
         }
@@ -359,7 +357,7 @@
     if (characteristicsBlob) {
         blobv3* rawBlob = characteristicsBlob.mBlob.get();
         rc = writeBlob(entry_->getCharacteristicsBlobPath(), std::move(characteristicsBlob),
-                       rawBlob, aes_key, state, entropy);
+                       rawBlob, aes_key, state);
     }
     return rc;
 }
diff --git a/keystore/blob.h b/keystore/blob.h
index 92e4514..86f367f 100644
--- a/keystore/blob.h
+++ b/keystore/blob.h
@@ -89,7 +89,6 @@
     TYPE_KEY_CHARACTERISTICS_CACHE = 6,
 } BlobType;
 
-class Entropy;
 class LockedKeyBlobEntry;
 
 /**
@@ -263,7 +262,7 @@
              [](uid_t, const std::string&) -> bool { return true; });
 
     ResponseCode writeBlobs(Blob keyBlob, Blob characteristicsBlob, const uint8_t* aes_key,
-                            State state, Entropy* entorpy) const;
+                            State state) const;
     std::tuple<ResponseCode, Blob, Blob> readBlobs(const uint8_t* aes_key, State state) const;
     ResponseCode deleteBlobs() const;
 
diff --git a/keystore/entropy.cpp b/keystore/entropy.cpp
deleted file mode 100644
index 8d4d305..0000000
--- a/keystore/entropy.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "keystore"
-
-#include "entropy.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <log/log.h>
-
-#include "keystore_utils.h"
-
-Entropy::~Entropy() {
-    if (mRandom >= 0) {
-        close(mRandom);
-    }
-}
-
-bool Entropy::open() {
-    const char* randomDevice = "/dev/urandom";
-    mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
-    if (mRandom < 0) {
-        ALOGE("open: %s: %s", randomDevice, strerror(errno));
-        return false;
-    }
-    return true;
-}
-
-bool Entropy::generate_random_data(uint8_t* data, size_t size) const {
-    return (readFully(mRandom, data, size) == size);
-}
diff --git a/keystore/entropy.h b/keystore/entropy.h
deleted file mode 100644
index 0e4d1b2..0000000
--- a/keystore/entropy.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef KEYSTORE_ENTROPY_H_
-#define KEYSTORE_ENTROPY_H_
-
-#include <stdint.h>
-
-class Entropy {
-  public:
-    Entropy() : mRandom(-1) {}
-    ~Entropy();
-
-    bool open();
-    bool generate_random_data(uint8_t* data, size_t size) const;
-
-  private:
-    int mRandom;
-};
-
-#endif  // KEYSTORE_ENTROPY_H_
diff --git a/keystore/keystore_main.cpp b/keystore/keystore_main.cpp
index 409ac83..70f38cc 100644
--- a/keystore/keystore_main.cpp
+++ b/keystore/keystore_main.cpp
@@ -32,7 +32,6 @@
 #include <keystore/keystore_return_types.h>
 
 #include "KeyStore.h"
-#include "entropy.h"
 #include "key_store_service.h"
 #include "legacy_keymaster_device_wrapper.h"
 #include "permissions.h"
@@ -136,9 +135,6 @@
     CHECK(argc >= 2) << "A directory must be specified!";
     CHECK(chdir(argv[1]) != -1) << "chdir: " << argv[1] << ": " << strerror(errno);
 
-    Entropy entropy;
-    CHECK(entropy.open()) << "Failed to open entropy source.";
-
     auto kmDevices = initializeKeymasters();
 
     CHECK(kmDevices[SecurityLevel::SOFTWARE]) << "Missing software Keymaster device";
@@ -156,7 +152,7 @@
         halVersion.majorVersion >= 2 ? SecurityLevel::TRUSTED_ENVIRONMENT : SecurityLevel::SOFTWARE;
 
     android::sp<keystore::KeyStore> keyStore(
-        new keystore::KeyStore(&entropy, kmDevices, minimalAllowedSecurityLevelForNewKeys));
+        new keystore::KeyStore(kmDevices, minimalAllowedSecurityLevelForNewKeys));
     keyStore->initialize();
     android::sp<android::IServiceManager> sm = android::defaultServiceManager();
     android::sp<keystore::KeyStoreService> service = new keystore::KeyStoreService(keyStore);
diff --git a/keystore/user_state.cpp b/keystore/user_state.cpp
index c9a2d72..9fe1347 100644
--- a/keystore/user_state.cpp
+++ b/keystore/user_state.cpp
@@ -25,6 +25,7 @@
 #include <sys/stat.h>
 
 #include <openssl/evp.h>
+#include <openssl/rand.h>
 
 #include <log/log.h>
 
@@ -83,11 +84,11 @@
     return unlink(mMasterKeyEntry.getKeyBlobPath().c_str()) == 0 || errno == ENOENT;
 }
 
-ResponseCode UserState::initialize(const android::String8& pw, Entropy* entropy) {
-    if (!generateMasterKey(entropy)) {
+ResponseCode UserState::initialize(const android::String8& pw) {
+    if (!generateMasterKey()) {
         return ResponseCode::SYSTEM_ERROR;
     }
-    ResponseCode response = writeMasterKey(pw, entropy);
+    ResponseCode response = writeMasterKey(pw);
     if (response != ResponseCode::NO_ERROR) {
         return response;
     }
@@ -137,15 +138,15 @@
     return ResponseCode::NO_ERROR;
 }
 
-ResponseCode UserState::writeMasterKey(const android::String8& pw, Entropy* entropy) {
+ResponseCode UserState::writeMasterKey(const android::String8& pw) {
     uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
     generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
     Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
     auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
-    return lockedEntry.writeBlobs(masterKeyBlob, {}, passwordKey, STATE_NO_ERROR, entropy);
+    return lockedEntry.writeBlobs(masterKeyBlob, {}, passwordKey, STATE_NO_ERROR);
 }
 
-ResponseCode UserState::readMasterKey(const android::String8& pw, Entropy* entropy) {
+ResponseCode UserState::readMasterKey(const android::String8& pw) {
 
     auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
 
@@ -180,10 +181,10 @@
     if (response == ResponseCode::NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
         // If salt was missing, generate one and write a new master key file with the salt.
         if (salt == nullptr) {
-            if (!generateSalt(entropy)) {
+            if (!generateSalt()) {
                 return ResponseCode::SYSTEM_ERROR;
             }
-            response = writeMasterKey(pw, entropy);
+            response = writeMasterKey(pw);
         }
         if (response == ResponseCode::NO_ERROR) {
             memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
@@ -250,15 +251,15 @@
                            8192, keySize, key);
 }
 
-bool UserState::generateSalt(Entropy* entropy) {
-    return entropy->generate_random_data(mSalt, sizeof(mSalt));
+bool UserState::generateSalt() {
+    return RAND_bytes(mSalt, sizeof(mSalt));
 }
 
-bool UserState::generateMasterKey(Entropy* entropy) {
-    if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
+bool UserState::generateMasterKey() {
+    if (!RAND_bytes(mMasterKey, sizeof(mMasterKey))) {
         return false;
     }
-    if (!generateSalt(entropy)) {
+    if (!generateSalt()) {
         return false;
     }
     return true;
diff --git a/keystore/user_state.h b/keystore/user_state.h
index 365941e..6cac02a 100644
--- a/keystore/user_state.h
+++ b/keystore/user_state.h
@@ -26,7 +26,6 @@
 #include <keystore/keystore.h>
 
 #include "blob.h"
-#include "entropy.h"
 #include "keystore_utils.h"
 
 #include <android-base/logging.h>
@@ -60,12 +59,12 @@
     void zeroizeMasterKeysInMemory();
     bool deleteMasterKey();
 
-    ResponseCode initialize(const android::String8& pw, Entropy* entropy);
+    ResponseCode initialize(const android::String8& pw);
 
     ResponseCode copyMasterKey(LockedUserState<UserState>* src);
     ResponseCode copyMasterKeyFile(LockedUserState<UserState>* src);
-    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy);
-    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy);
+    ResponseCode writeMasterKey(const android::String8& pw);
+    ResponseCode readMasterKey(const android::String8& pw);
 
     const uint8_t* getEncryptionKey() const { return &mMasterKey[0]; }
 
@@ -83,8 +82,8 @@
 
     void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
                                  uint8_t* salt);
-    bool generateSalt(Entropy* entropy);
-    bool generateMasterKey(Entropy* entropy);
+    bool generateSalt();
+    bool generateMasterKey();
     void setupMasterKeys();
 
     KeyBlobEntry mMasterKeyEntry;