Overview / Machine learning

ModelGuard

Beta

Treats the model as a protected asset. Signs it with Ed25519, encrypts it at rest with ChaCha20-Poly1305, binds it to a license, watermarks it with the licensee, loads it into a protected region and verifies the loaded weights in memory.

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

modelguard.hpp

#include <ethereal/cpp/ml/guard/modelguard.hpp>

ModelGuard: the model as a protected asset (spec 34).

No inference library treats the model as an asset under attack. They all assume the file is benign. On a client it is not: whoever extracts the detection model trains against it. This module signs, encrypts, binds to a license and watermarks the model, and verifies the loaded weights in memory.

What this buys: it raises the cost of extracting the model. It does not make it impossible. The verifier runs on the attacker's machine, and during inference the weights are in plain text in memory. Encryption at rest defeats a copy of the file, not a copy of the memory. The real protection is split inference: the model that discriminates stays on the server (see the README).

The load order is strict, as in the Updater: the signature over the container bytes, then the parse, then the payload authentication (copied into the protected region, so what is verified is what is used), then decryption, and only then the model. Nothing that is not authenticated is read.

The module links no other module. The signature, the digest, the cipher, the license and the findings are seams, and the glues connect them to Crypto, Licensing and Guard.

const

MODELGUARD_MAGIC

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_MAGIC = 0x4D4C5445u;

Container magic, 'ETLM'.

const

MODELGUARD_FORMAT_VERSION

Ethereal::Ml::Guard#
inline constexpr ETL_UINT16 MODELGUARD_FORMAT_VERSION = 1u;

Container format version written by this code.

const

MODELGUARD_HEADER_SIZE

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_HEADER_SIZE = 20u;

Header size, in bytes.

const

MODELGUARD_SIGNATURE_SIZE

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_SIGNATURE_SIZE = 64u;

Signature size, in bytes.

const

MODELGUARD_PUBLIC_KEY_SIZE

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_PUBLIC_KEY_SIZE = 32u;

Public key size, in bytes.

const

MODELGUARD_DIGEST_SIZE

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_DIGEST_SIZE = 32u;

Payload digest size, in bytes.

const

MODELGUARD_MAX_METADATA

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_MAX_METADATA = 1u << 20;

Maximum metadata length, in bytes.

const

MODELGUARD_RUNTIME_VERSION

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_RUNTIME_VERSION = 1u;

Version of this code. A model that asks for a newer one is refused.

const

MODELGUARD_CIPHER_SLACK

Ethereal::Ml::Guard#
inline constexpr std::size_t MODELGUARD_CIPHER_SLACK = 64u;

Bytes after the data that the cipher can use as scratch (the caller zeroes them afterwards). Poly1305 wants the padding and the lengths right after the data.

const

MODELGUARD_FINDING_TAMPER

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_FINDING_TAMPER = 0x4D475431u;

Default id of the finding for weights changed in memory, 'MGT1'.

const

MODELGUARD_FLAG_ENCRYPTED

Ethereal::Ml::Guard#
inline constexpr ETL_UINT16 MODELGUARD_FLAG_ENCRYPTED = 0x1u;

Header flag: the payload is encrypted.

const

MODELGUARD_FLAG_WATERMARKED

Ethereal::Ml::Guard#
inline constexpr ETL_UINT16 MODELGUARD_FLAG_WATERMARKED = 0x2u;

Header flag: the container carries a licensee watermark.

const

MODELGUARD_FLAG_LICENSE_BOUND

Ethereal::Ml::Guard#
inline constexpr ETL_UINT16 MODELGUARD_FLAG_LICENSE_BOUND = 0x4u;

Header flag: the model is bound to a license.

const

MODELGUARD_FLAG_MASK

Ethereal::Ml::Guard#
inline constexpr ETL_UINT16 MODELGUARD_FLAG_MASK = 0x7u;

All known header flags.

const

MODELGUARD_HASH_SHA256

Ethereal::Ml::Guard#
inline constexpr ETL_UINT32 MODELGUARD_HASH_SHA256 = 1u;

Payload digest algorithm: SHA-256.

enum

EModelType

Ethereal::Ml::Guard#
C++
enum class   EModelType : ETL_UINT32
{
    /// @brief  Bytes the integrator knows how to read.
    eRaw = 0,

    /// @brief  A '.etltree' (Ml::Trees, the Isolation Forest of Anomaly).
    eTrees,

    /// @brief  A Ml::Neural model.
    eNeural,

    /// @brief  A Ml::Anomaly model that is not made of trees (the LOF 'ETLO', a
    ///             calibration 'ETLE').
    eAnomaly
};

Kind of model inside the container.

struct

SLicenseBinding

Ethereal::Ml::Guard#
C++
struct   SLicenseBinding   final
{
    /// @brief  Bit of uLicenseId.
    static constexpr ETL_UINT32 kLicenseId = 0x1u;

    /// @brief  Bit of uProductHash.
    static constexpr ETL_UINT32 kProduct = 0x2u;

    /// @brief  Bit of uEditionId.
    static constexpr ETL_UINT32 kEdition = 0x4u;

    /// @brief  The model must have been released inside the license update window.
    static constexpr ETL_UINT32 kUpdateWindow = 0x8u;

    /// @brief  Fields in use (k* bits).
    ETL_UINT32        uFields = 0u;

    /// @brief  License id.
    ETL_UINT64        uLicenseId = 0u;

    /// @brief  64 bit FNV-1a of the product name (the one Licensing uses).
    ETL_UINT64        uProductHash = 0u;

    /// @brief  Edition id.
    ETL_UINT32        uEditionId = 0u;
};

What binds the model to a license. Each field only counts with its bit.

struct

SModelMetadata

Ethereal::Ml::Guard#
C++
struct   SModelMetadata   final
{
    /// @brief  Kind of model.
    EModelType        eType = EModelType::eRaw;

    /// @brief  Number of inputs (0: not stated).
    ETL_UINT32        uInputs = 0u;

    /// @brief  Number of outputs (0: not stated).
    ETL_UINT32        uOutputs = 0u;

    /// @brief  Where the model came from ("lightgbm 4.7", "scikit-learn 1.7"...).
    std::string        sFramework;

    /// @brief  Hash of the feature spec used in training (0: none).
    ETL_UINT64        uSpecHash = 0u;

    /// @brief  Container watermark: who the model was delivered to.
    std::string        sLicensee;

    /// @brief  License binding.
    SLicenseBinding    Binding;

    /// @brief  When the model was released (the update window compares this).
    ETL_INT64        iReleasedUnix = 0;

    /// @brief  Minimum ModelGuard runtime version.
    ETL_UINT32        uMinRuntime = MODELGUARD_RUNTIME_VERSION;

    /// @brief  Payload digest algorithm. Filled by the writer, like the fields below.
    ETL_UINT32        uHashAlgorithm = MODELGUARD_HASH_SHA256;

    /// @brief  Digest of the stored payload.
    std::array< ETL_UINT8, MODELGUARD_DIGEST_SIZE >    PayloadDigest{};

    /// @brief  Cipher nonce. Only with encryption.
    std::array< ETL_UINT8, 12 >                        Nonce{};

    /// @brief  Size of the model in plain text.
    ETL_UINT64        uPlainSize = 0u;
};

The metadata. In plain text (the model can be inspected without the key) and signed.

struct

ISignatureVerifier

Ethereal::Ml::Guard#
C++
struct   ISignatureVerifier
{
    ///
    /// Verify
    ///
    /// @brief  Verifies a signature.
    ///
    /// @param Message        Signed bytes.
    /// @param Signature    The signature.
    /// @param PublicKey    The issuer public key.
    ///
    /// @return  true when the signature is valid.
    ///
    virtual bool Verify( std::span< const ETL_UINT8 > Message, std::span< const ETL_UINT8 > Signature,
                         std::span< const ETL_UINT8 > PublicKey ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~ISignatureVerifier() = default;
};

Verifies an Ed25519 signature (the Crypto glue).

struct

ISigner

Ethereal::Ml::Guard#
C++
struct   ISigner
{
    ///
    /// Sign
    ///
    /// @brief  Signs a message.
    ///
    /// @param Message            Bytes to sign.
    /// @param pSignature64        Receives the 64 byte signature.
    ///
    /// @return  true on success.
    ///
    virtual bool Sign( std::span< const ETL_UINT8 > Message, ETL_UINT8 * pSignature64 ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~ISigner() = default;
};

Signs. Only on the issuer side (the tool and the tests).

struct

IHasher

Ethereal::Ml::Guard#
C++
struct   IHasher
{
    /// @brief  Algorithm id (MODELGUARD_HASH_*).
    ///
    virtual ETL_UINT32 AlgorithmId() const ETL_NOEXCEPT = 0;

    /// @brief  Starts a new digest.
    ///
    virtual void Init() ETL_NOEXCEPT = 0;

    /// @brief  Adds bytes to the digest.
    ///
    virtual void Update( std::span< const ETL_UINT8 > Data ) ETL_NOEXCEPT = 0;

    /// @brief  Writes the 32 byte digest to @p pOut32.
    ///
    virtual void Final( ETL_UINT8 * pOut32 ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~IHasher() = default;
};

Payload digest (32 bytes).

struct

ICipher

Ethereal::Ml::Guard#
C++
struct   ICipher
{
    /// @brief  Nonce size, in bytes.
    ///
    virtual std::size_t NonceSize() const ETL_NOEXCEPT = 0;

    /// @brief  Tag size, in bytes.
    ///
    virtual std::size_t TagSize() const ETL_NOEXCEPT = 0;

    ///
    /// EncryptInPlace
    ///
    /// @brief  Encrypts @p Data in place and writes the tag.
    ///
    /// @param Nonce    The nonce.
    /// @param Data        Plain text, replaced by the cipher text.
    /// @param OutTag    Receives the tag.
    ///
    /// @return  true on success.
    ///
    virtual bool EncryptInPlace( std::span< const ETL_UINT8 > Nonce, std::span< ETL_UINT8 > Data, std::span< ETL_UINT8 > OutTag ) ETL_NOEXCEPT = 0;

    ///
    /// DecryptInPlace
    ///
    /// @brief  Checks the tag and decrypts @p Data in place.
    ///
    /// @param Nonce    The nonce.
    /// @param Data        Cipher text, replaced by the plain text.
    /// @param Tag        The expected tag.
    ///
    /// @return  false when the tag does not match.
    ///
    virtual bool DecryptInPlace( std::span< const ETL_UINT8 > Nonce, std::span< ETL_UINT8 > Data, std::span< const ETL_UINT8 > Tag ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~ICipher() = default;
};

Authenticated cipher, in place. The model is decrypted inside the protected region, and the plain text never goes through common memory.

Data has, after its end, MODELGUARD_CIPHER_SLACK bytes the cipher can use (the caller zeroes them afterwards). Decryption checks the tag before decrypting. On false the data is worthless (the caller zeroes it). The key lives in the glue (the integrator's, derived from the license, or from the server).

struct

SLicenseFacts

Ethereal::Ml::Guard#
C++
struct   SLicenseFacts   final
{
    /// @brief  License id.
    ETL_UINT64        uLicenseId = 0u;

    /// @brief  64 bit FNV-1a of the product name.
    ETL_UINT64        uProductHash = 0u;

    /// @brief  Edition id.
    ETL_UINT32        uEditionId = 0u;

    /// @brief  End of the update window (0: no window, every version).
    ETL_INT64        iUpdateWindowEndUnix = 0;
};

License of the running client (the Licensing glue).

struct

IEntitlement

Ethereal::Ml::Guard#
C++
struct   IEntitlement
{
    /// @brief  The license valid now. false: there is no license.
    ///
    virtual bool Current( SLicenseFacts * pOut ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~IEntitlement() = default;
};

Source of the current license.

struct

IFindingSink

Ethereal::Ml::Guard#
C++
struct   IFindingSink
{
    /// @brief  Receives one finding.
    ///
    /// @param uFindingId    Finding id.
    /// @param uWeight        Weight of the finding (number of bad pages and canaries).
    ///
    virtual void Report( ETL_UINT32 uFindingId, ETL_UINT32 uWeight ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~IFindingSink() = default;
};

Where the findings go (the Guard glue). The module never acts.

enum

ELoadStage

Ethereal::Ml::Guard#
C++
enum class   ELoadStage : ETL_UINT32
{
    /// @brief  The header was read.
    eHeaderRead = 0,

    /// @brief  The signature over the header and the metadata was verified.
    eSignatureVerified,

    /// @brief  The metadata was parsed.
    eMetadataParsed,

    /// @brief  The license and the spec were checked.
    ePolicyChecked,

    /// @brief  The payload digest matched.
    ePayloadAuthenticated,

    /// @brief  The payload was decrypted.
    eDecrypted,

    /// @brief  The model is ready.
    eReady
};

Steps of the load, in order. Used for diagnostics, and by the tests to prove that nothing goes past the signature when it fails.

struct

ILoadObserver

Ethereal::Ml::Guard#
C++
struct   ILoadObserver
{
    /// @brief  Called when the load reaches @p eStage.
    ///
    virtual void OnStage( ELoadStage eStage ) ETL_NOEXCEPT = 0;

    /// @brief  Destructor.
    ///
    virtual ~ILoadObserver() = default;
};

Receives the load steps.

struct

SGuardParams

Ethereal::Ml::Guard#
C++
struct   SGuardParams   final
{
    /// @brief  Signature verifier.
    ISignatureVerifier *    pVerifier = nullptr;

    /// @brief  Trusted public keys, 32 bytes each.
    const ETL_UINT8 *        pPublicKeys = nullptr;

    /// @brief  Id of each trusted key.
    const ETL_UINT32 *        pKeyIds = nullptr;

    /// @brief  Number of trusted keys.
    ETL_UINT32                uKeyCount = 0u;

    /// @brief  Payload digest. Required.
    IHasher *                pHasher = nullptr;

    /// @brief  Cipher. Required for encrypted models.
    ICipher *                pCipher = nullptr;

    /// @brief  License source. Without it, license bound models are refused.
    IEntitlement *            pEntitlement = nullptr;

    /// @brief  Hash of the feature spec of the live pipeline (0: not checked). A
    ///             model without a spec, or with another one, is refused
    ///             (@ref EStatus::eSpecMismatch).
    ETL_UINT64                uExpectedSpecHash = 0u;

    /// @brief  Sink for the findings of the in-memory verification.
    IFindingSink *            pFindings = nullptr;

    /// @brief  Finding id reported on a mismatch.
    ETL_UINT32                uFindingId = MODELGUARD_FINDING_TAMPER;

    /// @brief  Receives the load steps. May be null.
    ILoadObserver *            pObserver = nullptr;

    /// @brief  Where to write the reason of a refusal (the window date, the
    ///             license...). Null: nothing.
    std::string *            pMessage = nullptr;
};

Load parameters: the trust, the seams and the policy.

enum

EVerifyDepth

Ethereal::Ml::Guard#
C++
enum class   EVerifyDepth : ETL_UINT32
{
    /// @brief  Some random pages (the default, cheap).
    eSampled = 0,

    /// @brief  Every page (expensive, an explicit call).
    eFull
};

How much of the model VerifyIntegrity checks.

class

CProtectedModel

Ethereal::Ml::Guard#

A model loaded from a protected container.

class CProtectedModel final

The weights live in a region of their own: guard pages on both sides, locked out of paging when the system allows it, read only after the load (a write fails with a memory exception), and zeroed on unload. Inference reads them through Payload, with no cost per prediction.

constructor

CProtectedModel

#
CProtectedModel() noexcept;

Default constructor. Nothing is loaded.

constructor

CProtectedModel

#
CProtectedModel( CProtectedModel && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CProtectedModel & operator=( CProtectedModel && Other ) noexcept;

Move assignment. Unloads this model first. Other is left empty.

function

Load

#
static EStatus Load( std::span< const ETL_UINT8 > Container, const SGuardParams & Params, CProtectedModel * pOut );

Verifies, authenticates, decrypts and loads.

The seams of Params must live as long as the model (the in-memory verification uses them).

Container
Container bytes.
Params
Trust, seams and policy.
pOut
Receives the model.
eOk, or one status per refusal: EStatus::eBadMagic, EStatus::eVersionTooNew, EStatus::eSignatureTruncated (the file ends in the header or in the signature), EStatus::eTruncated (it ends in the body), EStatus::eCorrupt, EStatus::eUnknownKeyId, EStatus::eBadSignature, EStatus::ePayloadTampered, EStatus::eLicenseRefused, EStatus::eUpdateWindowClosed, EStatus::eSpecMismatch, EStatus::eDecryptFailed. EStatus::eNotLicensed when the library is not licensed.
function

LoadFile

#
static EStatus LoadFile( std::string_view sPath, const SGuardParams & Params, CProtectedModel * pOut );

Reads a file and calls Load.

sPath
File path, UTF-8.
Params
Trust, seams and policy.
pOut
Receives the model.
The statuses of Load, or eIoError. EStatus::eNotLicensed when the library is not licensed.
function

Payload

#
std::span< const ETL_UINT8 > Payload() const noexcept;

Model bytes, read only, page aligned (empty without a model).

function

Metadata

#
const SModelMetadata & Metadata() const noexcept

Metadata of the loaded model.

function

IsLoaded

#
bool IsLoaded() const noexcept

true when a model is loaded.

function

IsLocked

#
bool IsLocked() const noexcept

true when the region was locked out of paging (the system can refuse it: the user limit of locked memory).

function

VerifyIntegrity

#
EStatus VerifyIntegrity( EVerifyDepth eDepth ) noexcept;

Checks the weights in memory against what was loaded.

A difference goes to the findings sink and returns EStatus::eIntegrityFailure. It never acts: it does not unload, terminate or write logs. No allocations.

eDepth
Some random pages (EVerifyDepth::eSampled) or all of them.
eOk, eIntegrityFailure or eNotLoaded.
function

SetSampledPages

#
void SetSampledPages( ETL_UINT32 uPages ) noexcept;

Number of pages the sampled verification checks (default 16).

function

PageCount

#
std::size_t PageCount() const noexcept;

Number of pages of the model.

function

PageSize

#
std::size_t PageSize() const noexcept;

Page size of the system, in bytes.

function

Unload

#
EStatus Unload() noexcept;

Zeroes the weights and releases the region.

function

WriteContainer

Ethereal::Ml::Guard#
EStatus WriteContainer( const SModelMetadata & Meta, std::span< const ETL_UINT8 > Model, ETL_UINT32 uKeyId, ISigner * pSigner, IHasher * pHasher, ICipher * pCipher, std::vector< ETL_UINT8 > * pOut );

Writes a container: the digest, the encryption and the signature.

The fields of Meta filled by the writer are ignored.

Meta
Model metadata.
Model
Model bytes.
uKeyId
Id of the signing key.
pSigner
Signer.
pHasher
Payload digest.
pCipher
Cipher. Null: plain text.
pOut
Receives the container.
eOk, eInvalidArgument, eUnsupported or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
struct

SContainerHeader

Ethereal::Ml::Guard#
C++
struct   SContainerHeader   final
{
    /// @brief  Format version.
    ETL_UINT16        uVersion = 0u;

    /// @brief  Id of the signing key.
    ETL_UINT32        uKeyId = 0u;

    /// @brief  MODELGUARD_FLAG_* bits.
    ETL_UINT16        uFlags = 0u;

    /// @brief  Metadata length, in bytes.
    ETL_UINT32        uMetadataLength = 0u;

    /// @brief  Payload length, in bytes.
    ETL_UINT32        uPayloadLength = 0u;
};

Header of a container, as it is in the file.

function

VerifyContainer

Ethereal::Ml::Guard#
EStatus VerifyContainer( std::span< const ETL_UINT8 > Container, const SGuardParams & Trust, SContainerHeader * pHeader, SModelMetadata * pMeta );

Checks the signature and the payload, for the 'verify' tool.

Runs the load steps up to the payload authentication, without the license and without decrypting. Uses only the trust of Trust (the verifier, the keys, the digest).

Container
Container bytes.
Trust
Verifier, keys and digest.
pHeader
Receives the header. May be null.
pMeta
Receives the metadata. May be null.
eOk, or the refusal status of the load. EStatus::eNotLicensed when the library is not licensed.
function

ReadMetadataUnverified

Ethereal::Ml::Guard#
EStatus ReadMetadataUnverified( std::span< const ETL_UINT8 > Container, SContainerHeader * pHeader, SModelMetadata * pMeta );

Reads the header and the metadata without verifying the signature.

For inspecting the compatibility of a model without the key (the 'inspect' tool). Nothing this returns can be trusted.

Container
Container bytes.
pHeader
Receives the header. May be null.
pMeta
Receives the metadata. May be null.
eOk, or the status of the header or metadata parse.