Overview / Networking

tls

In-house TLS 1.3 (RFC 8446), client and server, with the X.509 it needs: DER, certificates, chains, host names, PEM and the system roots. TLS 1.3 only, on purpose: 1.2 would double the attack surface.

Always compiled: part of the core build.Include #include <ethereal/cpp/tls/der.hpp>C layer

der.hpp

#include <ethereal/cpp/tls/der.hpp>

Strict ASN.1 DER reader (ITU-T X.690), the base of the X.509 parser.

Reads tag, length and value triples from a byte span without copying. Only DER is accepted:

  • one byte tags (tag numbers 0 to 30), which is all X.509 uses;
  • definite lengths in the shortest form, at most 4 length bytes, never past the end of the input;
  • no indefinite length (0x80). The value helpers add the rules of each type: INTEGER without a redundant leading byte, BOOLEAN only 0x00 or 0xFF, NULL empty, BIT STRING with zero unused bits, OID subidentifiers in the shortest form, and the RFC 5280 "Z" forms of UTCTime and GeneralizedTime.

Nothing here reads outside the input span. Nesting is bounded by the caller (the X.509 parser has a fixed shape) or by the depth argument of Validate.

enum

ETag

Ethereal::Tls::Der#
C++
enum ETag : ETL_UINT8
{
    /// @brief  BOOLEAN.
    eTagBoolean                = 0x01,

    /// @brief  INTEGER.
    eTagInteger                = 0x02,

    /// @brief  BIT STRING.
    eTagBitString            = 0x03,

    /// @brief  OCTET STRING.
    eTagOctetString            = 0x04,

    /// @brief  NULL.
    eTagNull                = 0x05,

    /// @brief  OBJECT IDENTIFIER.
    eTagOid                    = 0x06,

    /// @brief  UTF8String.
    eTagUtf8String            = 0x0C,

    /// @brief  PrintableString.
    eTagPrintableString        = 0x13,

    /// @brief  TeletexString (T61String).
    eTagTeletexString        = 0x14,

    /// @brief  IA5String.
    eTagIa5String            = 0x16,

    /// @brief  UTCTime.
    eTagUtcTime                = 0x17,

    /// @brief  GeneralizedTime.
    eTagGeneralizedTime        = 0x18,

    /// @brief  UniversalString.
    eTagUniversalString        = 0x1C,

    /// @brief  BMPString.
    eTagBmpString            = 0x1E,

    /// @brief  SEQUENCE (constructed).
    eTagSequence            = 0x30,

    /// @brief  SET (constructed).
    eTagSet                    = 0x31
};

Universal tags used by X.509, with the constructed bit where it applies.

const

MAX_LENGTH

Ethereal::Tls::Der#
static constexpr std::size_t MAX_LENGTH = 0xFFFFFFu;

Largest element length accepted, in bytes (16 MB, the TLS limit of a certificate list).

function

ContextTag

Ethereal::Tls::Der#
constexpr ETL_UINT8 ContextTag( const unsigned uNumber, const bool bConstructed ) noexcept

Tag of a context specific element [n].

uNumber
The tag number, 0 to 30.
bConstructed
true for EXPLICIT tags and constructed IMPLICIT ones.
The tag byte.
struct

SElement

Ethereal::Tls::Der#
C++
struct   SElement   final
{
    /// @brief  The tag byte.
    ETL_UINT8 uTag = 0;

    /// @brief  The value bytes.
    std::span< const std::uint8_t > Content;

    /// @brief  The whole element: tag, length and value.
    std::span< const std::uint8_t > Whole;
};

One TLV element.

class

CReader

Ethereal::Tls::Der#

Reads consecutive DER elements from a span.

class CReader final

After the first failure every call fails, so a parser can chain reads and test once. Does not own the bytes.

constructor

CReader

#
explicit CReader( std::span< const std::uint8_t > Data ) noexcept : m_Data( Data )

Constructor over the bytes to read.

function

Read

#
bool Read( SElement & Out ) noexcept;

Reads the next element, whatever its tag.

Out
Receives the element.
false at the end of the input or on a DER error.
function

Expect

#
bool Expect( ETL_UINT8 uTag, SElement & Out ) noexcept;

Reads the next element and requires a tag.

uTag
The required tag.
Out
Receives the element.
false on another tag (the reader then fails), at the end or on a DER error.
function

ReadOptional

#
bool ReadOptional( ETL_UINT8 uTag, SElement & Out, bool & bPresent ) noexcept;

Reads the next element only when it has the given tag.

uTag
The tag.
Out
Receives the element when present.
bPresent
Receives whether it was present.
false only on a DER error.
function

AtEnd

#
bool AtEnd() const noexcept

true when everything was read.

function

Failed

#
bool Failed() const noexcept

true after a failure.

function

Fail

#
void Fail() noexcept

Marks the reader as failed.

function

ParseSingle

Ethereal::Tls::Der#
bool ParseSingle( std::span< const std::uint8_t > Data, SElement & Out ) noexcept;

Reads exactly one element that fills the whole input.

Data
The bytes.
Out
Receives the element.
false on a DER error or trailing bytes.
function

IsValidInteger

Ethereal::Tls::Der#
bool IsValidInteger( std::span< const std::uint8_t > Content ) noexcept;

Checks INTEGER contents: not empty, no redundant leading 0x00 or 0xFF.

Content
The value bytes.
true when valid.
function

ReadSmallUnsigned

Ethereal::Tls::Der#
bool ReadSmallUnsigned( const SElement & Element, std::uint64_t & uOut ) noexcept;

Reads a non negative INTEGER that fits in 63 bits.

Element
The INTEGER element.
uOut
Receives the value.
false when not an INTEGER, malformed, negative or too large.
function

ReadPositiveInteger

Ethereal::Tls::Der#
bool ReadPositiveInteger( const SElement & Element, std::span< const std::uint8_t > & Out ) noexcept;

Reads a positive INTEGER as unsigned big-endian bytes.

Element
The INTEGER element.
Out
Receives the magnitude, without the sign byte.
false when not an INTEGER, malformed, zero or negative.
function

ReadBoolean

Ethereal::Tls::Der#
bool ReadBoolean( const SElement & Element, bool & bOut ) noexcept;

Reads a BOOLEAN. DER allows only 0x00 and 0xFF.

Element
The element.
bOut
Receives the value.
false when not a valid BOOLEAN.
function

ReadBitString

Ethereal::Tls::Der#
bool ReadBitString( const SElement & Element, std::span< const std::uint8_t > & Bits, unsigned & uUnused ) noexcept;

Reads a BIT STRING.

The unused bit count must be 0 to 7, 0 when there are no bits, and the unused bits themselves must be zero.

Element
The element.
Bits
Receives the bytes after the unused bits count.
uUnused
Receives the unused bits count.
false when not a valid BIT STRING.
function

IsValidOid

Ethereal::Tls::Der#
bool IsValidOid( std::span< const std::uint8_t > Content ) noexcept;

Checks OBJECT IDENTIFIER contents: not empty, each subidentifier in the shortest form, the last one complete.

Content
The value bytes.
true when valid.
function

IsOid

Ethereal::Tls::Der#
bool IsOid( const SElement & Element, std::span< const std::uint8_t > Oid ) noexcept;

Checks whether an element is a given OID.

Element
The element.
Oid
The OID contents (without tag and length).
true when the tag is OBJECT IDENTIFIER and the bytes are equal.
function

ReadTime

Ethereal::Tls::Der#
bool ReadTime( const SElement & Element, std::int64_t & iOut ) noexcept;

Reads a UTCTime or GeneralizedTime as Unix seconds.

Only the forms RFC 5280 allows: "YYMMDDHHMMSSZ" for UTCTime (years 50 to 99 are 1950 to 1999) and "YYYYMMDDHHMMSSZ" for GeneralizedTime, no fraction, no offset, seconds 0 to 59, a real calendar date.

Element
The element.
iOut
Receives seconds since 1970-01-01T00:00:00Z.
false when not a valid time.
function

Validate

Ethereal::Tls::Der#
bool Validate( std::span< const std::uint8_t > Data, std::size_t uMaxDepth ) noexcept;

Walks a DER tree and checks its encoding.

Every element of the input in sequence, descending into the constructed ones. Checks tags and lengths, and the contents of BOOLEAN, INTEGER, NULL, OID and BIT STRING. Used by the tests.

Data
The bytes.
uMaxDepth
Deepest nesting allowed.
true when the whole input is well formed.

engine.hpp

#include <ethereal/cpp/tls/engine.hpp>

TLS 1.3 engine without I/O, client and server.

The engine takes the bytes received from the peer (CTlsEngine::Feed), gives the bytes to send (CTlsEngine::PendingOutput) and reports events: handshake done, data available, peer closed, error with the alert. It never touches a socket and never blocks, so the same engine serves a blocking stream (stream.hpp), an event loop or a test that wires two engines in memory.

Scope: TLS 1.3 only (RFC 8446). Suites TLS_AES_128_GCM_SHA256, TLS_CHACHA20_POLY1305_SHA256, TLS_AES_256_GCM_SHA384. Groups x25519 and secp256r1. HelloRetryRequest on both sides. The client accepts ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384 and rsa_pss_rsae_sha256/384/512 in CertificateVerify. The server signs with ecdsa_secp256r1_sha256.

Left out: TLS 1.2 and older, 0-RTT, PSK and resumption (the client ignores NewSessionTicket, the server sends none), client certificates (the client answers a CertificateRequest with an empty Certificate, the server never asks), rsa_pss_pss_* (no RSA-PSS keys in x509.hpp), record_size_limit, OCSP and SCT.

enum

ETlsEvent

Ethereal::Tls#
C++
enum ETlsEvent : ETL_UINT8
{
    /// @brief  Nothing left to report.
    eEventNone = 0,

    /// @brief  The handshake finished. Data can flow.
    eEventHandshakeDone,

    /// @brief  Application data is waiting in @ref CTlsEngine::Read.
    eEventData,

    /// @brief  The peer sent close_notify.
    eEventClosed,

    /// @brief  The connection failed. See @ref CTlsEngine::Status.
    eEventError
};

What happened during a CTlsEngine::Feed.

function

TlsEventName

Ethereal::Tls#
const char * TlsEventName( const ETlsEvent eEvent ) noexcept;

Readable name of an event.

eEvent
The event.
A static string.
class

CTlsEngine

Ethereal::Tls#
class CTlsEngine final
constructor

CTlsEngine

#
CTlsEngine();

Idle engine.

constructor

CTlsEngine

#
CTlsEngine( CTlsEngine && Other ) noexcept;

Move.

operator

operator=

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

Move assignment.

function

StartClient

#
STlsStatus StartClient( const STlsClientConfig & Config );

Starts a client handshake and queues the ClientHello.

Config
The configuration. Copied, except the trust store, which is used by pointer until the handshake ends.
eTlsBadConfig when the configuration is incomplete, eTlsBadState when the engine was already started, eNotLicensed when the library is not licensed.
function

StartServer

#
STlsStatus StartServer( const STlsServerConfig & Config );

Starts a server handshake. Waits for the ClientHello.

Config
The configuration. Copied.
eTlsBadConfig when the chain is empty, the leaf cannot be parsed or its key does not match the private key, eNotLicensed when the library is not licensed.
function

SetTestHooks

#
void SetTestHooks( const Detail::STlsTestHooks * pHooks ) noexcept;

Installs test hooks. Before the Start call. Tests only.

pHooks
The hooks, kept by pointer. Null removes them.
function

Feed

#
void Feed( std::span< const std::uint8_t > Data );

Hands bytes received from the peer to the engine.

Any split of the stream works. Records are buffered until complete. Each record is processed at once, which can queue output (the handshake flights, a KeyUpdate answer, an alert) and events.

Data
The bytes.
function

PendingOutput

#
std::span< const std::uint8_t > PendingOutput() const noexcept;

Bytes waiting to be sent to the peer.

function

ConsumeOutput

#
void ConsumeOutput( const std::size_t uBytes ) noexcept;

Marks bytes of PendingOutput as sent.

uBytes
How many, from the start.
function

NextEvent

#
ETlsEvent NextEvent() noexcept;

Takes the oldest event not yet read.

eEventNone when there is none.
function

Write

#
STlsStatus Write( std::span< const std::uint8_t > Data );

Encrypts application data into records (up to 16384 bytes each) and queues them.

Data
The data. Empty data queues nothing.
eTlsBadState before the handshake ends, after an error or after Close.
function

Read

#
std::size_t Read( std::span< std::uint8_t > Out ) noexcept;

Copies received application data.

Out
Where to write.
How many bytes were copied.
function

Available

#
std::size_t Available() const noexcept;

Bytes of application data waiting in Read.

function

RequestKeyUpdate

#
STlsStatus RequestKeyUpdate( const bool bAskPeer );

Sends a KeyUpdate and moves the sending side to the next key.

bAskPeer
true asks the peer to update its own key too.
eTlsBadState before the handshake ends.
function

Close

#
STlsStatus Close();

Queues close_notify. Nothing more can be written after it.

eTlsBadState when the engine never started or already failed.
function

IsHandshakeDone

#
bool IsHandshakeDone() const noexcept;

true after the handshake finished.

function

IsPeerClosed

#
bool IsPeerClosed() const noexcept;

true after close_notify arrived.

function

IsLocalClosed

#
bool IsLocalClosed() const noexcept;

true after this side queued close_notify.

function

HasFailed

#
bool HasFailed() const noexcept;

true after a fatal error.

function

IsServer

#
bool IsServer() const noexcept;

true when started as a server.

function

Status

#
const STlsStatus & Status() const noexcept;

The error that stopped the engine, or success.

function

CipherSuite

#
ETlsCipherSuite CipherSuite() const noexcept;

The negotiated suite.

function

Group

#
ETlsGroup Group() const noexcept;

The negotiated group.

function

UsedHelloRetry

#
bool UsedHelloRetry() const noexcept;

true when the handshake went through a HelloRetryRequest.

function

Alpn

#
const std::string & Alpn() const noexcept;

The negotiated ALPN protocol, empty when none.

function

ClientServerName

#
const std::string & ClientServerName() const noexcept;

Server: the name the client sent in SNI. Empty when none.

function

PeerCertificates

#
const std::vector< std::vector< std::uint8_t > > & PeerCertificates() const noexcept;

Client: the chain the server sent, in DER, leaf first.

key_schedule.hpp

#include <ethereal/cpp/tls/key_schedule.hpp>

TLS 1.3 key schedule (RFC 8446 section 7).

HKDF-Expand-Label, Derive-Secret, the chain early secret, handshake secret, master secret, the traffic keys and the Finished keys, over SHA-256 or SHA-384. Without PSK the early secret is HKDF-Extract of zeros. Public so that the test can check every value against RFC 8448.

enum

ETlsHash

Ethereal::Tls#
C++
enum ETlsHash : ETL_UINT8
{
    /// @brief  SHA-256 (32 bytes).
    eTlsHashSha256 = 0,

    /// @brief  SHA-384 (48 bytes).
    eTlsHashSha384
};

The hash of a suite.

struct

SSecret

Ethereal::Tls#
C++
struct   SSecret   final
{
    /// @brief  The bytes. Only the first @ref uSize are valid.
    std::array< std::uint8_t, 48 > aBytes{};

    /// @brief  How many bytes are valid.
    std::size_t uSize = 0;


    /// @brief  The valid bytes.
    ETL_API_NOIGN    std::span< const std::uint8_t > View() const ETL_NOEXCEPT    { return { aBytes.data(), uSize }; }

    /// @brief  The valid bytes, writable.
    ETL_API_NOIGN    std::span< std::uint8_t > Span() ETL_NOEXCEPT                { return { aBytes.data(), uSize }; }

    /// @brief  Wipes the bytes with SecureZero.
    void Wipe() ETL_NOEXCEPT;
};

A secret or a hash of up to 48 bytes, with its size.

struct

STrafficKeys

Ethereal::Tls#
C++
struct   STrafficKeys   final
{
    /// @brief  The AEAD key. Only the first @ref uKeySize are valid.
    std::array< std::uint8_t, 32 > aKey{};

    /// @brief  16 or 32.
    std::size_t uKeySize = 0;

    /// @brief  The 12 byte IV.
    std::array< std::uint8_t, 12 > aIv{};

    /// @brief  Wipes the bytes with SecureZero.
    void Wipe() ETL_NOEXCEPT;
};

Traffic key and IV of one direction.

class

CKeySchedule

Ethereal::Tls#

The key schedule of one connection.

class CKeySchedule final

The secrets live inside the object and are wiped by the destructor and by Reset.

Thread safety: none. One object per connection.
constructor

CKeySchedule

#
CKeySchedule() noexcept = default;

Empty schedule. Call Reset before use.

function

HashSize

#
static std::size_t HashSize( const ETlsHash eHash ) noexcept;

Size of the hash in bytes.

function

SuiteHash

#
static ETlsHash SuiteHash( const ETlsCipherSuite eSuite ) noexcept;

The hash of a suite.

function

SuiteKeySize

#
static std::size_t SuiteKeySize( const ETlsCipherSuite eSuite ) noexcept;

The AEAD key size of a suite (16 or 32).

function

Hash

#
static SSecret Hash( const ETlsHash eHash, std::span< const std::uint8_t > Data ) noexcept;

Hash of a message with the hash of the suite.

eHash
The hash.
Data
The message.
The digest.
function

Extract

#
static SSecret Extract( const ETlsHash eHash, std::span< const std::uint8_t > Salt, std::span< const std::uint8_t > Ikm ) noexcept;

HKDF-Extract.

eHash
The hash.
Salt
The salt.
Ikm
The input key material.
The pseudorandom key.
function

ExpandLabel

#
static bool ExpandLabel( const ETlsHash eHash, std::span< const std::uint8_t > Secret, std::string_view Label, std::span< const std::uint8_t > Context, std::span< std::uint8_t > Out ) noexcept;

HKDF-Expand-Label (RFC 8446 section 7.1).

eHash
The hash.
Secret
The secret.
Label
The label, without the "tls13 " prefix.
Context
The context (a transcript hash or empty).
Out
Where to write. Up to 255 bytes.
false when a size is out of range.
function

DeriveSecret

#
static SSecret DeriveSecret( const ETlsHash eHash, std::span< const std::uint8_t > Secret, std::string_view Label, std::span< const std::uint8_t > TranscriptHash ) noexcept;

Derive-Secret, with the transcript hash already computed.

eHash
The hash.
Secret
The secret.
Label
The label.
TranscriptHash
Hash of the messages.
The derived secret.
function

TrafficKeys

#
static STrafficKeys TrafficKeys( const ETlsCipherSuite eSuite, std::span< const std::uint8_t > Secret ) noexcept;

The key and the IV of a traffic secret.

eSuite
The suite (gives the hash and the key size).
Secret
The traffic secret.
The key and the IV.
function

FinishedKey

#
static SSecret FinishedKey( const ETlsHash eHash, std::span< const std::uint8_t > Base ) noexcept;

finished_key = HKDF-Expand-Label( Base, "finished", "", Hash.length ).

eHash
The hash.
Base
The handshake traffic secret of the side.
The key.
function

FinishedData

#
static SSecret FinishedData( const ETlsHash eHash, std::span< const std::uint8_t > Base, std::span< const std::uint8_t > TranscriptHash ) noexcept;

verify_data = HMAC( finished_key, TranscriptHash ).

eHash
The hash.
Base
The handshake traffic secret of the side.
TranscriptHash
Hash of the messages before the Finished.
The verify_data.
function

NextTrafficSecret

#
static SSecret NextTrafficSecret( const ETlsHash eHash, std::span< const std::uint8_t > Current ) noexcept;

The secret after a KeyUpdate ("traffic upd").

eHash
The hash.
Current
The current traffic secret.
The next secret.
function

Reset

#
void Reset( const ETlsHash eHash ) noexcept;

Wipes everything and computes the early secret (no PSK).

eHash
The hash of the negotiated suite.
function

SetHandshake

#
void SetHandshake( std::span< const std::uint8_t > SharedSecret, std::span< const std::uint8_t > HelloHash ) noexcept;

Handshake secret and the two handshake traffic secrets.

SharedSecret
The (EC)DHE output.
HelloHash
Transcript hash up to the ServerHello.
function

SetApplication

#
void SetApplication( std::span< const std::uint8_t > FinishedHash ) noexcept;

Master secret, the two application traffic secrets and the exporter master secret.

FinishedHash
Transcript hash up to the server Finished.
function

HashKind

#
ETlsHash HashKind() const noexcept

The hash in use.

function

EarlySecret

#
const SSecret & EarlySecret() const noexcept

Early secret.

function

HandshakeSecret

#
const SSecret & HandshakeSecret() const noexcept

Handshake secret.

function

MasterSecret

#
const SSecret & MasterSecret() const noexcept

Master secret.

function

ClientHandshakeTraffic

#
const SSecret & ClientHandshakeTraffic() const noexcept

client_handshake_traffic_secret.

function

ServerHandshakeTraffic

#
const SSecret & ServerHandshakeTraffic() const noexcept

server_handshake_traffic_secret.

function

ClientApplicationTraffic

#
const SSecret & ClientApplicationTraffic() const noexcept

client_application_traffic_secret_0.

function

ServerApplicationTraffic

#
const SSecret & ServerApplicationTraffic() const noexcept

server_application_traffic_secret_0.

function

ExporterMaster

#
const SSecret & ExporterMaster() const noexcept

exporter_master_secret.

function

Wipe

#
void Wipe() noexcept;

Wipes every secret. The engine calls it when the handshake ends: the traffic keys already live in the record layer, and an old traffic secret left here would undo the forward secrecy of a later KeyUpdate.

pem.hpp

#include <ethereal/cpp/tls/pem.hpp>

PEM text (RFC 7468): certificate blocks and P-256 private keys.

A PEM file is base64 between "-----BEGIN label-----" and "-----END label-----" lines. Several blocks can follow each other, with any text between them (comments, the "subject=" lines some tools write). Lines may end in LF or CRLF.

The private key loader reads the two forms of an EC P-256 key: PKCS #8 ("PRIVATE KEY", RFC 5208 / 5958) and SEC1 ("EC PRIVATE KEY", RFC 5915). Encrypted keys are not supported.

function

PemDecodeAll

Ethereal::Tls#
bool PemDecodeAll( std::string_view Text, const char * pLabel, std::vector< std::vector< std::uint8_t > > & Out );

Decodes every PEM block with a given label.

Blocks with another label are skipped. A block whose base64 does not decode, or whose END line is missing, is skipped and makes the return false, but the good blocks are still appended. RFC 1421 header lines ("Proc-Type: ...") make the block fail.

Text
The PEM text.
pLabel
The label, for example "CERTIFICATE". nullptr takes any label.
Out
Receives the decoded blocks, appended in order.
true when at least one block was found and every block with the label decoded.
function

LoadP256PrivateKeyDer

Ethereal::Tls#
bool LoadP256PrivateKeyDer( std::span< const std::uint8_t > Der, Crypto::P256::PrivateKey & Out );

Reads an EC P-256 private key from DER, PKCS #8 or SEC1.

The curve must be named secp256r1 (in the PKCS #8 algorithm or the SEC1 parameters). The scalar must be 32 bytes and in [1, n-1]. When the SEC1 structure carries the public key, it must match the one derived from the scalar. The intermediate copies are wiped.

Der
The PrivateKeyInfo or ECPrivateKey DER.
Out
Receives the scalar. Zeroed on failure.
true when loaded.
function

LoadP256PrivateKeyPem

Ethereal::Tls#
bool LoadP256PrivateKeyPem( std::string_view Text, Crypto::P256::PrivateKey & Out );

Reads an EC P-256 private key from PEM text.

Takes the first "PRIVATE KEY" (PKCS #8) or "EC PRIVATE KEY" (SEC1) block, whichever comes first, and ignores the others (an "EC PARAMETERS" block in front is common). The decoded DER is wiped before returning.

Text
The PEM text.
Out
Receives the scalar. Zeroed on failure.
true when loaded.

stream.hpp

#include <ethereal/cpp/tls/stream.hpp>

Blocking TLS 1.3 stream over a TCP socket.

CTlsStream drives a CTlsEngine over a Network::CTcpSocket: the client connects and runs the handshake, the server runs the handshake on an accepted socket. After that CTlsStream::Send and CTlsStream::Receive carry the data, each with a time limit.

struct

STlsStreamOptions

Ethereal::Tls#
C++
struct   STlsStreamOptions   final
{
    /// @brief  TCP connect (client only).
    ETL_UINT32 uConnectTimeoutMs = 10000;

    /// @brief  The whole handshake.
    ETL_UINT32 uHandshakeTimeoutMs = 15000;

    /// @brief  Each Send or Receive after the handshake.
    ETL_UINT32 uIoTimeoutMs = 30000;
};

Time limits of a stream, in milliseconds.

class

CTlsStream

Ethereal::Tls#

A blocking TLS 1.3 connection.

class CTlsStream final
Thread safety: none. One thread at a time per stream. Different streams share nothing. The padding of this type is intended (alignment). See 'ETL_BEGIN_INTENDED_PADDING'.
constructor

CTlsStream

#
CTlsStream();

Closed stream.

constructor

CTlsStream

#
CTlsStream( CTlsStream && Other ) noexcept;

Move.

operator

operator=

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

Move assignment.

function

Connect

#
STlsStatus Connect( std::string_view Host, const ETL_UINT16 uPort, const STlsClientConfig & Config, const STlsStreamOptions & Options = STlsStreamOptions() );

Connects over TCP and runs the client handshake.

Host
Name or address to connect to. Also the server name when STlsClientConfig::sServerName is empty.
uPort
The port.
Config
The client configuration.
Options
Time limits.
The result. On failure the socket is closed.
function

ConnectOver

#
STlsStatus ConnectOver( Network::CTcpSocket && Socket, const STlsClientConfig & Config, const STlsStreamOptions & Options = STlsStreamOptions() );

Runs the client handshake over a socket already connected.

Socket
The connected socket. The stream takes it.
Config
The client configuration. The server name must be set.
Options
Time limits.
The result. On failure the socket is closed.
function

Accept

#
STlsStatus Accept( Network::CTcpSocket && Socket, const STlsServerConfig & Config, const STlsStreamOptions & Options = STlsStreamOptions() );

Runs the server handshake over an accepted socket.

Socket
The accepted socket. The stream takes it.
Config
The server configuration.
Options
Time limits.
The result. On failure the socket is closed.
function

Send

#
STlsStatus Send( std::span< const std::uint8_t > Data );

Encrypts and sends all of the data.

Data
The data.
The result.
function

Receive

#
STlsStatus Receive( std::span< std::uint8_t > Buffer, std::size_t & uReceived );

Waits for application data and copies what is available.

Buffer
Where to write.
uReceived
How many bytes were written (at least 1 on success).
eTlsClosed with 0 bytes when the peer sent close_notify, eTlsTruncated when TCP closed without it.
function

Close

#
STlsStatus Close();

Sends close_notify and closes the socket.

The result of sending close_notify.
function

IsOpen

#
bool IsOpen() const noexcept;

true between a successful handshake and Close.

function

Engine

#
const CTlsEngine & Engine() const noexcept

The engine, for the negotiated parameters.

function

Engine

#
CTlsEngine & Engine() noexcept

The engine, for test hooks and KeyUpdate.

function

Socket

#
Network::CTcpSocket & Socket() noexcept

The socket.

function

RequestKeyUpdate

#
STlsStatus RequestKeyUpdate( const bool bAskPeer );

Sends a KeyUpdate at once.

bAskPeer
true asks the peer to update too.
The result.

tls_common.hpp

#include <ethereal/cpp/tls/tls_common.hpp>

TLS 1.3 shared types: alerts, cipher suites, groups, errors and the client and server configurations.

TLS 1.3 only (RFC 8446). No TLS 1.2 or older, no 0-RTT, no PSK or session resumption, no client certificates, no record_size_limit. The engine is in engine.hpp, the blocking stream over TCP in stream.hpp, the key schedule in key_schedule.hpp. Certificates and trust stores come from x509.hpp and pem.hpp.

enum

ETlsAlert

Ethereal::Tls#
C++
enum ETlsAlert : ETL_UINT8
{
    /// @brief  Orderly close of one direction.
    eAlertCloseNotify = 0,

    /// @brief  A message arrived where the protocol does not allow it.
    eAlertUnexpectedMessage = 10,

    /// @brief  A record failed authentication.
    eAlertBadRecordMac = 20,

    /// @brief  A record is longer than the protocol allows.
    eAlertRecordOverflow = 22,

    /// @brief  No acceptable set of parameters.
    eAlertHandshakeFailure = 40,

    /// @brief  The certificate is corrupt or failed a check.
    eAlertBadCertificate = 42,

    /// @brief  The certificate is of an unsupported type.
    eAlertUnsupportedCertificate = 43,

    /// @brief  The certificate was revoked.
    eAlertCertificateRevoked = 44,

    /// @brief  The certificate is expired or not yet valid.
    eAlertCertificateExpired = 45,

    /// @brief  Some other certificate problem.
    eAlertCertificateUnknown = 46,

    /// @brief  A field is out of range or inconsistent.
    eAlertIllegalParameter = 47,

    /// @brief  The chain does not end at a trusted root.
    eAlertUnknownCa = 48,

    /// @brief  Access denied.
    eAlertAccessDenied = 49,

    /// @brief  A message could not be parsed.
    eAlertDecodeError = 50,

    /// @brief  A signature or a Finished check failed.
    eAlertDecryptError = 51,

    /// @brief  The peer does not speak TLS 1.3.
    eAlertProtocolVersion = 70,

    /// @brief  The parameters are too weak.
    eAlertInsufficientSecurity = 71,

    /// @brief  Local failure unrelated to the peer.
    eAlertInternalError = 80,

    /// @brief  Inappropriate fallback.
    eAlertInappropriateFallback = 86,

    /// @brief  The peer gave up, normally followed by close_notify.
    eAlertUserCanceled = 90,

    /// @brief  A mandatory extension is missing.
    eAlertMissingExtension = 109,

    /// @brief  An extension the other side never offered.
    eAlertUnsupportedExtension = 110,

    /// @brief  Unknown server name.
    eAlertUnrecognizedName = 112,

    /// @brief  Bad OCSP response.
    eAlertBadCertificateStatusResponse = 113,

    /// @brief  Unknown PSK identity.
    eAlertUnknownPskIdentity = 115,

    /// @brief  The server requires a client certificate.
    eAlertCertificateRequired = 116,

    /// @brief  No common ALPN protocol.
    eAlertNoApplicationProtocol = 120,

    /// @brief  No alert (not a wire value).
    eAlertNone = 255
};

Alert description codes. Any other byte value can arrive from the peer and is kept as is.

function

AlertName

Ethereal::Tls#
const char * AlertName( const ETlsAlert eAlert ) noexcept;

Readable name of an alert, as written in the RFC.

eAlert
The alert code.
A static string, "unknown_alert" for codes outside the list.
enum

ETlsCipherSuite

Ethereal::Tls#
C++
enum ETlsCipherSuite : ETL_UINT16
{
    /// @brief  No suite.
    eSuiteNone = 0,

    /// @brief  TLS_AES_128_GCM_SHA256, mandatory in RFC 8446.
    eSuiteAes128GcmSha256 = 0x1301,

    /// @brief  TLS_AES_256_GCM_SHA384.
    eSuiteAes256GcmSha384 = 0x1302,

    /// @brief  TLS_CHACHA20_POLY1305_SHA256.
    eSuiteChaCha20Poly1305Sha256 = 0x1303
};

The TLS 1.3 cipher suites this library implements.

function

CipherSuiteName

Ethereal::Tls#
const char * CipherSuiteName( const ETlsCipherSuite eSuite ) noexcept;

IANA name of a suite ("TLS_AES_128_GCM_SHA256").

eSuite
The suite.
A static string, "unknown" for other values.
enum

ETlsGroup

Ethereal::Tls#
C++
enum ETlsGroup : ETL_UINT16
{
    /// @brief  No group.
    eGroupNone = 0,

    /// @brief  NIST P-256 (secp256r1).
    eGroupSecp256r1 = 0x0017,

    /// @brief  X25519.
    eGroupX25519 = 0x001d
};

The key exchange groups this library implements.

function

GroupName

Ethereal::Tls#
const char * GroupName( const ETlsGroup eGroup ) noexcept;

IANA name of a group ("x25519", "secp256r1").

eGroup
The group.
A static string, "unknown" for other values.
enum

ETlsSignatureScheme

Ethereal::Tls#
C++
enum ETlsSignatureScheme : ETL_UINT16
{
    /// @brief  RSASSA-PKCS1-v1_5 with SHA-256 (certificates only).
    eSchemeRsaPkcs1Sha256 = 0x0401,

    /// @brief  RSASSA-PKCS1-v1_5 with SHA-384 (certificates only).
    eSchemeRsaPkcs1Sha384 = 0x0501,

    /// @brief  RSASSA-PKCS1-v1_5 with SHA-512 (certificates only).
    eSchemeRsaPkcs1Sha512 = 0x0601,

    /// @brief  ECDSA over P-256 with SHA-256.
    eSchemeEcdsaSecp256r1Sha256 = 0x0403,

    /// @brief  ECDSA over P-384 with SHA-384.
    eSchemeEcdsaSecp384r1Sha384 = 0x0503,

    /// @brief  RSASSA-PSS with an rsaEncryption key and SHA-256.
    eSchemeRsaPssRsaeSha256 = 0x0804,

    /// @brief  RSASSA-PSS with an rsaEncryption key and SHA-384.
    eSchemeRsaPssRsaeSha384 = 0x0805,

    /// @brief  RSASSA-PSS with an rsaEncryption key and SHA-512.
    eSchemeRsaPssRsaeSha512 = 0x0806
};

Signature schemes (RFC 8446 section 4.2.3) used by this library.

enum

ETlsError

Ethereal::Tls#
C++
enum ETlsError : ETL_UINT8
{
    /// @brief  Success.
    eTlsOk = 0,

    /// @brief  The peer sent close_notify. Orderly end of the data.
    eTlsClosed,

    /// @brief  The peer sent a fatal alert (see @ref STlsStatus::eAlert).
    eTlsAlertReceived,

    /// @brief  This side found a protocol violation and sent the alert in
    ///          @ref STlsStatus::eAlert.
    eTlsProtocolError,

    /// @brief  The certificate chain was rejected (see @ref STlsStatus::eCert).
    eTlsCertificateRejected,

    /// @brief  The leaf public key does not match the configured pin.
    eTlsPinMismatch,

    /// @brief  The TCP layer failed (see @ref STlsStatus::Transport).
    eTlsTransport,

    /// @brief  The time limit expired.
    eTlsTimeout,

    /// @brief  TCP closed without close_notify. Data may be truncated.
    eTlsTruncated,

    /// @brief  The configuration is incomplete or inconsistent.
    eTlsBadConfig,

    /// @brief  Call not valid in the current state.
    eTlsBadState,

    /// @brief  Local failure (random source, signing).
    eTlsInternal,

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

What ended an operation.

function

TlsErrorName

Ethereal::Tls#
const char * TlsErrorName( const ETlsError eError ) noexcept;

Readable name of an error code.

eError
The error code.
A static string.
struct

STlsStatus

Ethereal::Tls#
C++
struct   STlsStatus   final
{
    /// @brief  The error code.
    ETlsError eError = eTlsOk;

    /// @brief  The alert sent or received, @ref eAlertNone when none.
    ETlsAlert eAlert = eAlertNone;

    /// @brief  The certificate status when the chain was rejected.
    ECertStatus eCert = eCertOk;

    /// @brief  The TCP result when the transport failed.
    Network::STcpResult Transport;


    /// @brief  true on success.
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == eTlsOk; }

    /// @brief  true on success.
    ETL_API_NOIGN    explicit operator bool() const ETL_NOEXCEPT    { return IsOk(); }

    ///
    /// ToString
    ///
    /// @brief  One line description ("protocol_error: sent bad_record_mac").
    ///
    /// @return  The description.
    ///
    ETL_API_NOIGN    std::string ToString() const;
};

Detailed result of a TLS operation.

enum

ETlsVerifyMode

Ethereal::Tls#
C++
enum ETlsVerifyMode : ETL_UINT8
{
    /// @brief  Chain up to the trust store, validity dates and host name. The
    ///          pin, when set, is checked too. The default.
    eVerifyChain = 0,

    /// @brief  Only the pin: the SHA-256 of the leaf SubjectPublicKeyInfo must
    ///          match. For a server with a self-signed certificate whose key is
    ///          known in advance. Requires the pin.
    eVerifyPinOnly,

    /// @brief  No authentication at all. Anyone in the path can impersonate the
    ///          server. For tests only.
    eVerifyNone_InsecureTestOnly
};

How the client authenticates the server.

struct

STlsClientConfig

Ethereal::Tls#
C++
struct   STlsClientConfig   final
{
    /// @brief  Trusted roots. Required by @ref eVerifyChain. Not owned: it must
    ///          live while the connection is in the handshake.
    const CTrustStore * pTrustStore = nullptr;

    /// @brief  Server name: sent in SNI (unless it is an IP literal) and checked
    ///          against the certificate. The blocking stream fills it with the
    ///          host when empty.
    std::string sServerName;

    /// @brief  How the server is authenticated.
    ETlsVerifyMode eVerify = eVerifyChain;

    /// @brief  true when @ref aPinSha256 must be checked.
    bool bUsePin = false;

    /// @brief  SHA-256 of the DER SubjectPublicKeyInfo of the leaf.
    std::array< std::uint8_t, 32 > aPinSha256{};

    /// @brief  Suites to offer, in order of preference.
    std::vector< ETlsCipherSuite > vCipherSuites{ eSuiteAes128GcmSha256,
                                                  eSuiteChaCha20Poly1305Sha256,
                                                  eSuiteAes256GcmSha384 };

    /// @brief  Groups to offer, in order of preference. A key share is sent for
    ///          the first one only. The server can ask for another with a
    ///          HelloRetryRequest.
    std::vector< ETlsGroup > vGroups{ eGroupX25519, eGroupSecp256r1 };

    /// @brief  ALPN protocols to offer ("http/1.1"). Empty: no ALPN.
    std::vector< std::string > vAlpn;

    /// @brief  Time for the certificate dates, in seconds since the Epoch.
    ///          0: the wall clock.
    std::int64_t iUnixTime = 0;

    /// @brief  Maximum chain depth accepted.
    std::size_t uMaxChainDepth = 8;
};

Client configuration.

struct

STlsServerConfig

Ethereal::Tls#
C++
struct   STlsServerConfig   final
{
    /// @brief  The chain in DER, leaf first.
    std::vector< std::vector< std::uint8_t > > vCertificateChainDer;

    /// @brief  The P-256 private key of the leaf.
    Crypto::P256::PrivateKey PrivateKey{};

    /// @brief  Suites accepted, in order of preference.
    std::vector< ETlsCipherSuite > vCipherSuites{ eSuiteAes128GcmSha256,
                                                  eSuiteChaCha20Poly1305Sha256,
                                                  eSuiteAes256GcmSha384 };

    /// @brief  Groups accepted, in order of preference.
    std::vector< ETlsGroup > vGroups{ eGroupX25519, eGroupSecp256r1 };

    /// @brief  ALPN protocols accepted, in order of preference. Empty: ALPN is
    ///          ignored. Not empty and no overlap with the client list: the
    ///          handshake fails with no_application_protocol.
    std::vector< std::string > vAlpn;


    /// @brief  Wipes the private key.
    ~STlsServerConfig();

    /// @brief  Default constructor.
    STlsServerConfig() = default;

    /// @brief  Copy.
    STlsServerConfig( const STlsServerConfig & ) = default;

    /// @brief  Copy assignment.
    STlsServerConfig & operator=( const STlsServerConfig & ) = default;


    ///
    /// LoadPem
    ///
    /// @brief  Loads the chain and the key from PEM text.
    ///
    /// @param ChainPem        The CERTIFICATE blocks, leaf first.
    /// @param KeyPem        The P-256 private key (SEC 1 or PKCS#8).
    ///
    /// @return  false when a part is missing or invalid. The object is then
    ///           left without chain.
    ///
    ETL_API_NOIGN    bool LoadPem( std::string_view ChainPem, std::string_view KeyPem );
};

Server configuration.

The certificate must carry a P-256 key. The server signs with ecdsa_secp256r1_sha256 only.

x509.hpp

#include <ethereal/cpp/tls/x509.hpp>

X.509 v3 certificates (RFC 5280): parsing, the trust store, chain verification and host name matching.

What a TLS 1.3 client or server needs to decide whether the peer certificate chain is acceptable. Parsing is strict DER. Chains are built from the leaf up to a certificate of the trust store, matching issuer and subject byte for byte, and every link has its signature checked.

Supported signatures: sha256/384/512WithRSAEncryption, RSASSA-PSS with SHA-256/384/512 and MGF1 of the same hash, and ecdsa-with-SHA256/384/512. Supported keys: RSA 2048 to 8192 bits, EC P-256 and P-384. A certificate with another key type does not parse (eCertUnsupported). A certificate signed with another algorithm parses, and only fails when its signature is checked, so old roots signed with SHA-1 still work as anchors.

Host names follow RFC 9525: subjectAltName only when it exists, wildcard only as the whole leftmost label, IP literals only against iPAddress entries. See CCertificate::MatchesHost.

enum

ECertStatus

Ethereal::Tls#
C++
enum ECertStatus : ETL_UINT8
{
    /// @brief  Accepted.
    eCertOk = 0,

    /// @brief  The DER does not follow the X.509 or DER rules.
    eCertMalformed,

    /// @brief  Valid DER with a key type, curve or signature algorithm this code
    ///          does not support.
    eCertUnsupported,

    /// @brief  A certificate of the path is past its notAfter.
    eCertExpired,

    /// @brief  A certificate of the path is before its notBefore.
    eCertNotYetValid,

    /// @brief  No certificate of the chain or of the trust store issued one link.
    eCertUnknownIssuer,

    /// @brief  An issuer was found by name, but the signature does not verify.
    eCertBadSignature,

    /// @brief  The leaf does not match the requested host name.
    eCertHostMismatch,

    /// @brief  An issuing certificate is not a CA (basicConstraints).
    eCertNotCa,

    /// @brief  keyUsage or extKeyUsage forbids the use (keyCertSign on an issuer,
    ///          digitalSignature or serverAuth on the leaf).
    eCertBadKeyUsage,

    /// @brief  The path is longer than the maximum depth or than a pathLen
    ///          constraint allows.
    eCertPathTooLong,

    /// @brief  A certificate of the path has a critical extension this code does
    ///          not process.
    eCertUnknownCriticalExtension,

    /// @brief  The chain has no certificate.
    eCertEmptyChain
};

Result of parsing a certificate or verifying a chain.

When a chain has several faults, the first one found wins. The order is: parsing, path building (issuer, signature, depth), then each certificate of the path from the leaf up (critical extensions, validity, CA flag, key usage, path length), then the host name.

function

CertStatusName

Ethereal::Tls#
const char * CertStatusName( ECertStatus eStatus ) noexcept;

Readable name of an ECertStatus ("ok", "expired", ...).

eStatus
The status.
A static string. "unknown" for a value out of range.
enum

EPublicKeyType

Ethereal::Tls#
C++
enum EPublicKeyType : ETL_UINT8
{
    /// @brief  No key loaded.
    eKeyNone = 0,

    /// @brief  RSA, 2048 to 8192 bits.
    eKeyRsa,

    /// @brief  EC on P-256 (secp256r1).
    eKeyEcP256,

    /// @brief  EC on P-384 (secp384r1).
    eKeyEcP384
};

Type of a certificate public key.

enum

ESignatureAlgorithm

Ethereal::Tls#
C++
enum ESignatureAlgorithm : ETL_UINT8
{
    /// @brief  None parsed, or an algorithm this code does not support.
    eSigUnsupported = 0,

    /// @brief  sha256WithRSAEncryption.
    eSigRsaPkcs1Sha256,

    /// @brief  sha384WithRSAEncryption.
    eSigRsaPkcs1Sha384,

    /// @brief  sha512WithRSAEncryption.
    eSigRsaPkcs1Sha512,

    /// @brief  RSASSA-PSS with SHA-256 and MGF1-SHA-256.
    eSigRsaPssSha256,

    /// @brief  RSASSA-PSS with SHA-384 and MGF1-SHA-384.
    eSigRsaPssSha384,

    /// @brief  RSASSA-PSS with SHA-512 and MGF1-SHA-512.
    eSigRsaPssSha512,

    /// @brief  ecdsa-with-SHA256.
    eSigEcdsaSha256,

    /// @brief  ecdsa-with-SHA384.
    eSigEcdsaSha384,

    /// @brief  ecdsa-with-SHA512.
    eSigEcdsaSha512
};

Signature algorithm of a certificate.

class

CPublicKey

Ethereal::Tls#

A certificate public key (RSA or EC) that verifies signatures.

class CPublicKey

Holds the key bytes only. The RSA verification loads a Crypto::CRsaPublicKey on the stack for each call, which keeps a trust store of a few hundred roots small.

Copyable. The const methods are safe from several threads.
constructor

CPublicKey

#
CPublicKey() noexcept;

Constructor. No key.

function

ParseSubjectPublicKeyInfo

#
ECertStatus ParseSubjectPublicKeyInfo( std::span< const std::uint8_t > Der );

Loads the key from a DER SubjectPublicKeyInfo.

Accepts rsaEncryption (NULL parameters, modulus 2048 to 8192 bits) and id-ecPublicKey with secp256r1 or secp384r1 and an uncompressed point on the curve. Anything else is eCertUnsupported. On failure the key is left empty.

Der
The whole SubjectPublicKeyInfo element, nothing after it.
eCertOk, eCertMalformed or eCertUnsupported.
function

Type

#
EPublicKeyType Type() const noexcept

The key type.

function

RsaModulusBits

#
std::size_t RsaModulusBits() const noexcept

RSA modulus size in bits, 0 for other types.

function

RsaModulus

#
std::span< const std::uint8_t > RsaModulus() const noexcept

RSA modulus, big-endian, without the DER sign byte. Empty for other types.

function

RsaExponent

#
std::span< const std::uint8_t > RsaExponent() const noexcept

RSA public exponent, big-endian. Empty for other types.

function

EcPoint

#
std::span< const std::uint8_t > EcPoint() const noexcept

EC point, 0x04 || X || Y (65 or 97 bytes). Empty for other types.

function

VerifyEcdsaDer

#
bool VerifyEcdsaDer( std::span< const std::uint8_t > Digest, std::span< const std::uint8_t > DerSig ) const;

Verifies a DER ECDSA signature, on P-256 or P-384 as the key says.

Digest
The digest already computed by the caller.
DerSig
The ECDSA-Sig-Value.
true when valid. false for a non EC key.
function

VerifyRsaPkcs1v15

#
bool VerifyRsaPkcs1v15( Crypto::ERsaHash eHash, std::span< const std::uint8_t > Digest, std::span< const std::uint8_t > Sig ) const;

Verifies an RSASSA-PKCS1-v1_5 signature.

eHash
The hash the digest was made with.
Digest
The digest.
Sig
The signature, exactly the modulus size.
true when valid. false for a non RSA key.
function

VerifyRsaPss

#
bool VerifyRsaPss( Crypto::ERsaHash eHash, std::span< const std::uint8_t > Digest, std::span< const std::uint8_t > Sig, std::size_t uSaltSize ) const;

Verifies an RSASSA-PSS signature, MGF1 with the same hash.

eHash
The hash of the digest and of MGF1.
Digest
The digest.
Sig
The signature.
uSaltSize
The salt size, or Crypto::CRsaPublicKey::PSS_SALT_ANY.
true when valid. false for a non RSA key.
function

Clear

#
void Clear() noexcept;

Drops the key.

enum

EKeyUsageBit

Ethereal::Tls#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Certificate
///=============================================================================


/// @brief  keyUsage bits (RFC 5280 section 4.2.1.3), as bit masks.
enum EKeyUsageBit : ETL_UINT16
{
    /// @brief  digitalSignature (bit 0).
    eKuDigitalSignature    = 0x0001,

    /// @brief  nonRepudiation / contentCommitment (bit 1).
    eKuNonRepudiation    = 0x0002,

    /// @brief  keyEncipherment (bit 2).
    eKuKeyEncipherment    = 0x0004,

    /// @brief  dataEncipherment (bit 3).
    eKuDataEncipherment    = 0x0008,

    /// @brief  keyAgreement (bit 4).
    eKuKeyAgreement        = 0x0010,

    /// @brief  keyCertSign (bit 5).
    eKuKeyCertSign        = 0x0020,

    /// @brief  cRLSign (bit 6).
    eKuCrlSign            = 0x0040,

    /// @brief  encipherOnly (bit 7).
    eKuEncipherOnly        = 0x0080,

    /// @brief  decipherOnly (bit 8).
    eKuDecipherOnly        = 0x0100
};
class

CCertificate

Ethereal::Tls#

A parsed X.509 certificate.

class CCertificate

Keeps its own copy of the DER, and every span it returns points into that copy. Copying the object copies the DER.

The const methods are safe from several threads.
constructor

CCertificate

#
CCertificate() noexcept;

Constructor. Nothing parsed.

function

Parse

#
bool Parse( std::span< const std::uint8_t > Der );

Parses one DER certificate.

Copies the DER first. The input must be exactly one Certificate, with nothing after it. On failure the object is empty and Status says why.

Der
The certificate DER.
true when parsed (Status() == eCertOk).
function

Clear

#
void Clear() noexcept;

Drops the parsed certificate.

function

Status

#
ECertStatus Status() const noexcept

Result of the last Parse: eCertOk, eCertMalformed or eCertUnsupported. eCertMalformed before any Parse.

function

IsValid

#
bool IsValid() const noexcept

true when the last Parse succeeded.

function

Der

#
std::span< const std::uint8_t > Der() const noexcept

The whole certificate DER.

function

TbsDer

#
std::span< const std::uint8_t > TbsDer() const noexcept

The tbsCertificate element (what the signature covers).

function

SubjectPublicKeyInfoDer

#
std::span< const std::uint8_t > SubjectPublicKeyInfoDer() const noexcept

The SubjectPublicKeyInfo element.

function

SubjectDer

#
std::span< const std::uint8_t > SubjectDer() const noexcept

The subject Name element, compared byte for byte to build chains.

function

IssuerDer

#
std::span< const std::uint8_t > IssuerDer() const noexcept

The issuer Name element.

function

SerialNumber

#
std::span< const std::uint8_t > SerialNumber() const noexcept

The serial number INTEGER contents (two's complement, big-endian).

function

SignatureValue

#
std::span< const std::uint8_t > SignatureValue() const noexcept

The signature bits (BIT STRING contents without the unused bits byte).

function

PublicKey

#
const CPublicKey & PublicKey() const noexcept

The subject public key.

function

Version

#
unsigned Version() const noexcept

X.509 version: 1, 2 or 3.

function

NotBefore

#
std::int64_t NotBefore() const noexcept

notBefore, in seconds since the Unix epoch (UTC).

function

NotAfter

#
std::int64_t NotAfter() const noexcept

notAfter, in seconds since the Unix epoch (UTC).

function

SignatureAlgorithm

#
ESignatureAlgorithm SignatureAlgorithm() const noexcept

The signature algorithm. eSigUnsupported when the certificate is signed with something this code does not verify (SHA-1, MD5, ...).

function

PssSaltSize

#
std::size_t PssSaltSize() const noexcept

PSS salt size from the parameters (20 when absent). 0 for other algorithms.

function

IsCa

#
bool IsCa() const noexcept

true when basicConstraints is present with cA TRUE.

function

HasBasicConstraints

#
bool HasBasicConstraints() const noexcept

true when the basicConstraints extension is present.

function

PathLenConstraint

#
int PathLenConstraint() const noexcept

pathLenConstraint, or -1 when absent.

function

HasKeyUsage

#
bool HasKeyUsage() const noexcept

true when the keyUsage extension is present.

function

KeyUsage

#
ETL_UINT16 KeyUsage() const noexcept

keyUsage bits (EKeyUsageBit). 0 when absent.

function

HasExtKeyUsage

#
bool HasExtKeyUsage() const noexcept

true when the extKeyUsage extension is present.

function

AllowsServerAuth

#
bool AllowsServerAuth() const noexcept

true when extKeyUsage is absent, or lists serverAuth or anyExtendedKeyUsage.

function

AllowsClientAuth

#
bool AllowsClientAuth() const noexcept

true when extKeyUsage is absent, or lists clientAuth or anyExtendedKeyUsage.

function

HasSubjectAltName

#
bool HasSubjectAltName() const noexcept

true when the subjectAltName extension is present.

function

DnsNames

#
const std::vector< std::string > & DnsNames() const noexcept

The dNSName entries of subjectAltName, as written.

function

IpAddresses

#
const std::vector< std::vector< std::uint8_t > > & IpAddresses() const noexcept

The iPAddress entries of subjectAltName (4 or 16 bytes each).

function

SubjectCommonName

#
const std::string & SubjectCommonName() const noexcept

The last commonName of the subject, for diagnostics. Empty when none.

function

IssuerCommonName

#
const std::string & IssuerCommonName() const noexcept

The last commonName of the issuer, for diagnostics. Empty when none.

function

HasUnknownCriticalExtension

#
bool HasUnknownCriticalExtension() const noexcept

true when the certificate has a critical extension this code does not process. Such a certificate parses, and a chain that uses it fails.

function

IsSelfIssued

#
bool IsSelfIssued() const noexcept;

true when subject and issuer are byte for byte equal.

function

IsValidAt

#
ECertStatus IsValidAt( std::int64_t iUnixTime ) const noexcept;

Checks the validity period.

iUnixTime
Seconds since the Unix epoch (UTC).
eCertOk, eCertExpired or eCertNotYetValid. Both bounds are inclusive, as RFC 5280 says.
function

VerifySignedBy

#
ECertStatus VerifySignedBy( const CPublicKey & IssuerKey ) const;

Checks the certificate signature with an issuer key.

IssuerKey
The public key of the issuer.
eCertOk, eCertBadSignature, or eCertUnsupported when the algorithm is not supported.
function

MatchesHost

#
bool MatchesHost( const char * pHost ) const;

Checks a host name or IP literal against the certificate.

Policy (RFC 9525):

  • IP literal (IPv4 dotted quad, or IPv6, brackets allowed): only iPAddress entries of subjectAltName, never dNSName nor CN.
  • DNS name, with subjectAltName present: only its dNSName entries, the CN is ignored.
  • DNS name, no subjectAltName extension at all: the subject commonName entries, with the same rules. This is a compatibility choice for old internal certificates. Browsers no longer do it.
  • ASCII case is ignored. One final dot on either side is ignored.
  • A wildcard is only "" as the whole leftmost label, and matches exactly one non empty label: ".example.com" matches "a.example.com", not "a.b.example.com" nor "example.com". Partial labels ("f*.example.com") never match. A wildcard pattern needs at least three labels, so ".com" never matches. No public suffix list: ".co.uk" is accepted.
  • Internationalized names must arrive as A-labels ("xn--").
pHost
The host name. nullptr or empty never matches.
true when it matches.
class

CTrustStore

Ethereal::Tls#
class CTrustStore
constructor

CTrustStore

#
CTrustStore() noexcept;

Constructor. Empty store.

function

AddPem

#
std::size_t AddPem( std::string_view Text );

Adds every "CERTIFICATE" block of a PEM text.

Text
The PEM text. Anything between blocks is ignored.
How many certificates were added. Blocks that fail to decode or to parse are counted in SkippedCount, duplicates are not added again.
function

AddDer

#
bool AddDer( std::span< const std::uint8_t > Der );

Adds one DER certificate.

Der
The certificate.
true when added. false when it does not parse (counted in SkippedCount) or is already in the store.
function

LoadSystem

#
std::size_t LoadSystem();

Adds the root certificates of the operating system.

Linux: the file named by SSL_CERT_FILE when set and readable, else the first that exists of /etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt, /etc/ssl/ca-bundle.pem, /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem and /etc/ssl/cert.pem. macOS: SSL_CERT_FILE, else /etc/ssl/cert.pem. Windows: the "ROOT" system store through crypt32. Windows only lists the roots already downloaded by its automatic root update.

How many certificates were added.
function

Count

#
std::size_t Count() const noexcept

Number of certificates in the store.

function

SkippedCount

#
std::size_t SkippedCount() const noexcept

Number of certificates that failed to decode or parse since the last Clear.

function

At

#
const CCertificate & At( std::size_t uIndex ) const noexcept

The certificate at an index (0 to Count() - 1).

function

Clear

#
void Clear() noexcept;

Empties the store and the skipped counter.

function

ContainsDer

#
bool ContainsDer( std::span< const std::uint8_t > Der ) const noexcept;

Checks whether this exact DER is in the store.

Der
The certificate DER.
true when present.
struct

SVerifyOptions

Ethereal::Tls#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Chain verification
///=============================================================================


/// @brief  Options of VerifyChain.
struct   SVerifyOptions   final
{
    /// @brief  Host name or IP literal the leaf must match. nullptr skips the check.
    const char * pHostName = nullptr;

    /// @brief  Verification time in seconds since the Unix epoch. 0 means now.
    std::int64_t iUnixTime = 0;

    /// @brief  Largest path, in certificates, counting the leaf and the anchor.
    std::size_t uMaxDepth = 8;

    /// @brief  Checks the leaf for client authentication (extKeyUsage clientAuth)
    ///          instead of server authentication. For a server that asks for a
    ///          client certificate.
    bool bClientCertificate = false;
};
function

VerifyChain

Ethereal::Tls#
ECertStatus VerifyChain( std::span< const std::span< const std::uint8_t > > ChainDer, const CTrustStore & Trust, const SVerifyOptions & Options, CCertificate & OutLeaf );

Verifies a certificate chain against a trust store.

Builds a path from the leaf to a certificate of the store. Issuers are looked up first in the store, then among the other certificates sent, by subject equal byte for byte to the issuer, and each link must have a valid signature. When several paths exist they are tried in turn, and the first fully valid one wins. A chain that already carries the root works, and so does one without it. A self-issued leaf that is itself in the store is accepted (pinned certificate).

Then every certificate of the path: no unknown critical extension, valid at the time asked. Issuers (the anchor included) must not refuse the role: when basicConstraints is present it must say cA, when keyUsage is present it must have keyCertSign, and pathLen is honored. Intermediates must have basicConstraints with cA. When extKeyUsage is present on any certificate it must allow serverAuth (or clientAuth, see the options). The leaf keyUsage, when present, must have digitalSignature. Finally the host name.

ChainDer
The chain, leaf first, as received.
Trust
The trust store.
Options
Host name, time and depth.
OutLeaf
Receives the parsed leaf, also on failure when it parsed.
eCertOk, or the first fault found.
function

ParseIpLiteral

Ethereal::Tls#
bool ParseIpLiteral( const char * pText, std::array< std::uint8_t, 16 > & aOut, std::size_t & uSizeOut ) noexcept;

Parses an IPv4 dotted quad or an IPv6 literal.

IPv4: four decimal parts 0 to 255, no leading zero. IPv6: RFC 4291 text form, "::" once at most, an IPv4 tail allowed, brackets allowed, zone ("%eth0") refused.

pText
The text.
aOut
Receives the address bytes.
uSizeOut
Receives 4 or 16.
true when pText is an IP literal.