AuroraRuntime/Source/RNG/RNG.cpp
Reece cf70f0d45c [*/+/-] MEGA COMMIT. ~2 weeks compressed.
The intention is to quickly improve and add util apis, enhance functionality given current demands, go back to the build pipeline, finish that, publish runtime tests, and then use what we have to go back to to linux support with a more stable api.

[+] AuMakeSharedArray
[+] Technet ArgvQuote
[+] Grug subsystem (UNIX signal thread async safe ipc + telemetry flusher + log flusher.)
[+] auEndianness -> Endian swap utils
[+] AuGet<N>(...)
[*] AUE_DEFINE conversion for
        ECompresionType, EAnsiColor, EHashType, EStreamError, EHexDump
[+] ConsoleMessage ByteBuffer serialization
[+] CmdLine subsystem for parsing command line arguments and simple switch/flag checks
[*] Split logger from console subsystem
[+] StartupParameters -> A part of a clean up effort under Process
[*] Refactor SysErrors header + get caller hack
[+] Atomic APIs
[+] popcnt
[+] Ring Buffer sink
[+] Added more standard errors
        Catch,
        Submission,
        LockError,
        NoAccess,
        ResourceMissing,
        ResourceLocked,
        MalformedData,
        InSandboxContext,
        ParseError

[+] Added ErrorCategorySet, ErrorCategoryClear, GetStackTrace
[+] IExitSubscriber, ETriggerLevel
[*] Write bias the high performance RWLockImpl read-lock operation operation
[+] ExitHandlerAdd/ExitHandlerRemove (exit subsystem)
[*] Updated API style
        Digests
[+] CpuId::CpuBitCount
[+] GetUserProgramsFolder
[+] GetPackagePath
[*] Split IStreamReader with an inl file
[*] BlobWriter/BlobReader/BlobArbitraryReader can now take shared pointers to bytebuffers. default constructor allocates a new scalable bytebuffer
[+] ICharacterProvider
[+] ICharacterProviderEx
[+] IBufferedCharacterConsumer
[+] ProviderFromSharedString
[+] ProviderFromString
[+] BufferConsumerFromProvider
[*] Parse Subsystem uses character io bufferer
[*] Rewritten NT's high perf semaphore to use userland SRW/ConVars [like mutex, based on generic semaphore]
[+] ByteBuffer::ResetReadPointer
[*] Bug fix bytebuffer base not reset on free and some scaling issues
[+] ProcessMap -> Added kSectionNameStack, kSectionNameFile, kSectionNameHeap for Section
[*] ProcessMap -> Refactor Segment to Section. I was stupid for keeping a type conflict hack API facing
[+] Added 64 *byte* fast RNG seeds
[+] File Advisorys/File Lock Awareness
[+] Added extended IAuroraThread from OS identifier caches for debug purposes
[*] Tweaked how memory is reported on Windows. Better consistency of what values mean across functions.
[*] Broke AuroraUtils/Typedefs out into a separate library
[*] Update build script
[+] Put some more effort into adding detail to the readme before rewriting it, plus, added some media
[*] Improved public API documentation
[*] Bug fix `SetConsoleCtrlHandler`
[+] Locale TimeDateToFileNameISO8601
[+] Console config stdOutShortTime
[*] Begin using internal UTF8/16 decoders when platform support isnt available (instead of stl)
[*] Bug fixes in decoders
[*] Major bug fix, AuMax
[+] RateLimiter
[+] Binary file sink
[+] Log directory sink
[*] Data header usability (more operators)
[+] AuRemoveRange
[+] AuRemove
[+] AuTryRemove
[+] AuTryRemoveRange
[+] auCastUtils
[+] Finish NewLSWin32Source
[+] AuTryFindByTupleN, AuTryRemoveByTupleN
[+] Separated AuRead/Write types, now in auTypeUtils
[+] Added GetPosition/SetPosition to FileWriter
[*] Fix stupid AuMin in place of AuMax in SpawnThread.Unix.Cpp
[*] Refactored Arbitrary readers to SeekingReaders (as in, they could be atomic and/or parallelized, and accept an arbitrary position as a work parameter -> not Seekable, as in, you can simply set the position)
[*] Hack back in the sched deinit
[+] File AIO loop source interop
[+] Begin to prototype a LoopQueue object I had in mind for NT, untested btw
[+] Stub code for networking
[+] Compression BaseStream/IngestableStreamBase
[*] Major: read/write locks now support write-entrant read routines.
[*] Compression subsystem now uses the MemoryView concept
[*] Rewrite the base stream compressions, made them less broken
[*] Update hashing api
[*] WriterTryGoForward and ReaderTryGoForward now revert to the previous relative index instead of panicing
[+] Added new AuByteBuffer apis
    Trim, Pad, WriteFrom, WriteString, [TODO: ReadString]
[+] Added ByteBufferPushReadState
[+] Added ByteBufferPushWriteState
[*] Move from USC-16 to full UTF-16. Win32 can handle full UTF-16.
[*] ELogLevel is now an Aurora enum
[+] Raised arbitrary limit in header to 255, the max filter buffer
[+] Explicit GZip support
[+] Explicit Zip support
[+] Added [some] compressors

et al
2022-02-17 00:11:40 +00:00

284 lines
6.3 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: RNG.cpp
Date: 2021-6-11
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "RNG.hpp"
#if defined(AURORA_PLATFORM_WIN32)
#include <wincrypt.h>
#include <bcrypt.h>
#elif defined(AURORA_IS_MODERNNT_DERIVED)
#include <bcrypt.h>
#undef USE_OLD_NTCRYPT
#endif
#if defined(AURORA_IS_POSIX_DERIVED)
#include <cstdio>
#endif
#include "WELL.hpp"
namespace Aurora::RNG
{
static WELLRand gWellRand;
static RandomUnique_t gFastDevice;
#if defined(AURORA_IS_POSIX_DERIVED)
static FILE *gDevURand;
static void InitRandPlatform()
{
gDevURand = fopen("/dev/urandom", "rb");
if (gDevURand == NULL)
{
gDevURand = fopen("/dev/random", "rb");
}
if (!gDevURand)
{
return;
}
if (setvbuf(gDevURand, NULL, _IONBF, 0) != 0)
{
#if 0
fclose(gDevURand);
gDevURand = NULL;
#endif
}
}
static AuUInt32 RngUnix(AuUInt8 *buf, AuUInt32 len)
{
return fread(buf, 1, (size_t)len, gDevURand);
}
#elif defined(AURORA_IS_MODERNNT_DERIVED)
#if defined(USE_OLD_NTCRYPT)
static HCRYPTPROV gCryptoProv;
#endif
static void InitRandPlatform()
{
#if defined(USE_OLD_NTCRYPT)
if (!CryptAcquireContext(&gCryptoProv, NULL, MS_DEF_PROV, PROV_RSA_FULL,
(CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET)))
{
if (!CryptAcquireContext(&gCryptoProv, NULL, MS_DEF_PROV, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET))
{
gCryptoProv = 0;
}
}
#endif
}
static AuUInt32 RngWin32(AuUInt8 *buf, AuUInt32 len)
{
#if defined(USE_OLD_NTCRYPT)
if (!gCryptoProv)
{
return 0;
}
if (!CryptGenRandom(gCryptoProv, len, buf))
{
return 0;
}
return len;
#else
#if !defined(AURORA_DONT_PREFER_WIN32_USERLAND_AES_RNG)
if (BCryptGenRandom(BCRYPT_RNG_ALG_HANDLE, reinterpret_cast<PUCHAR>(buf), len, 0) == 0)
{
return len;
}
#endif
if (BCryptGenRandom(NULL, reinterpret_cast<PUCHAR>(buf), len, BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0)
{
return len;
}
return 0;
#endif
}
#else
static void InitRandPlatform()
{
}
#endif
static AuUInt32 RngStdC(AuUInt8 *buf, AuUInt32 len)
{
clock_t t1;
int l, acc, bits, a, b;
l = len;
acc = a = b = 0;
bits = 8;
while (len--)
{
while (bits--) // for each bit in byte
{
do
{
t1 = clock();
while (t1 == clock()) // spin within the resolution of 1 C clock() tick
{
a ^= 1; // flip
}
t1 = clock();
while (t1 == clock())
{
b ^= 1; // flip
}
} while (a == b); // ensure theres enough entropy for a deviation to occur
acc = (acc << 1) | a; // push the first bit state
}
*buf++ = acc;
acc = 0;
bits = 8;
}
return l;
}
static AuUInt32 RngGetBytes(AuUInt8 *out, AuUInt32 outlen)
{
AuUInt32 x;
#if defined(AURORA_IS_MODERNNT_DERIVED)
x = RngWin32(out, outlen);
if (x != 0)
{
return x;
}
#elif defined(AURORA_IS_POSIX_DERIVED)
x = RngUnix(out, outlen);
if (x != 0)
{
return x;
}
#endif
x = RngStdC(out, outlen);
if (x != 0)
{
return x;
}
return 0;
}
AUKN_SYM void ReadSecureRNG(void *in, AuUInt32 length)
{
AuUInt32 offset;
AuUInt8 *headPtr;
headPtr = reinterpret_cast<AuUInt8 *>(in);
offset = 0;
while (offset != length)
{
auto req = length - offset;
auto bytes = RngGetBytes(headPtr + offset, req);
SysAssertExp(bytes, "Couldn't consume {} RNG bytes", req);
offset += bytes;
}
}
AUKN_SYM void ReadFastRNG(void *in, AuUInt32 length)
{
WELL_NextBytes(&gWellRand, in, length);
}
AUKN_SYM AuString ReadString(AuUInt32 length, ERngStringCharacters type)
{
return gFastDevice->NextString(length, type);
}
AUKN_SYM void RngString(char *string, AuUInt32 length, ERngStringCharacters type)
{
gFastDevice->NextString(string, length, type);
}
AUKN_SYM AuUInt8 RngByte()
{
return gFastDevice->NextByte();
}
AUKN_SYM bool RngBoolean()
{
return gFastDevice->NextBoolean();
}
AUKN_SYM AuUInt32 RngU32()
{
return gFastDevice->NextU32();
}
AUKN_SYM AuUInt32 RngU32(AuUInt32 min, AuUInt32 max)
{
return gFastDevice->NextU32(min, max);
}
AUKN_SYM AuUInt64 RngU64()
{
return gFastDevice->NextU64();
}
AUKN_SYM AuInt32 RngInt(AuInt32 min, AuInt32 max)
{
return gFastDevice->NextInt(min, max);
}
AUKN_SYM double RngDecimal()
{
return gFastDevice->NextDecimal();
}
AUKN_SYM float RngNumber(float min, float max)
{
return gFastDevice->NextNumber(min, max);
}
AUKN_SYM AuUInt32 RngIndex(AuUInt32 count /* = max + 1*/)
{
return gFastDevice->NextIndex(count);
}
static void InitFastRng()
{
AuArray<AuUInt8, 64> maxEntropy;
RngArray<false, AuUInt8>(maxEntropy.data(), 64);
gWellRand = WELL_SeedRandBig64(maxEntropy);
gFastDevice = RandomUnique(RandomDef {false});
}
void Init()
{
InitRandPlatform();
InitFastRng();
}
void Release()
{
#if defined(AURORA_IS_POSIX_DERIVED)
if (gDevURand != NULL)
fclose(gDevURand);
#elif defined(AURORA_IS_MODERNNT_DERIVED) && defined(USE_OLD_NTCRYPT)
CryptReleaseContext(gCryptoProv, 0);
#endif
}
}