exo2: implement GenerateRandomBytes

This commit is contained in:
Michael Scire
2020-05-15 03:23:31 -07:00
committed by SciresM
parent 6bf283ec2e
commit fa64bf4951
6 changed files with 101 additions and 7 deletions

View File

@@ -16,17 +16,69 @@
#include <exosphere.hpp>
#include "../secmon_error.hpp"
#include "secmon_smc_random.hpp"
#include "secmon_random_cache.hpp"
#include "secmon_smc_se_lock.hpp"
namespace ams::secmon::smc {
namespace {
SmcResult GenerateRandomBytesImpl(SmcArguments &args) {
/* Validate the input size. */
const size_t size = args.r[1];
if (size > MaxRandomBytes) {
return SmcResult::InvalidArgument;
}
/* Create a buffer that the se can generate bytes into. */
util::AlignedBuffer<hw::DataCacheLineSize, MaxRandomBytes> buffer;
hw::FlushDataCache(buffer, size);
hw::DataSynchronizationBarrierInnerShareable();
/* Generate random bytes into the buffer. */
se::GenerateRandomBytes(buffer, size);
/* Ensure that the cpu sees consistent data. */
hw::DataSynchronizationBarrierInnerShareable();
hw::FlushDataCache(buffer, size);
hw::DataSynchronizationBarrierInnerShareable();
/* Copy the bytes to output. */
std::memcpy(std::addressof(args.r[1]), buffer, size);
return SmcResult::Success;
}
}
SmcResult SmcGenerateRandomBytes(SmcArguments &args) {
/* TODO */
return SmcResult::NotImplemented;
return LockSecurityEngineAndInvoke(args, GenerateRandomBytesImpl);
}
SmcResult SmcGenerateRandomBytesNonBlocking(SmcArguments &args) {
/* TODO */
return SmcResult::NotImplemented;
/* Try to lock the security engine, so that we can call the standard impl. */
if (TryLockSecurityEngine()) {
/* Ensure we unlock the security engine when done. */
ON_SCOPE_EXIT { UnlockSecurityEngine(); };
/* Take advantage of our lock to refill lthe random cache. */
ON_SCOPE_EXIT { RefillRandomCache(); };
/* If we lock it successfully, we can just call the blocking impl. */
return GenerateRandomBytesImpl(args);
} else {
/* Otherwise, we'll retrieve some bytes from the cache. */
const size_t size = args.r[1];
/* Validate the input size. */
if (size > MaxRandomBytes) {
return SmcResult::InvalidArgument;
}
/* Get random bytes from the cache. */
GetRandomFromCache(std::addressof(args.r[1]), size);
return SmcResult::Success;
}
}
}