machdocs
Home Ecosystem Changelog

Secrecy

Writing ^ in front of a type marks a value as data that must be processed in constant time. The compiler keeps such a value away from branches, memory addresses and variable-time instructions, and in a function marked #[constant_time] it proves the same of the machine code it emits.

Scope

Constant time is a working feature on linux x86-64 and linux aarch64. Every other target is experimental: the same checks run there, but the targets have not been cross-checked to the same standard. Cache and power side channels are not covered. A secret is a marker for constant time, not a promise of confidentiality: see What is promised about memory and Assurance.

What this is for

Say you check a password by comparing it one character at a time, and stop at the first character that does not match. That is the obvious way to write it, and it is correct: it never prints the password, never logs it, and returns nothing but yes or no.

It still gives the password away. An attacker who can time the check learns something from every attempt: a guess starting with the right character takes a hair longer to reject than one starting with the wrong character, because the comparison got one step further before giving up. Guess the first character, keep the one that is measurably slower, and guess the second. A password that would take longer than the universe to brute-force all at once falls in a few thousand tries, one character at a time.

Timing is not the only such channel. Three things about a running program are observable without reading its memory:

The standard defence is to write the code so none of those depend on the secret: compare every character whether or not an earlier one already failed, and combine the results arithmetically instead of branching. This is called constant-time code, and it is notoriously easy to get wrong.

Why the compiler has to be involved

Even when you get it right by hand, the compiler can undo it. An optimizer's whole job is to notice that work is unnecessary and remove it, and branch-free code that carefully does the same work every time looks exactly like work worth eliminating. The source is still constant-time and the binary is not.

So the guarantee cannot live in a coding convention or a library. It has to be something the compiler itself knows about and is obliged to preserve. That is what ^ is.

use std.types.bool.bool;
use std.types.bool.true;

# `^u64` is data the compiler keeps away from branches, addresses and variable-time instructions
#[constant_time("hard")]
fun ct_diff(a: ^u64, b: ^u64) ^u64 {
    ret a ^ b;                 # one xor, always the same work
}

fun verify(given: ^u64, secret: ^u64) bool {
    if (given == secret) { ret true; }   # refused, see below
    ret (ct_diff(given, secret):>u64) == 0;
}

That branch does not compile:

error[secret.branch] secret value used as a branch condition
   @ src/auth.mach:11:5
11 |     if (given == secret) { ret true; }   # refused, see below
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   note compute without branching on it, or declassify with `:>T` when disclosure is intended

The mistake is caught when you compile, not by an audit or a timing measurement after the fact. Secrecy is part of the type, so it travels with the value through every function it is passed to. And disclosure is possible but never accidental: :>T is the one way to turn a secret back into an ordinary value, so every deliberate release is a visible mark in the source that a reviewer can search for.

The secrecy lattice

There are two secrecy levels in a two-point lattice: public is the bottom, secret the top. ^ lifts a type to secret and binds to the type immediately to its right, so it nests with * and [N] in any order: ^u32, *^u8, ^*u8, [N]^u8, ^MyRec. Doubling collapses: ^^T is ^T.

A public value coerces up to secret wherever a secret is expected, with no syntax. The reverse never happens implicitly.

fun up(p: u32) ^u32 { ret p; }      # public u32 flows into a secret slot

A literal is public by construction and stays public through that coercion: its value sits in the instruction stream, so classifying it as secret would protect nothing. A value computed with a secret is secret however its other operand is spelled, so v << 3 on a secret v still yields a secret, while the constant 3 is not mistaken for a secret shift count.

Join

Any operation with a secret operand yields a secret result. Taint joins across arithmetic, bitwise, shift, and comparison operators, and through a value read out of a secret container.

fun mix(a: ^u32, b: u32) ^u32 { ret a + b; }    # ^u32 + u32 -> ^u32

rec Key { d: ^[32]u8; }
fun first(k: Key) ^u8 { ret k.d[0]; }            # element of a secret array is ^u8

A secret array ^[N]T coerces to the array of secrets [N]^T with no syntax, and a window x[start, n] over a secret array is the secret array ^[n]T. Taking the address of a ^T value with ? gives the public pointer *^T (the address is public, the pointee secret), and dereferencing it with @ recovers the secret ^T.

Gates

A secret may not reach a position the leakage model observes. Each is a compile error decided by operand type, in every function, whether or not it carries #[constant_time]:

fun leak(a: ^u32, t: *u8, p: ^*u8) u8 {
    if (a) { ret 1; }       # error: secret value used as a branch condition
    ret t[a];               # error: secret value used as a memory index
    ret @p;                 # error: secret value used as a memory address
}

The index and the address are the two halves of one effective address, so both are gated. Only a secret pointer is an address: a ^[N]T or ^Rec is a secret value living at a public address, and a *^T is a public address to secret storage.

Everything else is free everywhere: a secret moves through storage, arithmetic and calls in any function. Whether an integer multiply or a variable shift runs in time independent of a secret operand is the target's question, and it is asked inside a #[constant_time] function (see Soft and hard). A secret value passed to a variadic pack is rejected, including one wrapped inside an aggregate, while a pointer to secret storage (*^u8) is accepted.

Note

The gates are checked against the types of the instance, not of the template. A generic's body is re-checked per instantiation under its concrete type arguments, so a T that instantiates to a secret is gated exactly as the secret spelled out in full would be.

Asking about secrecy at comptime

A library has two different questions about secrecy, and each has its own predicate. Both are comptime-only, valid as a $if / $or gate condition, and answered per instantiation inside a generic. The full reference is in Intrinsics.

$is_secret is what lets a derive decide rather than refuse: a formatter redacts a secret field, a hash refuses one, and an equality picks the constant-time comparison instead of the early-out whose timing is the secret.

rec Session { id: u64; key: ^[32]u8; }

$each f in $fields(Session) {
    $if ($is_secret(f.type)) { }            # redact: no read of `key` is emitted
    $or { render(s.[f]); }
}

A walk must not gate on $holds_secret: it would redact a whole record over one field and still could not say which field was the secret. A walk that skips a secret field is pinned by the flow rules rather than by convention, since reading one into a public accumulator does not compile.

Downgrade with :>T

:>T is the only way to remove ^, in every function. It produces a new public value and never reinterprets storage in place, and it always names the public type it lands on, which must be the operand's type without ^.

fun publish(a: ^u32) u32 { ret a:>u32; }
fun publish2(a: ^*u8) *u8 { ret a:>*u8; }

:>T peels exactly the outer qualifier, so it never reaches a welded pointee: *^T stays *^T. :: and :~ may add ^ at a value position but never drop it. There is no untyped form: :^ is not an operator.

A module constant whose type holds a secret has no compile-time value, so it cannot size an array, gate a $if or feed a comptime parameter. An author who means the value writes the declassification where it is used:

val K: ^u64 = 7;

fun take($c: u64) u64 { ret c; }

fun main_value() u64 {
    ret take(K:>u64);   # a compile-time 7, declassified here
}

Welded-storage pointers

Secrecy is fixed at declaration and cannot be changed by aliasing, which makes the public/secret aliasing leak unconstructable with no alias analysis at all:

fun erase(p: *^u8) ptr { ret p; }     # error: expected ptr, found *^u8
uni Bad { a: ^u32; b: u32; }          # error: overlapping fields are part secret

The union rule is a property of the union type, so it holds for an inline uni { ... } and at every instance of a generic union. At the declaration a variant typed by a generic parameter says nothing about secrecy, so the check happens where each instance is formed.

uni U[T]   { a: T; b: u32; }
rec Box[T] { u: U[T]; }

var s: U[^u32];                       # error: this instantiation makes the variants disagree
var b: Box[^u64];                     # same error: the instance need not be spelled
var p: U[u32];                        # fine, and so is an all-secret instantiation

The check is deep and fails closed: a secret nested anywhere inside an aggregate counts as secret at these boundaries. A pointer cast between two record types is compared byte by byte, so a narrowing that keeps the class of every byte it covers is accepted, and a widening past a secret is refused. Comparing and ordering two pointers is allowed whatever their pointees' secrecy, since a *^T is a public address.

#[constant_time] - the codegen contract

The flow typing constrains the source. #[constant_time(mode)] carries the obligation through codegen, and its mode, "soft" or "hard", is required. Inside a function carrying it, in either mode, the emitted machine code holds to three conditions:

#[constant_time("hard")]
fun ct_select(mask: ^u32, a: ^u32, b: ^u32) ^u32 {
    ret (a & mask) | (b & ~mask);
}

The check walks the encoded code of each such function, after instruction selection, register allocation, spilling and frame layout, so a secret the compiler's own passes route to a branch, an address or a variable-time instruction is refused, never emitted. Secret-free code compiles byte-identically. No function is required to carry the mark: a function that computes on a secret without it compiles, held to the gates above and to nothing more, with no promise about the timing of its code.

The signature is the call contract

A call trusts the callee's declaration and never reads its body: the callee's mode and which bytes of each parameter and of its result are secret are all the caller's check knows of it. The callee's own build holds its body to that declaration, so a definition that breaks it fails its own module. A constant-time function may pass a secret only to a callee that is declared #[constant_time] in a mode it may rely on, that it names directly or reaches through a function type marked constant time, and that is not #[weak]:

fun helper(k: ^u64) ^u64 { ret k + 1; }

#[constant_time("soft")]
fun derive(k: ^u64) ^u64 {
    ret helper(k);          # error: helper is not declared constant time
}

A soft caller may call either mode. A hard caller may call a hard callee, or a soft one where the build guarantees every timing mode a soft function's code may be held under: every x86-64 build, an aarch64 build with dit and a riscv64 build with zkt. A trusted callee's result is what its declaration says it is, so a constant-time caller may branch on a public status a trusted callee returns. A call that passes no secret and reaches none needs nothing of its callee.

A function type carries a constant-time mode as part of its identity. The only spelling is an alias marked with the decorator, and a value of it holds only a function declared constant time in that mode or a stronger one:

#[constant_time("soft")]
def Seal: fun(*^u8, u64) ^u64;

rec Cipher { id: u64; seal: Seal; }

#[constant_time("soft")]
fun sum(data: *^u8, n: u64) ^u64 {
    var acc: ^u64 = 0;
    var i:   u64  = 0;
    for (i < n) {
        acc = acc + data[i]::^u64;
        i   = i + 1;
    }
    ret acc;
}

#[constant_time("soft")]
fun seal_with(table: *Cipher, which: u64, data: *^u8, n: u64) ^u64 {
    ret table[which].seal(data, n);   # trusted as a direct call of a soft function
}

A value converts with no cast from a stronger mode to a weaker one, hard to soft and any marked type to the plain one, and nothing converts the other way. A marked function type is passed, returned and called as the plain one in every calling convention.

Declassification

:>T is the declassification inside a constant-time function too. A value that went through :>T is public for every purpose there: it may decide a branch, form an index or an address, be stored into public memory and be returned as a public result. The promise of #[constant_time] is that nothing secret that was not explicitly declassified decides timing or reaches public storage or a public result. A value declassified in part is public only in that part.

The checker cannot judge what the author declared public. Each :>T is a claim the author makes and a reviewer checks, and mach check --declassified lists those claims, one a line, as file:line:column: function: type:

#[constant_time("soft")]
pub fun is_zero(x: ^u64) u64 {
    val d: u64 = ((x | (0 - x)) >> 63):>u64;   # a claim: whether x is zero is public
    ret 1 - d;
}
$ mach check . --declassified
   checked  scratch  linux-x86_64  debug   229ms
src/tag.mach:3:18: is_zero: ^u64

Inline assembly inside a constant-time function

Inline asm inside such a function is validated, not rejected. The block is encoded with the rest of the function and the walk reads its bytes as it reads every other instruction, so nothing about a block is taken on trust from its text. Every register is seeded at the function's entry from the declaration, flags are tracked bit by bit, and a store of a secret is admitted only into memory something states may hold one. What the walk cannot read, it refuses: bytes that decode to no instruction, an instruction whose effects are undecided, and control that leaves the block where the walk cannot follow it. A data directive is refused outright. A block may not turn the processor's timing mode off. See Inline assembly for the binding rules.

The mark is refused on a SPIR-V target, whose module a downstream compiler translates, and warned on wasm, whose runtime decides the instructions that run.

Soft and hard

Some instructions have data-independent timing only under a processor mode. An aarch64 multiply is data-independent only while the DIT mode is on, which user code turns on with msr dit, 1 and which a processor without FEAT_DIT does not have. On riscv the same promise is the Zkt extension, and on x86-64 Intel's DOITM, which the kernel owns. A constant-time function's mode says what happens when the build cannot be sure the promise holds.

#[constant_time("soft")]
fun mul_soft(a: ^u64, b: ^u64) ^u64 { ret a * b; }

#[constant_time("hard")]
fun mul_hard(a: ^u64, b: ^u64) ^u64 { ret a * b; }
$ mach build . -t linux-aarch64
error[secret.target_unguaranteed] 'scratch.mul.mul_hard' of 'scratch.mul' requires hard constant time, and its code runs in constant time only under FEAT_DIT, which the target does not guarantee. select it in the target's `isa` or `ext`, or mark the function soft
  @ src/mul.mach:5:5
5 | fun mul_hard(a: ^u64, b: ^u64) ^u64 { ret a * b; }
  |     ^

Selecting dit in the target's isa or ext, or marking the function soft, builds it. $mach.build.ct_mul(op, width) answers at comptime whether a multiply runs in constant time on the target, so a library can choose a hardware or a bit-serial path (see The comptime channel). In a constant-time function a secret multiply the check does not clear is a compile error: the compiler never substitutes a slower loop for it.

For code that holds the mode by hand, the standard library keeps std.system.dit.enable, disable and read on aarch64, and std.crypto.ct.begin.

What is promised about memory

The compiler promises two things of secret data: a constant-time function processes it in constant time, and no value typed secret reaches a public one without a :>. It does not promise memory hygiene. A function's stack slots, spills and registers are not wiped when it returns, so a secret's bytes can remain in dead stack memory. Bytes nothing wrote, such as a public record's padding or the unused bytes of a union, are unspecified and may hold whatever was there before. A long-lived buffer holding a secret is wiped by its author with the standard library's helpers, such as std.crypto.ct.zeroize.

The check takes such bytes as their type states them. Reading bytes nothing wrote is the program's to avoid, in marked code as in any other:

uni U { a: u8; b: [6]u64; }

fun make() U { ret U{a: 1}; }       # writes one byte of the 48

#[constant_time("soft")]
fun look(u: *U) u64 {
    if (u.b[1] != 0) { ret 1; }     # reads bytes nothing wrote
    ret 0;
}

look builds, and what it branches on is what the stack held when make ran. Read the member that was written, and write or send a record member by member.

Trusted base

The guarantee rests on four parts: the secrecy check of the source, the lowering that carries each secret through selection, allocation, spilling and framing to the emitted instructions, the walk of each constant-time function's encoded code against the timing class of every instruction it executes, and the hardware timing mode where an instruction needs one.

The checker verifies the functions marked #[constant_time], their asm included. Code that is not marked is trusted to follow the type system and its declared signatures, and asm outside a constant-time function is not checked. A proof is always relative to a leakage model, and its fidelity to real silicon is empirical.

Assurance

The guarantee. For code marked #[constant_time] and compiled for a covered target, the emitted machine code's branches and memory addresses never depend on secret values, and no instruction whose timing depends on its operands receives a secret. A build that cannot prove it is refused.

Covered targets. Linux x86-64 and linux aarch64. Every other target is experimental: linux riscv64 and riscv32, darwin, windows, uefi and every freestanding target run the same checks but have not been cross-checked to the same standard. wasm compiles a constant-time function with a warning, and SPIR-V refuses one.

Out of scope. Cache and power side channels. An access past the object a pointer addresses, including past a narrowed pointer cast: secrecy holds for in-bounds accesses only. Confidentiality of memory, as stated above.

The x86-64 caveat. The x86-64 timing rows come from Intel's "Data Operand Independent Timing Instructions" list, which holds while DOITM is on. Intel states that a processor which does not enumerate DOITM behaves as if it were on for the listed instructions. AMD publishes no equivalent list, so on AMD processors the guarantee rests on Intel's list with no statement from AMD behind it.

Independent checking. Two independent analyzers cross-check the emitted binaries: BINSEC's checkct, and valgrind's memcheck with the secret marked undefined (ctgrind). On linux x86-64 both have run, and checkct on linux aarch64, without and with optimization: neither reported anything on the constant-time functions, and both flagged the planted control and memory leaks wherever they ran. ctgrind on linux aarch64 waits for aarch64 hardware.

See also