Overview / Security & product

guard

Anti-reverse-engineering hardening primitives for legitimate software. The module detects, measures and protects, and never decides: it does not terminate processes and does not talk to the network. Everything ships off, with one CMake option per piece.

Optional module: turn it on with -DETHEREAL_GUARD=ONInclude #include <ethereal/cpp/guard/environment.hpp>C layer

environment.hpp

#include <ethereal/cpp/guard/environment.hpp>

Environment observation of the Guard module (debugger, timing, virtual machine).

Observes the environment and reports. It never acts, never ends the process, never decides.

Each signal comes with its real strength. The spec is explicit about this because overselling is a support and reputation liability:

  • Weak (the platform's own debugger query, 'TracerPid'): stopped in minutes, public bypasses exist. Here for completeness.
  • Moderate (debug registers per thread context): cost days.
  • Strong (timing deviation): single stepping and software breakpoints distort it in a way that is expensive to hide. It is the only one worth serious effort.

A virtual machine is reported as a fact, not as a verdict. Many legitimate users run in a VM, and treating a VM as hostile is how a product earns a one star review.

enum

EEnvSignal

Ethereal::Guard#
C++
enum class   EEnvSignal : ETL_UINT32
{
    /// @brief  No signal.
    eNone                    = 0u,

    /// Weak, for completeness.

    /// @brief  The platform says a debugger is attached.
    eDebuggerPresent        = 1u << 0,

    /// @brief  The 'TracerPid' of the process itself is not zero (POSIX).
    eTracerPid                = 1u << 1,

    /// Moderate.

    /// @brief  Hardware debug registers are armed on this thread.
    eHardwareBreakpoints    = 1u << 2,

    /// Strong.

    /// @brief  The signal that matters. A short sequence took much longer than it
    ///             should: single stepping or a software breakpoint distorting it.
    eTimingDeviation        = 1u << 3,

    /// Facts, not verdicts.

    /// @brief  Running in a virtual machine. It is a fact, nothing more.
    eVirtualMachine            = 1u << 4
};

The signals, each one maskable on its own.

operator

operator|

Ethereal::Guard#
constexpr EEnvSignal operator|( const EEnvSignal a, const EEnvSignal b ) noexcept

Union of two signals.

struct

SEnvironmentReport

Ethereal::Guard#
C++
struct   SEnvironmentReport   final
{
    /// @brief  'sizeof( SEnvironmentReport )'.
    ETL_UINT32        iStructSize = sizeof( SEnvironmentReport );

    /// @brief  Combination of @ref EEnvSignal.
    ETL_UINT32        uSignals = 0u;

    /// @brief  From 0 to 100, by the strength of what fired.
    ///
    /// @details  A number, not a yes or no. Timing deviation alone weighs a lot.
    ///            The platform debugger query weighs little. The integrator
    ///            decides the threshold, far from here, in a @ref CFindingSink.
    ETL_UINT32        uConfidence = 0u;

    /// @brief  How many nanoseconds the timing probe measured, for diagnostics.
    ETL_UINT64        uTimingNanos = 0u;
};

What the observation found. A number, never a verdict.

function

ObserveEnvironment

Ethereal::Guard#
EGuardStatus ObserveEnvironment( SEnvironmentReport * pOut, ETL_UINT32 uMask = 0u ) noexcept;

Observes the environment. Cost: ECostClass::eModerate.

Reports, does not act. Returns the signals and a confidence. It does not end the process, throw or log.

pOut
The report. Must not be null.
uMask
Which signals to observe, EEnvSignal OR-ed. Zero observes all those this platform supports.
eOk, eInvalidArgument or eNotSupported.
function

EnvironmentCapabilities

Ethereal::Guard#
ETL_UINT32 EnvironmentCapabilities() noexcept;

Which signals this build and this machine can observe.

Cost: ECostClass::eCheap.

function

CalibrateTiming

Ethereal::Guard#
EGuardStatus CalibrateTiming() noexcept;

Calibrates the timing deviation baseline, once, at startup.

Cost: ECostClass::eModerate.

Must be called at a clean moment, with no debugger attached, otherwise the baseline is born distorted and the probe never fires. The right place is startup, next to CIntegritySnapshot::SnapshotSelf.

function

EnvSignalName

Ethereal::Guard#
const ETL_CHAR * EnvSignalName( EEnvSignal eSignal ) noexcept;

Name of a signal, for reports.

eSignal
The signal (a single bit).
A static string. Never null.

findings.hpp

#include <ethereal/cpp/guard/findings.hpp>

The findings accumulator and the delayed read gate of the Guard module.

This is the most valuable piece of the module, and the one nobody builds on their own. Everything else here buys hours. This buys weeks, and the reason is economic, not technical.

Never fail at the point of detection. A check that ends the process the moment it detects something tells the attacker exactly where it is. They attach the debugger, see where it died, patch one instruction and move on. Each check becomes a five minute exercise, and forty checks are two hours of boring work.

The right way:

1. The detection calls 'Report' and returns normally. Nothing observable changes. 2. Findings pile up in obfuscated, scattered storage: not a counter at one address, but several shards combined on read. 3. The accumulator is read somewhere else, in unrelated code, seconds or minutes later. 4. The consequence is subtle degradation or telemetry, not a crash. 5. The real action happens on the server side, in batches.

This turns the economics around. The attacker can no longer run the observe, patch and repeat loop in minutes, because they cannot tell which of the forty checks fired, or when.

const

FINDING_SHARDS

Ethereal::Guard#
constexpr ETL_UINT32 FINDING_SHARDS = 8u;

How many shards the accumulator uses.

A counter at one address is a target. Whoever finds where the count lives puts a write breakpoint on it and catches every check at once.

With several shards, each finding touches one of them depending on its id, and the read combines them. It does not make it impossible. It makes it eight times more tedious, which is what this module sells.

const

FINDING_CAPACITY

Ethereal::Guard#
constexpr ETL_UINT32 FINDING_CAPACITY = 64u;

How many findings fit in the drainable list.

struct

SFinding

Ethereal::Guard#
C++
struct   SFinding   final
{
    /// @brief  'sizeof( SFinding )'.
    ETL_UINT32        iStructSize = sizeof( SFinding );

    /// @brief  Who reported it. The meaning belongs to the integrator.
    ETL_UINT32        uFindingId = 0u;

    /// @brief  How much it weighs.
    ETL_UINT32        uWeight = 0u;

    /// @brief  How many times this same finding was reported.
    ETL_UINT32        uCount = 0u;
};

A finding, as it comes out of CFindingSink::Drain.

class

CFindingSink

Ethereal::Guard#

The findings accumulator.

class CFindingSink final

It decides nothing, and that is the rule of the whole module. It holds primitives, not policy: it detects, measures and protects, and never chooses what to do with what it found.

It does not end processes, throw exceptions, write logs, phone home or ban anyone. Composing this into a real defense is the integrator's job.

No ETL_CLASS_ALIGN: the cache line aligned members already give 64, and a smaller alignment was ignored (C4359).

constructor

CFindingSink

#
CFindingSink() noexcept;

Default constructor. Empty accumulator.

function

Report

#
void Report( ETL_UINT32 uFindingId, ETL_UINT32 uWeight ) noexcept;

Records a finding and returns normally.

Cost: ECostClass::eCheap. Less than 50 ns, no allocation, and no observable effect at the call site.

The absence of effect is the contract, not a detail. If this call changed anything visible (a global counter, a file write, a delay) it would mark where the check is.

uFindingId
Who reported. Belongs to the integrator.
uWeight
How much it weighs. Added to the total.
function

Digest

#
ETL_UINT64 Digest() const noexcept;

The total accumulated weight, combined from the shards.

Cost: ECostClass::eCheap.

Read this far from where you reported. Reading right after the detection undoes everything this design buys: the attacker sees both places in the same neighborhood and links one to the other.

function

ExceedsThreshold

#
bool ExceedsThreshold( ETL_UINT32 uThreshold ) const noexcept;

Tells whether the total passed this limit.

Cost: ECostClass::eCheap.

uThreshold
The limit.
true when the total is above it.
function

DistinctCount

#
ETL_UINT32 DistinctCount() const noexcept;

How many distinct findings there are.

function

Drain

#
EGuardStatus Drain( SFinding * pOut, ETL_UINT32 uCap, ETL_UINT32 * pCount ) noexcept;

Takes the list out, for whoever sends it to the server.

Cost: ECostClass::eModerate.

pOut
Where to write. Null with uCap zero measures.
uCap
How many fit.
pCount
Receives how many exist, not how many fit.
eOk, eInvalidArgument or eBufferTooSmall.
function

Clear

#
void Clear() noexcept;

Forgets everything.

class

CTimeDelayedGate

Ethereal::Guard#

Makes the delayed read pattern the easy one to write.

class CTimeDelayedGate final

Without this, the integrator writes the naive version. It reads the accumulator right after the check, because that is the least work, and loses exactly what the accumulator exists to buy.

This gate only lets you look after some time has passed since the first finding. The time comes from outside, through the clock seam, so the bench can control it.

constructor

CTimeDelayedGate

#
CTimeDelayedGate() noexcept;

Default constructor. Closed, no delay.

function

Init

#
void Init( ETL_UINT64 uDelayMs ) noexcept;

Sets how much time must pass.

uDelayMs
How long after the first finding, in milliseconds.
function

Mark

#
void Mark( ETL_UINT64 uNowMs ) noexcept;

Says there was a finding, at this instant.

Cost: ECostClass::eCheap.

uNowMs
The instant, in milliseconds from any origin.
function

IsOpen

#
bool IsOpen( ETL_UINT64 uNowMs ) const noexcept;

Tells whether enough time has passed to look.

Cost: ECostClass::eCheap.

uNowMs
The instant, same origin as Mark.
true when the gate is open.
function

Reset

#
void Reset() noexcept;

Goes back to the start.

guard_common.hpp

#include <ethereal/cpp/guard/guard_common.hpp>

Shared types of the Guard module: the build seed, cost classes, capabilities, return states and the compile time hashes.

One flag per piece. The spec forbids a single switch. A tree with 'ETL_HARDENING' on would get everything: encrypted strings, debugger checks, integrity verification and timing traps. Whoever wants only one of them would get the other five.

Partial adoption is the normal case. A customer who only wants to hide strings does not want their own debugger to stop working. One who only wants integrity verification does not want to pay the access cost of the obfuscated values. So each piece has its own flag, and the absence of one does not affect the others.

None of this is on by default. A normal Ethereal build has no obfuscation at all: it is a library sold to programmers, who will debug their own code through it, run profilers, collect memory dumps from their users and pass the binary through their company antivirus. All of those paths break with aggressive obfuscation.

enum

ECostClass

Ethereal::Guard#
C++
enum class   ECostClass : ETL_UINT8
{
    /// @brief  Compile time only. Zero at run time.
    eFree = 0,

    /// @brief  Less than 50 ns.
    eCheap,

    /// @brief  Less than 10 us.
    eModerate,

    /// @brief  More than 10 us. Call on a schedule, never per frame.
    eExpensive
};

How much it costs to call something in this module.

Every public function here states its class in its doc block, for a simple reason: this module costs cycles and Ethereal is sold for being fast.

Without the class written down, the integrator finds out the cost when their profiler flags it, and by then the call is already inside a hot loop.

enum

EGuardCapability

Ethereal::Guard#
C++
enum class   EGuardCapability : ETL_UINT32
{
    /// @brief  No capability.
    eNone                    = 0u,

    /// @brief  Strings encrypted at compile time.
    eStringEncryption        = 1u << 0,

    /// @brief  Obfuscated values in memory.
    eProtectedValues        = 1u << 1,

    /// @brief  Import resolution by hash.
    eImportHashing            = 1u << 2,

    /// @brief  Image integrity verification.
    eIntegrity                = 1u << 3,

    /// @brief  Environment observation (debugger, virtual machine).
    eEnvironment            = 1u << 4,

    /// @brief  Timing deviation, the strong signal of section 3.5.
    eTimingDeviation        = 1u << 5,

    /// @brief  Processor debug registers.
    eDebugRegisters            = 1u << 6,

    /// @brief  Locking pages out of the swap file.
    ePageLocking            = 1u << 7,

    /// @brief  Guard pages around a sensitive allocation.
    eGuardPages                = 1u << 8
};

What this build and this machine can really do.

A check that passes silently is worse than no check.

A piece that is not available on this platform answers EGuardStatus eNotSupported. It never returns "clean" when it did not run, because whoever branches on that answer would believe they measured something.

operator

operator|

Ethereal::Guard#
constexpr EGuardCapability operator|( const EGuardCapability a, const EGuardCapability b ) noexcept

Union of two capabilities.

operator

operator&

Ethereal::Guard#
constexpr EGuardCapability operator&( const EGuardCapability a, const EGuardCapability b ) noexcept

Intersection of two capabilities.

function

Has

Ethereal::Guard#
constexpr bool Has( const EGuardCapability Set, const EGuardCapability Which ) noexcept

Tells whether a capability is in the set.

Set
The set.
Which
The capability to look for.
true when present.
function

Compiled

Ethereal::Guard#
constexpr EGuardCapability Compiled() noexcept

What this build brings. A compile time constant.

Cost: ECostClass::eFree.

It does not ask whether it works on this machine, only whether the code exists. For the second question there is Supported.

function

Supported

Ethereal::Guard#
EGuardCapability Supported() noexcept;

What this machine can do, now, with this privilege.

Cost: ECostClass::eModerate on the first call, cached after.

It probes, it does not assume. Locking pages needs privilege on some configurations. Reading the debug registers needs the platform to allow it. This function tries and answers with what it managed.

enum

EGuardStatus

Ethereal::Guard#
C++
enum class   EGuardStatus : ETL_UINT32
{
    /// @brief  It ran.
    eOk = 0,

    /// @brief  Invalid argument from the caller.
    eInvalidArgument,

    /// @brief  The buffer is too small. See the two pass protocol.
    eBufferTooSmall,

    /// @brief  This platform cannot do this.
    ///
    /// @details  'eOk' is never returned in place of this. A check that answers
    ///            "clean" when it did not even run lies to whoever branches on it.
    eNotSupported,

    /// @brief  This build does not have the code. See @ref Compiled.
    eNotCompiled,

    /// @brief  Missing privilege.
    eAccessDenied,

    /// @brief  The system refused for another reason.
    eSystemError,

    /// @brief  What was looked for was not found.
    eNotFound,

    /// @brief  Refused: no license was accepted and the evaluation of this machine has
    ///             ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

How a call went.

function

GuardStatusName

Ethereal::Guard#
const ETL_CHAR * GuardStatusName( EGuardStatus eStatus ) noexcept;

Name of the state, for messages.

eStatus
The state.
A static string. Never null.
function

GuardCapabilityName

Ethereal::Guard#
const ETL_CHAR * GuardCapabilityName( EGuardCapability eWhat ) noexcept;

Name of a capability, for reports.

eWhat
The capability (a single bit).
A static string. Never null.
function

HashFnv1a

Ethereal::Guard#
constexpr ETL_UINT32 HashFnv1a( const ETL_CHAR * pText, const ETL_UINT32 uSeed = ETL_GUARD_SEED ) noexcept

32 bit FNV-1a hash, at compile time, with the seed inside.

Cost: ECostClass::eFree when the arguments are constants.

It is the base of the string keys and the import hashes. The seed goes into the initial value, not at the end, so two builds diverge from the first byte.

pText
The text.
uSeed
The seed.
The hash.
function

HashFnv1aLower

Ethereal::Guard#
constexpr ETL_UINT32 HashFnv1aLower( const ETL_CHAR * pText, const ETL_UINT32 uSeed = ETL_GUARD_SEED ) noexcept

The same hash, case insensitive.

Module names on Windows show up with different casing depending on who wrote them. Comparing 'NTDLL.DLL' with 'ntdll.dll' by hash needs normalization, and normalizing here is free.

pText
The text.
uSeed
The seed.
The hash of the lower case text.
function

NextRandom

Ethereal::Guard#
constexpr ETL_UINT32 NextRandom( const ETL_UINT32 uState ) noexcept

A compile time number generator, for the per string keys.

One key per string, not a global one. With a single key, breaking one string breaks all of them, and the attacker only needs to find one they recognize to read the rest of the binary.

The sequence comes from this generator, seeded per string with '__COUNTER__', the line and the build seed.

uState
The current state.
The next state.

imports.hpp

#include <ethereal/cpp/guard/imports.hpp>

Import resolution by hash of the Guard module.

This is the best cost to benefit ratio of the whole module. Cheap to write, cheap at run time, and it removes from the binary the most informative artifact an analyst starts with.

The first thing anyone does with an unknown executable is look at the import table. It says, in one list, everything the program knows how to do: open files, talk over the network, read the registry, create processes. With the names out of it, that list is empty of the entries that matter.

What this is not: it does not hide what the program does. A sequence of system calls tells the same story to whoever looks at it at run time. It removes the shortcut.

function

ResolveByHash

Ethereal::Guard#
EGuardStatus ResolveByHash( ETL_UINT32 uModuleHash, ETL_UINT32 uFunctionHash, void ** ppOut ) noexcept;

Finds an exported function by the hash of its name, without naming it.

Cost: ECostClass::eModerate on the first call per function. Keep the result. The ETL_GUARD_IMPORT macro does that.

It walks the export table of the module already mapped, and does not call 'GetProcAddress' or 'dlsym'. The difference is not one of style: calling either one puts the function name as a string in the binary, which is exactly what this piece exists to avoid.

It does not show up in the import table either. The module is looked up in the process's own list of loaded modules: the PEB on Windows, 'dl_iterate_phdr' on POSIX.

uModuleHash
HashFnv1aLower of the module name, without path.
uFunctionHash
HashFnv1a of the function name.
ppOut
Receives the address.
EGuardStatus::eNotFound when the module or the function does not show up.
function

LoadedModuleCount

Ethereal::Guard#
ETL_UINT32 LoadedModuleCount() noexcept;

How many modules the process has loaded now.

Cost: ECostClass::eModerate.

For the bench and for diagnostics. A process with zero modules means the walk did not work, which is different from "the function is not there".

function

LoadedModuleHash

Ethereal::Guard#
ETL_UINT32 LoadedModuleHash( ETL_UINT32 uIndex ) noexcept;

Hash of the name of the module at this index.

Cost: ECostClass::eModerate.

uIndex
Module index.
Zero when the index does not exist.
class

CImportSlot

Ethereal::Guard#

Holds a resolved pointer, obfuscated, and resolves it only once.

template< typename TFn > class CImportSlot final

The pointer lives in an obfuscated value, not in a plain variable.

A memory scan for the known address of a system function is trivial to write and finds naive caches in no time, precisely because the value searched for is public.

The "already tried" state is kept apart from the pointer. Without it, a function that does not exist would be looked up on every call, and the export table walk is of class 'eModerate'.

function

Get

#
TFn Get( const ETL_UINT32 uModuleHash, const ETL_UINT32 uFunctionHash ) noexcept

Returns the function, resolving it the first time.

Cost: ECostClass::eModerate on the first call, ECostClass::eCheap after.

uModuleHash
HashFnv1aLower of the module name.
uFunctionHash
HashFnv1a of the function name.
Null when it does not exist. Always check: a missing function is a normal case, because the system version changes.
function

Reset

#
void Reset() noexcept

Forgets what it resolved.

macro

ETL_GUARD_IMPORT

#
#define ETL_GUARD_IMPORT( TFn, sModule, sFunction ) \

Declares an import resolved by hash, with a cache.

@def ETL_GUARD_IMPORT Use it inside a function:

C++
using FQuery = LONG ( __stdcall * )( HANDLE, ULONG, PVOID, ULONG, PULONG );

const FQuery pF = ETL_GUARD_IMPORT( FQuery, "ntdll.dll",
                                   "NtQueryInformationProcess" );

if( pF != nullptr ) { ... }

Both names are hashed at compile time, with the seed inside. Neither shows up in the binary, and two builds with different seeds produce different hashes.

The cache is 'static' inside the function, so it is per call site. Two sites that ask for the same function resolve it twice, which costs two walks in the life of the process and avoids a global table that would itself be a target.

integrity.hpp

#include <ethereal/cpp/guard/integrity.hpp>

Image integrity verification of the Guard module.

Checks that the code in memory is what it was. Detects a patched binary and an inline hook on an export.

Returns findings and never acts. It does not end the process, throw or log. Composing this into a defense is the integrator's job, and in our portfolio, Praetor's.

The snapshot is taken at startup, not read from disk. Comparing memory with the file on disk means undoing relocations and normalizing the import table, and that is what makes almost every home made checker give false positives all the time. A snapshot taken right after startup, when the image is already relocated and the imports already resolved, is the right reference state: what changes from then on is a patch, not the loader doing its job.

const

INTEGRITY_MAX_HOOKS

Ethereal::Guard#
constexpr ETL_UINT32 INTEGRITY_MAX_HOOKS = 32u;

How many exports a hook snapshot tracks.

struct

SIntegrityReport

Ethereal::Guard#
C++
struct   SIntegrityReport   final
{
    /// @brief  'sizeof( SIntegrityReport )'.
    ETL_UINT32        iStructSize = sizeof( SIntegrityReport );

    /// @brief  The code in memory differs from the snapshot.
    ETL_UINT8        bTextModified = 0u;

    /// @brief  Some tracked export has its first bytes changed.
    ETL_UINT8        bInlineHookDetected = 0u;

    /// @brief  Explicit padding.
    ETL_UINT16        uPadding = 0u;

    /// @brief  How many regions differ from the snapshot.
    ETL_UINT32        uMismatchCount = 0u;

    /// @brief  How many tracked exports were found changed.
    ETL_UINT32        uHookCount = 0u;

    /// @brief  Address of the first difference, or zero.
    ETL_UINT64        uFirstMismatchAddress = 0u;
};

What the verification found. See the note of CIntegritySnapshot::VerifySelf.

class

CIntegritySnapshot

Ethereal::Guard#

Holds the reference state. Taken once, compared many times.

class CIntegritySnapshot final

The snapshot must be taken early, before anything could have patched the code. The right place is right after the subsystems start.

constructor

CIntegritySnapshot

#
CIntegritySnapshot() noexcept;

Default constructor. No snapshot.

function

SnapshotSelf

#
EGuardStatus SnapshotSelf() noexcept;

Takes the snapshot of the executable code of this module.

Cost: ECostClass::eExpensive. Walks and hashes the executable regions of the image itself.

Does not allocate on the heap for the regions: there are few of them and they fit in a fixed size internal array. When there are more regions than it holds, returns EGuardStatus::eBufferTooSmall and says how many it needed.

function

TrackExport

#
EGuardStatus TrackExport( ETL_UINT32 uModuleHash, ETL_UINT32 uFunctionHash ) noexcept;

Adds an export to the inline hook snapshot.

Cost: ECostClass::eModerate.

Legitimate hooks exist and are common: game overlays, graphics tools, accessibility software and the customer's own profiler hook functions all the time. So this reports and does not judge. Whoever tracks an export is who decides that a hook on it matters.

uModuleHash
HashFnv1aLower of the module name.
uFunctionHash
HashFnv1a of the function name.
eOk, eNotFound, eBufferTooSmall or eNotSupported.
function

VerifySelf

#
EGuardStatus VerifySelf( SIntegrityReport * pOut ) noexcept;

Compares the current state with the snapshot.

Cost: ECostClass::eExpensive.

Returns, does not act. The report says what changed. What to do with it belongs to the caller, and the recommended path is to report to a CFindingSink and act later, far from here.

pOut
Receives the report.
eOk, eInvalidArgument, or eNotFound without a snapshot.
function

HasSnapshot

#
bool HasSnapshot() const noexcept;

true once the snapshot was taken.

function

RegionCount

#
ETL_UINT32 RegionCount() const noexcept;

How many regions the snapshot holds.

function

TrackedCount

#
ETL_UINT32 TrackedCount() const noexcept;

How many exports it tracks.

function

HashRange

Ethereal::Guard#
EGuardStatus HashRange( ETL_UINT64 uAddress, ETL_UINT64 uSize, ETL_UINT32 * pHashOut ) noexcept;

Hashes an address range of this process.

Cost: ECostClass::eModerate, depending on the size.

For those who want to pin only the few functions that matter instead of paying for the whole code section.

uAddress
The start, in this process's memory.
uSize
How many bytes.
pHashOut
Receives the hash.
eOk or eInvalidArgument.

secmem.hpp

#include <ethereal/cpp/guard/secmem.hpp>

Secure memory of the Guard module: real wiping, constant time comparison, page locking, guarded allocations and the encrypted region.

function

SecureZero

Ethereal::Guard#
void SecureZero( void * pMemory, std::size_t uBytes ) noexcept;

Fills with zeros, and the optimizer cannot remove the call.

Cost: ECostClass::eCheap.

A 'memset' on a buffer about to die is removed by every optimizer, and this is a class of defect that has shipped to production more times than anyone can count.

The rule that allows it is dead store elimination: if nobody reads what was written, the write has no observable effect and may go away. For a password on the stack, that means it stays there after the code says it wiped it.

This uses what the platform offers to forbid it, and a compiler barrier on the fallback path. The bench checks the generated code at every optimization level, because that is the only way to know.

pMemory
The memory.
uBytes
How many bytes.
function

ConstantTimeEquals

Ethereal::Guard#
bool ConstantTimeEquals( const void * pA, const void * pB, std::size_t uBytes ) noexcept;

Compares two blocks in constant time.

Cost: ECostClass::eCheap.

A 'memcmp' gives up at the first different byte, and the time it takes tells how many bytes matched. Whoever compares an authentication token with 'memcmp' is handing it byte by byte to whoever measures.

This one always walks the whole length.

pA
First block.
pB
Second block.
uBytes
How many bytes.
true when equal.
function

LockPages

Ethereal::Guard#
EGuardStatus LockPages( void * pMemory, std::size_t uBytes ) noexcept;

Keeps these pages out of the swap file.

Cost: ECostClass::eModerate.

A key that goes through the swap file stays on disk after the process dies, and survives a power off. Locking the pages avoids that. It does not avoid a memory dump, which is something else.

It may fail for lack of privilege, and then returns EGuardStatus::eAccessDenied instead of pretending it locked. On Windows there is a per process limit that runs out fast. On POSIX 'RLIMIT_MEMLOCK' is usually small.

pMemory
The memory.
uBytes
How many bytes.
eOk, eInvalidArgument, eAccessDenied or eSystemError.
function

UnlockPages

Ethereal::Guard#
EGuardStatus UnlockPages( void * pMemory, std::size_t uBytes ) noexcept;

Undoes LockPages.

Cost: ECostClass::eModerate.

pMemory
The memory.
uBytes
How many bytes.
eOk, eInvalidArgument or eSystemError.
function

SecureAllocOverhead

Ethereal::Guard#
std::size_t SecureAllocOverhead() noexcept;

Size of the hidden header of a guarded allocation.

function

SecureAlloc

Ethereal::Guard#
EGuardStatus SecureAlloc( std::size_t uBytes, void ** ppOut ) noexcept;

Allocates with a guard page on both sides and a canary.

Cost: ECostClass::eExpensive. Allocates system pages.

Guard pages have no access at all, one before and one after. Whoever writes a byte past the end gets a fault the moment they do it, instead of corrupting whatever comes next and showing up half an hour later somewhere else.

The canary is a second line: it catches an overflow that jumps over the guard page, which is what a copy with an attacker controlled size does.

uBytes
Usable size.
ppOut
Receives the pointer to the usable area.
eOk, eInvalidArgument or eSystemError.
function

SecureFree

Ethereal::Guard#
EGuardStatus SecureFree( void * pMemory ) noexcept;

Returns what SecureAlloc gave, wiping it first.

Cost: ECostClass::eExpensive.

Always wipes before returning. A secure allocation that goes back to the system with its content intact is secure in name only.

pMemory
Pointer returned by SecureAlloc.
eOk or eInvalidArgument.
function

VerifyCanary

Ethereal::Guard#
bool VerifyCanary( const void * pMemory ) noexcept;

Tells whether the canary of this allocation is still intact.

Cost: ECostClass::eCheap.

pMemory
Pointer returned by SecureAlloc.
false also when the pointer did not come from SecureAlloc.
class

CSecureBuffer

Ethereal::Guard#

A secure block with a size known at compile time.

template< typename T, std::size_t N > class CSecureBuffer final

It allocates nothing: the storage is the object itself, so it lives wherever its declarer put it. A class member stays in the class, a local variable stays on the stack.

What it guarantees is the wipe at the end and the canary. Whoever needs guard pages uses SecureAlloc, which costs system pages and does not belong in a function called often.

constructor

CSecureBuffer

#
CSecureBuffer() noexcept

Zeroes the storage and sets the canary.

function

Data

#
T * Data() noexcept

The storage.

function

Data

#
const T * Data() const noexcept
function

Size

#
constexpr std::size_t Size() const noexcept

Number of elements.

function

SizeBytes

#
constexpr std::size_t SizeBytes() const noexcept

Size in bytes.

function

VerifyCanary

#
bool VerifyCanary() const noexcept

Tells whether the canary is still intact.

function

Wipe

#
void Wipe() noexcept

Wipes now, without waiting for the end of the scope.

class

CScopedAccess

Ethereal::Guard#

The window in which the content of a CEncryptedRegion is in plain text.

class CScopedAccess final

The plain text only exists while this lives. At the end of the scope the region is encrypted again, and the pointer that came out of here is no longer valid.

constructor

CScopedAccess

#
CScopedAccess() noexcept = default;

Empty, invalid window.

constructor

CScopedAccess

#
CScopedAccess( CEncryptedRegion * pOwner ) noexcept;

Opens a window on the region.

pOwner
The owning region.
constructor

CScopedAccess

#
CScopedAccess( CScopedAccess && Other ) noexcept;

Move constructor. The other window becomes invalid.

Other
The window to move from.
function

Data

#
void * Data() noexcept;

The plain text area. Null when invalid.

function

Size

#
std::size_t Size() const noexcept;

Size of the region. Zero when invalid.

function

IsValid

#
bool IsValid() const noexcept

true when the window is open on a region.

class

CEncryptedRegion

Ethereal::Guard#

A region encrypted at rest, in plain text only inside a window.

class CEncryptedRegion final

What this solves is the memory scan. A secret that lives in plain text for the whole run of the process is there for whoever reads memory at any moment. Encrypted at rest, it is only readable during the windows in which the program needs it.

The key does not sit next to the ciphertext. It comes from transient process state (addresses that change on every run), because a key stored next to what it encrypts encrypts nothing.

It is not strong cryptography, and the header says so: it is added cost for whoever scans memory, not protection against whoever stops the process in the debugger during the window.

constructor

CEncryptedRegion

#
CEncryptedRegion() noexcept;

Default constructor. No region.

function

Init

#
EGuardStatus Init( std::size_t uBytes ) noexcept;

Allocates and encrypts a region of uBytes.

Cost: ECostClass::eExpensive.

uBytes
Region size.
eOk, eInvalidArgument or eSystemError.
function

Shutdown

#
void Shutdown() noexcept;

Frees, wiping.

function

IsOpen

#
bool IsOpen() const noexcept;

true between Init and Shutdown.

function

Size

#
std::size_t Size() const noexcept;

Region size.

function

Access

#
CScopedAccess Access() noexcept;

Opens the window. It closes by itself at the end of the scope.

Cost: ECostClass::eModerate, it encrypts the whole region at both ends. Not for calling in a loop.

function

OpenWindows

#
ETL_UINT32 OpenWindows() const noexcept;

How many windows are open now.

Windows nest: the region is only encrypted again when the last one closes.

strings.hpp

#include <ethereal/cpp/guard/strings.hpp>

Literal strings encrypted at compile time and decrypted to the stack.

This removes the text from the output of 'strings' and stops a casual 'grep'. Against someone who knows what they are doing it only buys hours, because emulation dumps every string.

It is still worth having. Most people who look at a binary never go past 'strings'. It should not be sold as more than that.

const

GUARD_STRING_MAX

Ethereal::Guard#
constexpr std::size_t GUARD_STRING_MAX = 256u;

Longest string accepted. Above this the code does not compile.

The decryption buffer lives on the stack, so a 10 KiB string puts 10 KiB on the stack of the caller. Large texts belong in encrypted resource data, not in a literal.

The error message says this, so whoever hits the limit knows what to do instead of raising the number.

struct

SCipherText

Ethereal::Guard#
C++
template< std::size_t N, ETL_UINT32 SEED >
struct   SCipherText   final
{
    ETL_CHAR    aBytes[ N ];

    constexpr SCipherText( const ETL_CHAR ( &pText )[ N ] ) ETL_NOEXCEPT
        : aBytes()
    {
        ETL_UINT32 uState = SEED;

        for( std::size_t i = 0; i < N; ++i )
        {
            uState = NextRandom( uState );

            aBytes[ i ] = static_cast< ETL_CHAR >(
                static_cast< unsigned char >( pText[ i ] )
                ^ static_cast< unsigned char >( uState >> 24 ) );
        }
    }
};

The encrypted text, produced at compile time.

This is the piece that makes the encryption happen early.

The first version had the 'constexpr' constructor on the protected string itself and passed the literal to it. The object was built at run time, so the literal stayed in '.rdata' as is and the encryption happened after the binary already had it.

The bench found it by searching for the text in the linked file. Reading '.Get()' and seeing the right text proves nothing about what is on disk.

Storing the result in a constant forces early evaluation. A 'constexpr auto' does not compile if the expression cannot be evaluated at compile time. The macro does exactly that, which is why it exists instead of calling the constructor by hand.

class

CProtectedString

Ethereal::Guard#

A string encrypted at compile time and decrypted to the stack.

template< std::size_t N, ETL_UINT32 SEED > class CProtectedString final

The plain text never lives in static storage. It exists inside this object, which dies at the end of the scope and is wiped when it dies.

The key is per string. With a global key, breaking one string breaks all of them. Here the key comes from '__COUNTER__', the line and the build seed, so two equal strings in the same file give different cipher texts.

The cipher is not a single byte XOR, which falls to frequency analysis in a minute. The key changes at every byte, for the whole length of the string.

constructor

CProtectedString

#
explicit CProtectedString( const SCipherText< N, SEED > & Cipher ) noexcept : m_pCipher( Cipher.aBytes ) , m_bDecrypted( false )

Receives the text already encrypted. See SCipherText.

function

Get

#
const ETL_CHAR * Get() noexcept

Decrypts into the internal buffer and returns it.

Cost: ECostClass::eCheap. Under 100 ns for 32 bytes, with no memory allocation.

The plain text.
The pointer dies with the object. Keeping it past the scope gives a dangling pointer, and the bench cannot catch that.
function

Length

#
constexpr std::size_t Length() const noexcept

Length without the terminator.

function

Wipe

#
void Wipe() noexcept

Wipes the plain text now, without waiting for the end of the scope.

class

CPlainString

Ethereal::Guard#

Same interface, without encryption. For debug builds. See the note on the macro.

template< std::size_t N > class CPlainString final
constructor

CPlainString

#
constexpr CPlainString( const ETL_CHAR ( &pText )[ N ] ) noexcept : m_pText( pText )
function

Get

#
const ETL_CHAR * Get() noexcept
function

Length

#
constexpr std::size_t Length() const noexcept
function

Wipe

#
void Wipe() noexcept
macro

ETL_GUARD_STR_SEED_

#
#define ETL_GUARD_STR_SEED_( uCounter ) \

The seed of each string combines three values, and none of them is enough alone.

'__COUNTER__' tells apart two equal strings in the same file. The line tells apart two builds where the counter restarted. The build seed tells apart two deliveries.

Without the first one, two equal strings would have the same cipher text and breaking one would give the other for free.

macro

ETL_GUARD_STR

#
#define ETL_GUARD_STR( sLiteral ) \

A literal string encrypted at compile time.

The 'constexpr' inside the lambda is what forces the encryption to happen early.

Without it the constructor would run at run time and the literal would stay in the binary as is. That was the defect of the first version, found by the bench when it searched for the text in the linked file.

C++
auto S = ETL_GUARD_STR( "texto sensivel" );
Usa( S.Get() );
macro

ETL_GUARD_STR

#
#define ETL_GUARD_STR( sLiteral ) \

In debug builds this does not encrypt anything, on purpose.

Whoever is debugging needs to see the strings in the debugger. Nobody reverse engineers a debug build, so encrypting there only makes the daily work worse.

The interface is the same in both cases, the same '.Get()' and the same lifetime. That is what lets the code compile the same way with and without the flag.

values.hpp

#include <ethereal/cpp/guard/values.hpp>

Obfuscated values in memory, for the Guard module.

class

CProtectedValue

Ethereal::Guard#

A stored value combined with a per instance key.

template< typename T > class CProtectedValue final

Two instances with the same logical value have different memory contents, and that is what defeats the tool that scans memory looking for the number 1000.

The key comes from the object's own address. It is not a secret: whoever has the address has the key. But whoever scans memory for a known value does not have the address, which is exactly what they are trying to find.

No implicit conversion, on purpose. Whoever uses this writes '.Get()'. Making the cost invisible at the call site is how these end up inside loops.

constructor

CProtectedValue

#
CProtectedValue() noexcept

Default constructor. Holds a zeroed value.

constructor

CProtectedValue

#
explicit CProtectedValue( const T Value ) noexcept

Constructor from a value.

Value
The value.
constructor

CProtectedValue

#
CProtectedValue( const CProtectedValue & Other ) noexcept

Copy constructor. It re encrypts, it does not copy the bytes.

The destination is at another address, so it has another key. Copying the raw content would give a different value on read.

operator

operator=

#
CProtectedValue & operator=( const CProtectedValue & Other ) noexcept

Copy assignment. Re encrypts, like the copy constructor.

function

Get

#
T Get() const noexcept

Reads the value.

Cost: ECostClass::eCheap, 10x to 50x a normal access.

function

Set

#
void Set( const T Value ) noexcept

Writes the value.

Cost: ECostClass::eCheap.

Value
The value.
function

Wipe

#
void Wipe() noexcept

Wipes, leaving the field with garbage instead of an encrypted zero.

alias

ProtectedI32

Ethereal::Guard#
using ProtectedI32 = CProtectedValue< ETL_INT32 >;

Shortcuts for the common cases.

alias

ProtectedU32

Ethereal::Guard#
using ProtectedU32 = CProtectedValue< ETL_UINT32 >;
alias

ProtectedI64

Ethereal::Guard#
using ProtectedI64 = CProtectedValue< ETL_INT64 >;
alias

ProtectedU64

Ethereal::Guard#
using ProtectedU64 = CProtectedValue< ETL_UINT64 >;
alias

ProtectedPtr

Ethereal::Guard#
using ProtectedPtr = CProtectedValue< void * >;
alias

ProtectedBool

Ethereal::Guard#
using ProtectedBool = CProtectedValue< ETL_UINT8 >;