Kleidos API Search

In development. It changes without notice.

Topic

One-Time Codes

Time-based one-time codes (RFC 6238): making one from the secret in the vault, and the gate that refuses when the clock cannot be trusted.

A code is made in five steps:

  1. the gate issues the time, or refuses;
  2. the time step is that time divided by 30 or 60 s;
  3. HMAC-SHA1, or HMAC-SHA256, of the step under the decrypted secret;
  4. dynamic truncation (RFC 4226);
  5. the remainder of 10 to the power of 6 or 8, with its leading zeros.

The gate is the only source of the time a code is made from, so no screen can make a code without asking it. It asks that the setting is on (it is by default on the boards with a clock chip, and off on the others), that the clock is set and, on a board without a clock chip, that a source which knows the time to the second set it since the last deep sleep: a network time answer, the portal's browser or a GPS receiver. A time set by hand does not count there, and enough light sleep after the sync spends it.

Codes are made by a worker of their own, so one never waits behind an unlock.

See also
Vault Storage, Clock & Time Zone, Network Services

Files

file src/totp/code_clock.h
The time base a one-time code is made from, issued only by the gate.
file src/totp/totp_code.h
The one place a stored TOTP's parameters are judged, its current code produced and that code turned into text.
file src/totp/totp_gate.cpp
The TOTP gate: implementation of totp_gate.h.
file src/totp/totp_gate.h
The one gate every one-time code goes through: the 2FA codes setting and whether the clock is good enough for a code.
file src/totp/totp_gate_types.h
The TOTP gate's verdicts and its rule, pure and host-tested.
file src/totp/totp_generator.h
RFC 6238 time-based one-time password generator (HMAC-SHA1 / HMAC-SHA256).
file src/totp/totp_task.h
Off-core TOTP worker so HMAC work never jitters the UI render ticks.

Classes

class kleidos::totp::CodeClock
Proof that the TOTP gate passed: the Unix time a code is made from. More about kleidos::totp::CodeClock
struct kleidos::totp::CodeSeed
Everything currentCode needs from a stored entry, as a view. More about kleidos::totp::CodeSeed
struct kleidos::totp::Verdict
The gate's answer: the verdict, and the time base when it is Ready. More about kleidos::totp::Verdict
class kleidos::TotpGenerator
Stateless RFC 6238 TOTP generator. More about kleidos::TotpGenerator

Typedefs

usingkleidos::totp::CodeText
Text of one code: up to kDigits8 characters plus the terminator.

Enumerations

enum class kleidos::totp::Gate : uint8_t { kleidos::totp::Gate::Ready , kleidos::totp::Gate::Disabled , kleidos::totp::Gate::ClockUnset , kleidos::totp::Gate::NeedsSync }
enum class kleidos::TotpAlgorithm : uint8_t { kleidos::TotpAlgorithm::Sha1 , kleidos::TotpAlgorithm::Sha256 }
HMAC hash function driving the RFC 6238 pipeline. More about kleidos::TotpAlgorithm

Functions

constexpr CodeClockkleidos::totp::codeClockForTest (uint64_t epoch, uint16_t msIntoSecond=0)
Native tests only: a time base for a fixed epoch (an RFC vector's).
constexpr uint8_tkleidos::totp::clampDigits (uint32_t digits)
Clamp a stored digit count to the only two legal RFC 6238 values.
constexpr uint16_tkleidos::totp::clampPeriod (uint32_t period)
Clamp a stored time step to the only two legal RFC 6238 values.
constexpr boolkleidos::totp::isValidDigits (uint32_t digits)
Whether a write may set this digit count.
constexpr boolkleidos::totp::isValidPeriod (uint32_t period)
Whether a write may set this time step.
voidkleidos::totp::formatCode (uint32_t code, uint32_t digits, CodeText &out)
Render a code as its fixed-width, zero-padded decimal text.
boolkleidos::totp::currentCode (const CodeSeed &seed, const CodeClock &clock, uint32_t &code, uint8_t *remaining=nullptr)
Generate the code valid at the gate's time base on the TOTP worker.
Verdictkleidos::totp::codeClock ()
Ask the gate, once per frame or request.
boolkleidos::totp::enabled ()
The 2FA codes setting.
boolkleidos::totp::setEnabled (bool on)
Store the 2FA codes setting.
constexpr Gatekleidos::totp::decideGate (bool enabled, timex::rtc::ClockTrust trust, bool preciseSyncHolds)
The gate's rule: the setting first, then the clock, then the sync.
constexpr const char *kleidos::totp::gateLabel (Gate gate)
The verdict's wire and console spelling.
constexpr TotpAlgorithmkleidos::totpAlgorithmFromByte (uint8_t value)
Map the vault's stored algorithm byte onto TotpAlgorithm.
boolkleidos::totp::begin (kleidos::platform::rtos::Core core=kleidos::platform::rtos::Core::ProCpu, kleidos::platform::rtos::Priority priority=4)
Bring up the TOTP worker. Idempotent.
voidkleidos::totp::shutdown ()
Stop the worker: drain the queue, signal exit, join (bounded timeout) and tear down the queue.
boolkleidos::totp::isRunning ()
Return whether the worker task is currently running.
rtos::TaskHandlekleidos::totp::taskHandle ()
Return the worker task handle.
uint32_tkleidos::totp::pendingRequests ()
Return the number of requests currently queued (diagnostics only).
boolkleidos::totp::onWorker ()
Whether running the work inline is safe right now.
template<typename Fn>
boolkleidos::totp::execute (Fn &&fn)
Run fn on the TOTP worker thread and return its result.
voidkleidos::totp::setDispatchFailureForTest (bool fail)
Host builds only: make execute report a dispatch that did not run.

Variables

constexpr uint8_tkleidos::totp::kDigits6
Short RFC 6238 code length (the default).
constexpr uint8_tkleidos::totp::kDigits8
Long RFC 6238 code length.
constexpr uint16_tkleidos::totp::kPeriod30
Default RFC 6238 time step, in seconds.
constexpr uint32_tkleidos::totp::kCountdownTickMs
How often a list of codes repaints its countdowns, in milliseconds.
constexpr uint16_tkleidos::totp::kPeriod60
Long RFC 6238 time step, in seconds.
constexpr boolkleidos::totp::kEnabledByDefault
The setting's default: on where a battery-backed RTC keeps the time.
constexpr std::array< const char *, 4 >kleidos::totp::kGateLabels
The verdicts' wire and console spellings, in Gate order.

Back to the top

Enumeration Type Documentation

Gate #

enum class kleidos::totp::Gate : uint8_t

Whether a one-time code may be made now, and why not.

Value Meaning
Ready A code may be made; the gate's verdict carries the time base.
Disabled The 2FA codes setting is off on this device.
ClockUnset The clock is not set (trust None).
NeedsSync The clock is only Volatile and no precise sync holds since the last sleep.
Enumerator
Ready 

A code may be made.

Disabled 

The 2FA codes setting is off.

ClockUnset 

The clock is not set.

NeedsSync 

A volatile clock with no precise sync holding.

TotpAlgorithm #

enum class kleidos::TotpAlgorithm : uint8_t

HMAC hash function driving the RFC 6238 pipeline.

The enumerator values are the vault's on-record algorithm byte (see kleidos::vault::TotpRecord), so the stored u8 and this enum convert with a plain cast through totpAlgorithmFromByte.

Enumerator
Sha1 

HMAC-SHA1 (the RFC 6238 default; 20-byte digest).

Sha256 

HMAC-SHA256 (32-byte digest).

Back to the top

Function Documentation

begin() #

Bring up the TOTP worker. Idempotent.

Default placement matches the canonical Kleidos task ladder: Core 0 (PRO_CPU), priority 4: one band above the vault worker (3), which shares that core.

Parameters
NameDirectionMeaning
coreinTarget core. Defaults to PRO_CPU.
priorityinApplication priority.
Return values
ValueMeaning
trueWorker is running on exit (started by this call, or idempotent re-entry).
falseWorker spawn failed (e.g. queue allocation error).
See also
shutdown

clampDigits() #

uint8_t kleidos::totp::clampDigits(uint32_t digits)
constexpr

Clamp a stored digit count to the only two legal RFC 6238 values.

Applied on READ: a record written by an older build (or restored from a hand-edited backup) may carry any byte, and an unclamped value would desynchronize the code from every other authenticator.

Parameters
NameDirectionMeaning
digitsinRaw digit count from the record.
Returns
kDigits8 when digits is exactly 8, kDigits6 otherwise.

clampPeriod() #

uint16_t kleidos::totp::clampPeriod(uint32_t period)
constexpr

Clamp a stored time step to the only two legal RFC 6238 values.

Applied on READ. A zero or absurd period would otherwise wrap the remaining-seconds arithmetic (period - epoch % period) and report a countdown that never expires.

Parameters
NameDirectionMeaning
periodinRaw period from the record, in seconds.
Returns
kPeriod60 when period is exactly 60, kPeriod30 otherwise.

codeClock() #

Verdict kleidos::totp::codeClock()
nodiscard

Ask the gate, once per frame or request.

Reads the setting, the clock's trust, the clock and then the precise-sync record, in that order: a clock write clears the record before it moves the clock, so a time read here is never paired with a sync made before it.

Returns
The verdict; clock holds the time base exactly when it is Gate::Ready.

codeClockForTest() #

CodeClock kleidos::totp::codeClockForTest(uint64_t epoch, uint16_t msIntoSecond = 0)
constexpr

Native tests only: a time base for a fixed epoch (an RFC vector's).

Parameters
NameMeaning
epochUnix seconds.
msIntoSecondMilliseconds into that second, for the countdown arc.
Returns
A time base for epoch.

currentCode() #

bool kleidos::totp::currentCode(const CodeSeed & seed, const CodeClock & clock, uint32_t & code, uint8_t * remaining = nullptr)

Generate the code valid at the gate's time base on the TOTP worker.

Runs TotpGenerator::tryGenerate, which clamps the seed's digits and period, on the TOTP worker (execute(), totp_task.h).

Parameters
NameDirectionMeaning
seedinThe stored secret and parameters.
clockinThe time base a Gate::Ready verdict carried (kleidos::totp::codeClock()).
codeoutThe code on success; 0 when there is none.
remainingoutOptional: seconds left in the clamped period, written whether or not a code came out.
Return values
ValueMeaning
truecode is the current code.
falseThere is no code to show or type: the worker dispatch did not run the generator (its completion semaphore could not be allocated, or the worker shut down with the request queued), or PSA could not compute the HMAC (an empty secret included).
See also
formatCode

decideGate() #

Gate kleidos::totp::decideGate(bool enabled, timex::rtc::ClockTrust trust, bool preciseSyncHolds)
constexpr

The gate's rule: the setting first, then the clock, then the sync.

A battery-backed RTC keeps the time through every sleep, so a Backed clock needs no sync. A Volatile one (the boards without an RTC chip) is good for a code only while a precise sync holds (time/precise_sync.h): a time a person sets on the device never is.

Parameters
NameMeaning
enabledThe 2FA codes setting.
trustThe clock's trust.
preciseSyncHoldsWhether a precise sync holds (precise::fresh()).
Returns
The verdict.

enabled() #

bool kleidos::totp::enabled()
nodiscard

The 2FA codes setting.

Read from NVS once and cached; an absent key, or an NVS that cannot be opened, reads as kEnabledByDefault.

Return values
ValueMeaning
trueThe device shows and types codes.
falseIt makes none.

execute() #

template<typename Fn>
bool kleidos::totp::execute(Fn && fn)
inline

Run fn on the TOTP worker thread and return its result.

Capturing lambdas are allowed: the worker invokes them through a captureless trampoline, so all closure state stays on the caller's stack. Falls back to inline execution when onWorker returns true (worker not running or caller IS the worker).

On a host build no FreeRTOS worker exists and fn always runs inline, unless setDispatchFailureForTest armed a failed dispatch.

Template Parameters
NameMeaning
FnCallable as bool fn(); capturing lambdas are allowed.
Parameters
NameDirectionMeaning
fninWork to execute; runs inline when on the worker or when the worker is not running.
Return values
ValueMeaning
truefn returned true.
falsefn returned false, or the semaphore/queue dispatch failed and the call did not run (on a host build: setDispatchFailureForTest armed a failed dispatch).
See also
onWorker

formatCode() #

void kleidos::totp::formatCode(uint32_t code, uint32_t digits, CodeText & out)

Render a code as its fixed-width, zero-padded decimal text.

RFC 6238 codes are compared as text, so a code below 10^(digits-1) keeps its leading zeros ("012345", not "12345"). A value wider than the width is reduced modulo 10^width, matching the generator's own truncation.

Parameters
NameDirectionMeaning
codeinCode value from currentCode.
digitsinStored digit count; clamped by clampDigits.
outoutReceives exactly clampDigits(digits) characters.

gateLabel() #

const char * kleidos::totp::gateLabel(Gate gate)
constexpr

The verdict's wire and console spelling.

Parameters
NameMeaning
gateThe verdict.
Returns
"ready", "disabled", "clock_unset" or "needs_sync" (never nullptr).

isRunning() #

bool kleidos::totp::isRunning()

Return whether the worker task is currently running.

Return values
ValueMeaning
trueBetween begin returning true and shutdown returning.
falseOtherwise.
See also
begin, shutdown

isValidDigits() #

bool kleidos::totp::isValidDigits(uint32_t digits)
constexpr

Whether a write may set this digit count.

Writes are strict where reads are lenient: anything but 6 or 8 is refused rather than silently clamped. Pass the value at full width; a narrowing cast first would read 264 as 8.

Parameters
NameDirectionMeaning
digitsinRequested digit count.
Return values
ValueMeaning
truedigits is 6 or 8.
falseAny other value.

isValidPeriod() #

bool kleidos::totp::isValidPeriod(uint32_t period)
constexpr

Whether a write may set this time step.

Parameters
NameDirectionMeaning
periodinRequested period, in seconds.
Return values
ValueMeaning
trueperiod is 30 or 60.
falseAny other value.

onWorker() #

bool kleidos::totp::onWorker()
inline

Whether running the work inline is safe right now.

Return values
ValueMeaning
trueWhen the worker is not running, or the caller IS the worker (so dispatching would deadlock on its own semaphore wait). Always, on a host build: no worker thread exists there.
falseWhen a dispatch is required.
See also
execute, taskHandle

pendingRequests() #

uint32_t kleidos::totp::pendingRequests()

Return the number of requests currently queued (diagnostics only).

Returns
Number of pending dispatch requests. A queue-depth probe for diagnostics surfaces (e.g. the serial debug console).

setDispatchFailureForTest() #

void kleidos::totp::setDispatchFailureForTest(bool fail)
inline

Host builds only: make execute report a dispatch that did not run.

A device dispatch fails when the caller's completion semaphore cannot be allocated, or when the worker shuts down with the request queued; the work never runs and execute returns false. The host build runs everything inline, so a native test reaches that path through this switch.

Parameters
NameDirectionMeaning
failinTrue to fail every following execute without running its work; false to run inline again.

setEnabled() #

bool kleidos::totp::setEnabled(bool on)
nodiscard

Store the 2FA codes setting.

Parameters
NameMeaning
onThe new value.
Return values
ValueMeaning
trueNVS took it (the cache follows).
falseNVS refused; the setting is unchanged.

shutdown() #

void kleidos::totp::shutdown()

Stop the worker: drain the queue, signal exit, join (bounded timeout) and tear down the queue.

Posts a nullptr sentinel to wake the worker, waits up to 200 ms for the task to delete itself, and force-deletes if it does not exit in time. Stale queued requests have their completion semaphores given so blocked callers can unwind.

Note
Safe to call when the worker is not running. Must be called before deep sleep.
See also
begin

taskHandle() #

kleidos::platform::rtos::TaskHandle kleidos::totp::taskHandle()

Return the worker task handle.

Returns
The worker task handle, or nullptr when not running.
See also
onWorker

totpAlgorithmFromByte() #

TotpAlgorithm kleidos::totpAlgorithmFromByte(uint8_t value)
constexpr

Map the vault's stored algorithm byte onto TotpAlgorithm.

Any value other than 1 clamps to SHA-1, mirroring the record decoder's unknown-value clamp so both layers agree on the fallback.

Parameters
NameDirectionMeaning
valueinStored algorithm byte (0 = SHA-1, 1 = SHA-256).
Returns
The corresponding enumerator (SHA-1 for any unknown value).

Back to the top

Variable Documentation

kCountdownTickMs #

uint32_t kleidos::totp::kCountdownTickMs
inlineconstexpr

How often a list of codes repaints its countdowns, in milliseconds.

Five times a second, not once. The arc that draws a code's remaining window is the one thing on a 2FA page that moves, and from whole seconds it has one position per second, a step so small that a reader sees a page that is not moving and a recording of the page shows a still. At 200 ms the arc has five positions a second, which is the design system's own motion floor, and the region it repaints is the code and its ring and nothing else.

Paid only while a 2FA list is on the glass and the display is on; the three views that draw one share this rather than each naming a number.

Back to the top