Security audit: P-256 ECDSA and X25519
The record of the security audit of nish/crypto/p256 and nish/crypto/x25519
(tracking issue #363, stage "Crypto ECC"). It says what was checked, how, what
was found and what became of it, and names the test that pins each property,
so that the next audit starts from evidence rather than from trust.
Result. No forgery, key recovery, panic, non-canonical accept or secret-dependent branch was found. Every applicable Wycheproof vector passes (2,150 of them, 1,666 new), the fiat-crypto port matches upstream statement for statement, and two independent reference implementations agree with both modules on 5,000 more inputs. Three Low findings are recorded below: two were fixed here, and one lies outside this stage's files and stays open.
Scope
| File | Functions |
|---|---|
std/crypto/p256.ts |
p256PublicKey, p256Ecdh (with p256EcdhExposed; added after this audit, see "P-256 ECDH" under Properties verified), p256Sign, p256Verify, p256SignSha256, p256VerifySha256, and everything they reach: the p256Fiat* field and scalar arithmetic, p256DecodePoint / p256EncodePoint, p256ScalarInRange, p256DigestScalar, the RFC 6979 nonce (p256NonceKey, p256SignScalar), the inversions, the complete point formulas and the windowed p256ScalarMult, and the fixed-base comb that multiplies G for a public key or a signature (p256BaseMult, p256BaseMultWith and the table p256BaseTable, added by #628 after this audit and signed since ECC-7; see below); P256SignScratch and p256SignSha256Into, with the SHA-256 and HMAC they run (p256ShaCompress, p256ShaInto, p256HmacInto), the key's steps (p256NonceKeyExposed, p256SignSExposed) and p256ScalarMultWith, which #628 replaced with p256BaseMultWith |
std/crypto/x25519.ts |
x25519, x25519Base, and the field (f25519*), f25519Decode / f25519Encode, f25519Invert and x25519Ladder |
std/crypto/ed25519.ts |
added after this audit and recorded as ECC-5: ed25519PublicKey, ed25519Sign, ed25519Verify and everything they reach |
tests/cases/ct_asm_p256.ts, tests/cases/ct_asm_x25519.ts |
the copies the constant-time disassembly check holds, compared here with the module functions they mirror |
Out of scope: std/crypto/sha256.ts, sha512.ts, hmac.ts and ct.ts,
which these modules call (the K1 stage audits them), and std/crypto/x509.ts,
which calls p256Verify (the X.509 stage).
Threat model
The attacker controls every byte of every argument of the verifying and
key-agreement side: p256Verify's public key, digest and signature (any
length, any value), and x25519's u (any length, any value, including
low-order points, points on the twist and u-coordinates of p or more). On the
signing side the attacker chooses the digest and sees the signature, and may
time the call; the private key is the secret. For X25519 the scalar is the
secret, and the attacker may time the call and choose u.
A win for the attacker is any of: a signature accepted that the key's owner did not make (forgery), a private key or scalar learned from outputs or timing (key recovery), a panic, an unbounded loop or allocation (denial of service), or two encodings of one value both accepted (a non-canonical accept).
Method
Specifications compared against. SEC 1 v2 §2.3.3–2.3.4 (point encoding), §3.2.2 (public-key validation) and §4.1.3–4.1.4 (ECDSA signing and verification); FIPS 186-4 §6.4; SEC 2 §2.4.2 (the curve's constants); RFC 6979 §2.3 and §3.2 (bits2int, bits2octets and the HMAC-DRBG nonce); RFC 7748 §5 (decoding, clamping and the ladder) and §6.1 (the all-zero check).
Upstream diff of the fiat-crypto port. fiat-c/src/p256_32.c and
fiat-c/src/p256_scalar_32.c were fetched at the commit
THIRD_PARTY_NOTICES.md names, abe078c5149bc15bc368c27cc364fdef56470136.
A script parsed each C function into its statement list (every mulx,
addcarryx, subborrowx and cmovznz call with its outputs and arguments,
every assignment and every store to out1) and did the same to the Nish
translation, undoing its three documented changes (the packed u64 results,
the length guard, and square's limbs read into locals first).
Every one of the ten ported functions — field mul, square, add, sub,
nonzero, selectznz, set_one, and scalar mul, add, set_one — matched
statement for statement: 359, 359, 33, 25, 2, 16, 8, 415, 33 and 8 statements.
Where Nish leaves out one half of a helper's result, the script checked that
fiat never reads that half.
The script was also shown to catch a change: one
constant in p256FiatMul altered by one bit was reported at once. The four
helpers were read against upstream by hand: subborrowx keeps bit 32 of a
difference that wraps modulo 2^64, which is the borrow; cmovznz is
ctSelect(ctEq(arg1, 0), arg2, arg3), which answers arg2 for a zero arg1,
as fiat's does.
The 64-bit field port (ECC-8). Field mul, square, add and sub
were then ported again from fiat-c/src/p256_64.c at the same commit, onto
four 64-bit limbs read from and stored to the same eight u32 words (limb i
is words 2i and 2i + 1), so the Montgomery R stays 2^256 and every other
function, and the generated comb table, is unchanged. A second, one-off
script (run for this audit and not kept in the repository; the counts and the
two mutations below are its output, recorded here as evidence) parsed
the four 64-bit C functions the same way and checked the Nish against them:
every value read, and every store, matched — 182 values read and 4 stores for
mul and for square (107 C statements each), 21 and 4 for add (17), 16
and 4 for sub (13). It caught both changes it was shown: one constant
altered by one bit, and one carry-in replaced by zero. Nish has no 128-bit
integer, so the four 64-bit helpers stand in for fiat's: mulx_u64's high
word from four 32 × 32 products (p256FiatMulxU64Hi), addcarryx_u64 and
subborrowx_u64's carry and borrow from the operands' and result's top bits
((a & b) | ((a | b) & ~s) and (~a & b) | (~(a ^ b) & d), bit 63), and
cmovznz_u64 as ctSelect on 64 bits. These were read by hand and are
checked by tests/link/crypto_p256_inverse ("arithmetic: 38296 of 38296 field
ops agree with the bit-serial reference"), which a carry with its a & b term
dropped fails.
The closest upstream for X25519. std/crypto/x25519.ts says it was written
from RFC 7748. The nearest well-known implementations are ref10's field code
(SUPERCOP, public domain) and curve25519-donna. Both also use ten signed limbs
of alternately 26 and 25 bits. Function by function:
-
f25519Muldoes not follow ref10'sfe_mul. It loops over a doubled copy and a 19-limb wide product, where ref10 writes out 100 products with the factors 2 and 19 folded in by hand. -
f25519Carryandf25519Encodeshare ref10's idea: an arithmetic-shift carry, and adding 19 to decide whether the value is at least p. They do not share its statement order, and the byte packing is a loop over an accumulator. -
f25519Invertuses the same addition chain as ref10'sfe_invert(254 squarings and 11 multiplications to reach p − 2). That chain is Bernstein's published construction, an idea rather than code, and ref10 is public domain in any case. x25519Ladderis RFC 7748 §5's pseudocode, step for step.
Nothing here needs a notice that it does not already carry.
Constants. p, n, R² mod p, R² mod n, b·R mod p, R mod p (fiat's
set_one), R mod n (the scalar set_one), both inversion exponents p − 2 and
n − 2, and G's coordinates were recomputed from SEC 2 in Python and compared
limb by limb. G was checked to be on the curve. All agree.
Constant-time fixtures. The copies in tests/cases/ct_asm_p256.ts and
ct_asm_x25519.ts were compared mechanically with the module functions they
mirror. The fiat functions, p256TableMove and p256Copy are identical once
the guard is dropped. p256PointAdd (43 steps) and p256PointDouble (34
steps) call the same field functions on the same operands in the same order,
once the coordinate arrays are renamed. The X25519 field functions and the
ladder step differ only in the ways the fixture's header documents. So the
disassembly check proves the shape of the code that ships.
node tests/run.js ct_asm passes on x86-64 and aarch64.
Bounds of the X25519 limbs. Signed i64 overflow was undefined behaviour
when this was audited and is a checked panic since #426, so either way
f25519Mul's bound was re-derived rather than trusted. Inputs have
limbs below 2^27 in magnitude. Each output limb collects ten products, each
scaled by at most 2 × 19, so each limb is below 380 × 2^54 < 2^62.6.
Every partial sum is bounded by the same sum of absolute values. wide[k + 10] × 19 plus wide[k] stays below 362 × 2^54, and the carries f25519Carry then
adds are below 2^38. Every call site in the ladder was checked to pass reduced
elements, or one sum or difference of two.
Differential testing. Two reference implementations were written in Python from the RFCs' own pseudocode: RFC 7748's ladder, and affine-coordinate ECDSA with RFC 6979. Both were first checked against the Wycheproof files. A driver program linked against the modules was then compared with them:
-
X25519, 1,692 inputs: 1,500 random (scalar, u) pairs over all 256 bits of
u; 15 special u-coordinates (0, 1, 2, 9, p − 1, p, p + 1, p + 9, 2^255 − 1, 2^255 − 20, 2^255 − 18, 2^254 and both points of order 8), each with its top bit clear and set, 6 times each; and all-zero, all-one and small scalars. 0 mismatches. -
P-256, 3,379 operations. Public keys of 0, 1, 2, 3, n − 1, n, n + 1, 2^256 − 1, (n ± 1)/2 and 40 random scalars. Signatures under 24 keys (1, 2, n − 2, n − 1 and 20 random) of digests of lengths 0, 1, 2, 20, 31, 32, 33, 48 and 64, and of the digests 0, 1, n − 1, n, n + 1, 2^256 − 1 and p.
Verification of every one of those signatures, and of its high-
stwin, a one-bit flip,r + n,s + n, the digestz + n, a digest that puts the sum at infinity, and a digest that makes the final addition a doubling. And 10 signatures built from the verification equation so that u1·G = u2·Q. 0 mismatches. RFC 6979 signatures agreed byte for byte.
Wycheproof. At commit 3fa63dd0344abb611f1fb1d77e119938603ea230, every
file that applies to these two modules is now run:
| File | Cases | Before | Test |
|---|---|---|---|
ecdsa_secp256r1_sha256_test.json |
484 | run | tests/link/crypto_p256, crypto_p256_f64 |
ecdsa_secp256r1_sha256_p1363_test.json |
262 | added | the same |
ecdsa_secp256r1_sha512_test.json |
554 | added | the same (checks the truncation of a 64-byte digest) |
ecdsa_secp256r1_sha512_p1363_test.json |
332 | added | the same |
x25519_test.json |
518 | added | tests/link/crypto_x25519, crypto_x25519_f64 |
Every case passes in both number modes. The 254 X25519 cases marked
acceptable are low-order points, twist points and non-canonical
u-coordinates. They are held to the file's exact shared secret, which is RFC
7748's answer and so this module's promise. Some files do not apply: the
ecdh_secp256r1_* files (the module had no ECDH; p256Ecdh now runs the
_ecpoint file, see "P-256 ECDH"), the SHA-3 and SHA-224
variants (std has neither hash), and x25519_asn / _jwk / _pem (these
test key encodings, which the module does not parse).
The new ECDSA vectors are in tests/link/crypto_wycheproof/ecdsa_secp256r1_sha256.ts,
the file that already carried Wycheproof's notice, and the X25519 ones in
tests/link/crypto_wycheproof/x25519.ts, which carries the same notice. Each
has a row in THIRD_PARTY_NOTICES.md naming the upstream files it derives
from and their case counts (ECC-3).
Mutation check of the tests. A test that has never been seen to fail proves little, so five defences were removed one at a time and the suites were rerun.
- The digest's reduction mod n removed: caught by "the digest n signs as the digest 0" and "the digest n + 5 signs as the digest 5".
-
p256Verify'sr/srange check removed: caught by Wycheproof cases in all four ECDSA files. - Bit 254 no longer set by the X25519 clamp: caught by RFC 7748's vectors and Wycheproof.
-
The explicit top-bit mask in
f25519Decoderemoved: not caught, and cannot be. The decoder fills exactly 255 bits of limbs and drops whatever is left in its accumulator, so bit 255 is ignored with or without the mask. The mask is a second, redundant statement of RFC 7748 §5's rule. The property itself is pinned by "a u with its top bit set gives the same answer as with it clear". -
p256Verify's check for a sum at the identity removed: not caught, and cannot be. The identity's Z inverts to 0, so its x reads as 0, andrhas already been checked to be at least 1, so the comparison fails anyway. The check is a redundant defence that states the rule where SEC 1 does. The property is pinned by "a sum u1 G + u2 Q at the identity is refused".
Findings
| Id | Severity | Where | Description | Disposition |
|---|---|---|---|---|
| ECC-1 | Low | std/crypto/x25519.ts:481 (x25519's doc) |
The doc said RFC 7748 §6.1's all-zero check is made by the TLS 1.3 module. At the time of this audit no TLS module existed in the tree and nothing called x25519, so a reader could conclude the check was made for them. |
Fixed in this change. The doc said from then on that a caller must refuse an all-zero answer itself, with timingSafeEqual. The TLS 1.3 server and client, which landed later, each refuse an all-zero shared secret themselves (std/net/tls.ts, std/net/tls/client.ts). Doc only, so there is no failing-first test. The behaviour it describes is pinned by crypto_x25519's "u = 0 answers all zeros, not null" and the six "low-order u … answers all zeros" checks. std/README.md says the same thing; see below. |
| ECC-2 | Low | std/crypto/p256.ts (p256Sign, p256SignScalar), std/crypto/x25519.ts (x25519) |
Secret intermediates are not wiped: the private-key limbs dM, the nonce v and its Montgomery form, RFC 6979's HMAC key k, the table built from G, and X25519's clamped scalar copy and ladder state all stay in arena memory after the call returns. A later memory disclosure could read them. The language has no store that the optimiser is barred from removing, so a wipe written in Nish could be deleted as a dead store and would give false assurance. |
Closed in this change. The private key reaches both modules as a Secret<u8[]> from nish:secret (docs/LANGUAGE.md, "Secrets"), so a caller cannot print, compare, branch on or drop it unwiped, and both modules compute on it only inside expose / exposeWith, whose function the checker holds to reaching no I/O and no C and keeping nothing of the key. Inside, everything the key reaches is zeroed with wipe before the call returns — a volatile llvm.memset no optimiser removes, pinned under opt -O2 by tests/run.js ("nish:secret: the wipe survives opt -O2", secret_wipe_o2 and its plain twin). p256: the key's limbs in p256ScalarInRange, dM, the nonce v and its Montgomery form kM, RFC 6979's K and V each time the next replaces it, the nonce point and its scratch, and the multiply's accumulator and the comb entry it selected (#628: p256BaseMultWith wipes the entry, its callers the scratch and accumulator; the comb's table is a function of G alone and is not wiped; names at 6e11fa6). RFC 6979's HMAC is now written out over Sha256 (p256Mac) so that both key blocks, both hashers' state, block and schedule, and the inner digest are its own to wipe. x25519: the clamped scalar copy and all fourteen ladder elements; the shared secret leaves as a Secret<u8[]> too. What is still not reached, and is recorded rather than claimed: a scalar the compiler keeps in a register or spills to the stack (the ladder's swap and bit, a limb in flight), which no store in the language can name; a buffer a push outgrew, no longer the array's; and nish/crypto/hmac's own instances, which p256 no longer uses. crypto_p256, crypto_x25519 and their _f64 twins answer every vector as before, through adapters that hold the key as a Secret (tests/link/crypto_p256/plain.ts, crypto_x25519/plain.ts). Signing over caller-owned scratch (WP34, #463). p256SignSha256 makes its points and hashers with new, so it stores allocations of its own and no arena scope may release around it (NL2424): every signature kept them, 9,312 bytes a TLS connection over the carrier (#489). p256SignSha256Into signs in a P256SignScratch made once and writes r || s into the caller's window, inside an arena block of its own, so a signature keeps 0 bytes (crypto_p256: fifty signatures, each measured on its own, move neither Arena.mark() nor Arena.used()), and it answers what p256SignSha256 answers byte for byte (RFC 6979 A.2.5, and every message length 0 to 199 under four keys). The key is still read only inside expose / exposeWith, and a function exposeWith runs may not write its argument (NL2450), so the three steps that read the key — its range check, RFC 6979 §3.2 steps d and f, and s = k^-1 (z + r d) — compute on fresh arrays and wipe them (the message holding the key, dM, and the HMAC's key block, hash value, schedule and tail), and only their answer leaves: the next K, which is copied into the scratch and wiped, and s. That is why the path hashes with SHA-256 written out over plain arrays rather than Sha256 or HmacSha256Scratch, whose state such a step would have to write. Before it returns it wipes the scratch's K, V, V || 0x00, k^-1, the nonce point, which is the comb's accumulator, and the comb's point scratch, as p256SignScalar does, and p256BaseMultWith wipes the entry it selected (#628, replacing p256ScalarMultWith, which wiped its window table, accumulator and entry; names at 6e11fa6). Not reached, as in p256Sign: the fresh limbs inside p256FieldInvert and p256Below (which see the nonce point's Z and V - n). The arena block releases them, which frees but does not zero; p256Sign leaves the same values in memory it keeps. Since #758 both paths invert the nonce with p256ScalarInverse (ECC-4), which wipes its own d, e, f, g and transition matrix; what it leaves is in registers or spill slots no store in the language names: zeta, the divsteps' u, v, q, r and their masks, p256UpdateDe30's and p256UpdateFg30's 64-bit carries and md / me, and p256AddOrder30's masks. p256ScalarInvert, which they called before, was verification's until K5 and saw only public values; verification now calls p256ScalarInverse too (ECC-4). |
| ECC-3 | Low (documentation) | THIRD_PARTY_NOTICES.md (the tests/link/crypto_wycheproof/ecdsa_secp256r1_sha256.ts row) |
The row says the file holds "all 484 cases and the 113 group keys" of one Wycheproof file. As first written, this change put five files' cases there, ECDSA and X25519, as its header said, so the row no longer said what the file derives from, which a notice row must. third-party-licence reads only the file and licence-text columns, so it could not catch this. |
Fixed in this change. The X25519 cases moved to tests/link/crypto_wycheproof/x25519.ts, with the same upstream notice and a row of its own (x25519_test.json, 518 cases), and crypto_x25519/wycheproof.ts reads them from there. The ECDSA row now names its four files and their case and group-key counts. Layout and documentation only: no value of any vector changed, and crypto_p256* and crypto_x25519* answer as before. |
| ECC-4 | None (a change after this audit, recorded) | std/crypto/p256.ts:3751 (p256ScalarInvert), :4931 (p256SignScalar's inversion of kM), :5496 (p256SignSha256Into's, of sc.kM) (at c8a00d6); the new functions by name: p256ScalarInverse, p256ToSigned30, p256FromSigned30, p256Divsteps30, p256UpdateDe30, p256UpdateFg30, p256AddOrder30, p256Normalize30 |
The nonce is inverted by safegcd (#758). Both signing paths inverted k by Fermat, k^(n-2) by square-and-multiply on the public exponent: 776,501 Ir of a signature's work. They now call p256ScalarInverse, Bernstein and Yang's divsteps in libsecp256k1's constant-time form, ported from libsecp256k1 v0.6.0's src/modinv32_impl.h (MIT, std/crypto/LICENSE-libsecp256k1): nine signed 30-bit limbs, twenty batches of thirty divsteps (600, past the 590 that bound any 256-bit input), each batch a 2x2 transition matrix applied to (f, g) and to (d, e) mod n, then one Montgomery multiply by R^3, because the divsteps invert a R as a plain number. Every product is 32 by 32 bits into 64. Every selection is a mask, the loop counts are constants and nothing divides (CT-2). Agreement: it answers the Fermat ladder's value (p256SeamScalarFermat, kept in tests/link/crypto_p256_inverse/seam.ts.in since verification stopped using Fermat) bit for bit on 10,794 scalars (the inverses of 2 and n - 1 that arithmetic gives; the edges 0, 1, 2, 3, n - 2, n - 1, n, n + 1 and 2^256 - 1, every 2^k and 2^k - 1, every byte repeated across all 32, and n plus and minus each 2^(30 j); and a seeded corpus of 10,000), natively and under WASI: "p256 inverse: safegcd and Fermat give the same inverse for every scalar of tests/link/crypto_p256_inverse, natively" and its WASI twin, p256 inverse: the `--profile wasi` build (sysroot ${WASI_SYSROOT}) prints the same expected.out under Node's WASI. A zero answers zero, as Fermat's does. crypto_p256* answer every signature as before, RFC 6979 A.2.5's byte for byte. What ct_asm reads: ct_asm_p256's p256Divsteps30 (the module's divstep loop body thirty times, held to the module text by "ct_asm: ct_asm_p256's p256Divsteps30 is thirty copies of std/crypto/p256.ts's divstep loop body"), p256UpdateDe30 and p256UpdateFg30 with their limb loops unrolled, each passing on x86-64, x86-64-v3 and aarch64 with the promise "no branch, call, secret-indexed access or secret-dependent latency"; ct_asm_refused's leakyDivstep, which tests g's low bit with an if, is refused for a conditional branch on all three. What remains discipline: the twenty-batch loop, the conversions to and from signed-30, p256Normalize30 and the limb loops of the module's own functions, which branch only on counters and lengths. The wipe: p256ScalarInverse wipes d, e, f, g and the matrix t; tests/wipes/crypto.js counts 3 volatile memsets for it (d, e and f) and 3 more in each signing path. opt promotes g and t to stack slots and turns their wipes into volatile i32 zero stores, one per limb, which that counter does not see, so a check of their own pins them: "crypto: the wipes survive opt -O2 (p256ScalarInverse's g and t, nine and four volatile i32 zero stores)", which fails with either wipe deleted. Not reached, as ECC-2 and X509-7 record for their own: the secret-derived scalars the compiler keeps in registers or spills to the stack, which no store in the language names — p256Divsteps30's locals f, g, u, v, q, r and zeta and its masks, p256UpdateDe30's and p256UpdateFg30's u, v, q, r, md and me and their 64-bit carries, and p256AddOrder30's masks. Measured: callgrind, 64 inversions through the crypto_p256_inverse seam with its own 4,003 Ir per call taken out: Fermat 776,501 Ir per inversion, safegcd 33,661, 23.1x fewer. Verification too (WP34 K5): p256Verify inverts its public s with the same constant-time p256ScalarInverse, and p256ScalarInvert and its bit reader p256Bit left the module; the Fermat ladder lives on only in tests/link/crypto_p256_inverse/seam.ts.in, as the reference the safegcd is held to on the same 10,794 scalars. A variable-time twin (libsecp256k1's modinv32_var) was not written: s is public, so it would be allowed, but it could save at most the constant-time inversion's own 33,661 Ir (0.4% of a verification) and would add a second path to audit and hold to Fermat. No secret path changed, so ct_asm_p256 is unchanged. Callgrind, Ir per call as the difference of 3 and 1 calls over 2 of bench/p256.ts built against each module, base bf63d260 and a byte-identical copy of it (0 Ir band): verification 9,179,460 → 8,437,142 (−8.1%). |
|
| ECC-5 | None (a change after this audit, recorded) | std/crypto/ed25519.ts (new) by name: ed25519PublicKey / ed25519PublicKeyExposed, ed25519Sign / ed25519SignExposed, ed25519Verify, and what they reach (ed25519ScalarMult, ed25519Digits, ed25519Table, ed25519Select, ed25519Add, ed25519Double, ed25519Encode, ed25519Decode, ed25519Reduce, ed25519MulAdd, ed25519ScalarCanonical, ed25519Expand, ed25519Challenge); std/crypto/x25519.ts's field functions, now exported, and f25519Pow250, split out of f25519Invert so both inversions and Ed25519's square root share the chain |
Ed25519 signatures (RFC 8032 §5.1, #788), written from the RFC. The field is X25519's, imported; SHA-512 is nish/crypto/sha512's. Points are extended twisted Edwards coordinates (a = -1) with the complete addition of Hisil, Wong, Carter and Dawson, so no input steers a formula down another path. Constant time, by discipline: the secret scalar (the clamped seed hash, and the nonce) is recoded into 64 signed radix-16 digits; each step doubles four times and adds the entry for the digit, chosen by reading all eight entries of the table and keeping one under a mask, and negated by a masked swap and a masked select. The mask arithmetic is f25519Add64 / f25519Sub64 / f25519Mul64, which wrap rather than branch. The scalar reductions mod L, ed25519Reduce (512 fixed steps of a shift and a masked conditional subtraction over 32-bit limbs in u64) and ed25519MulAdd (a 16 by 16 schoolbook product of 16-bit limbs, then ed25519Reduce), branch only on bit and limb positions. Every if and loop bound in the signing path is on a position or a length. f25519Mul, f25519Square and the swap are the functions ct_asm reads for X25519 (ct_asm_x25519); the Ed25519 functions themselves are read here, not by ct_asm. Verification is variable time: every input to ed25519Verify is public. It is cofactorless ([S]B = R + [k]A, checked by encoding [S]B - [k]A (as [S]B plus [k] times the negated key) and comparing with R's bytes), refuses an S of L or more (§5.1.7 step 1, the malleability of §8.4), a key whose y is p or more, a key off the curve, and x = 0 with the sign bit set (§5.1.3); an R that is not a canonical encoding never matches the canonical encoding it is compared with. A key of small order is accepted, as RFC 8032 allows: under the order-2 key (0, -1), R = the identity and S = 0 verify for every message whose k is even, and tests/link/crypto_ed25519 pins both answers. A caller that needs a signature to bind one key rejects small-order keys itself; the module does not. Agreement: RFC 8032 §7.1's five vectors (TEST 1, 2, 3, 1024 and SHA(abc)) — public key, signature and verification — natively and under --number-mode f64, and the negative cases in tests/link/crypto_ed25519. A one-off check, not standing evidence and not in the repository: on 2026-10-22, while the module was written (before fb78967), 300 random seeds and messages of 0 to 129 bytes agreed with node:crypto (OpenSSL) on every public key and signature byte for byte, every verification, and the answer for each signature under a random 32-byte key. The seed is a Secret: ed25519PublicKey and ed25519Sign run inside expose / exposeWith and wipe the seed's hash (scalar and prefix), the nonce's 64-byte hash and the nonce, the digits, x's encoding, the accumulator point, the scratch (the formula temporaries, the selected entry and the table point), ed25519MulAdd's limbs, product and bytes, and both SHA-512 states. "crypto: the wipes survive opt -O2 (Ed25519's seed hash, nonce, hashers, digits, point and scratch in ed25519PublicKeyExposed and ed25519SignExposed)" pins ed25519ScalarMult 1, ed25519Encode 1, ed25519PublicKeyExposed 26 and ed25519SignExposed 38; ed25519Reduce's acc and diff are promoted to stack slots and pinned as two groups of eight volatile i64 zero stores by "crypto: the wipes survive opt -O2 (ed25519Reduce's acc and diff, eight volatile i64 zero stores each)". A one-off mutation check on 2026-10-22, before fb78967: one wipe of each kind was deleted in turn and its roots' counts dropped; the pins, not that check, are what holds now. Not reached: the scalars the compiler keeps in registers or spills (a digit, the select and negation masks, ed25519Reduce's carry and borrow, ed25519MulAdd's carry), as ECC-2 records for the ladder; f25519Mul's doubled limbs and 19-limb product (f25519Square is f25519Mul), which it allocates and does not wipe; the locals of the f25519Pow250 / f25519Invert chain in ed25519Encode, which hold powers of Z of a secret multiple of B; and f25519Encode's internal copy of y. Each is a function of the public output or of a secret point the caller already wipes, and none holds the scalar. The table is a function of B (or, in verification, of a public key) and is not wiped. Message length: ed25519Sign and ed25519Verify panic on a message longer than 2^31 - 1 bytes, as sha512 does: the length does not survive toI32 under --number-mode f64, so both would hash a prefix, and a signature would verify for any longer message that shares it. A 2 GiB test is impractical, so "crypto: ed25519Sign and ed25519Verify panic on a message longer than 2^31 - 1 bytes (--number-mode f64)" reads the f64 IR for each function's compare and panic instead. Tests: "link/crypto_ed25519: exits with 0 and stdout matches expected.out", "link/crypto_ed25519_f64: exits with 0 and stdout matches expected.out", the two wipe checks above, the length-guard check, and the curves family of "crypto-bench: every family (aead, curves, handshake, hash, x509) prints its expected.txt checksums from every twin, and its portable columns are portable". |
|
| ECC-6 | None (a change after this audit, recorded) | std/crypto/p256.ts by name: p256Safegcd (ECC-4's p256ScalarInverse body, now taking the modulus and its inverse mod 2^30), p256FieldInvert, p256Prime30, p256FieldR3, p256UpdateDe30, p256AddModulus30 (was p256AddOrder30); p256Verify and the new p256DoubleMultPublic, p256Wnaf, p256ByteBit, p256OddMultiples, p256WnafAdd |
The field is inverted by safegcd, and verification is one wNAF pass (#1430). Field inversion: p256FieldInvert, the inverse of a Z that follows the key or the nonce (the public key, ECDH's shared x and the signature's r), was raised to p - 2 by square-and-multiply on that public exponent; it now calls p256Safegcd, ECC-4's divsteps with p's signed-30 limbs and p^-1 mod 2^30 = 0x3fffffff in place of n's, then one Montgomery multiply by R^3 mod p. The divsteps and matrix updates are the functions ct_asm already reads; p256UpdateDe30 takes the modulus's inverse as an argument, and ct_asm_p256's copy does too and runs three known inverses mod p (1/2, 1/(p - 1) and 1/Gx) beside its scalar ones, passing on x86-64, x86-64-v3 and aarch64. A copy given one secret-indexed load of a table in p256UpdateDe30 was refused on all three (a one-off check while this was written, reverted). The wipe: p256Safegcd wipes d, e, f, g and t as p256ScalarInverse did; opt now promotes f too, so the counter sees 2 memsets per call (d and e) and "crypto: the wipes survive opt -O2 (p256Safegcd's f, g and t, nine, nine and four volatile i32 zero stores)" pins the rest. The roots move to p256PublicKeyExposed 20, p256SignExposed 97, p256SignSha256Into 60 and p256ScalarInverse 2. Not reached: as ECC-4, the divsteps' and updates' locals in registers and spill slots. Verification: p256Verify computed u1 G and u2 Q with two p256ScalarMult ladders and added them. It now calls p256DoubleMultPublic: u1 and u2 recoded as width-5 wNAF (p256Wnaf, digits odd in [-15, 15] with at least four zeros after each), eight odd multiples of G and of Q (p256OddMultiples), and one pass of 256 shared doublings, each nonzero digit adding its entry or the entry with Y negated (p256WnafAdd). The complete formulas leave no exceptional case (P + P, P - P and the identity among them). It is variable time: the digits, the additions skipped and the entries read follow u1 and u2, which are functions of the digest, the signature and nothing else, as Q is the public key. Its doc says so and says it may be given nothing secret; signing and ECDH keep the comb and the window. Agreement: crypto_p256* (RFC 6979 A.2.5, the 10 signatures whose u1 G equals u2 Q, u1 = 0, the sum at the identity refused) and Wycheproof's P-256 ECDSA files answer as before, natively and under --number-mode f64. Measured: valgrind (callgrind), Ir per call as the difference of 3 and 1 calls over 2, against a byte-identical copy of the base for the noise band (0 Ir: the copy answered the base's counts exactly): verify 17,425,698 → 9,101,720 (−47.8%), sign 2,429,142 → 1,910,566 (−21.3%), ECDH 8,590,013 → 8,070,973 (−6.0%). |
|
| ECC-7 | None (a change after this audit, recorded) | std/crypto/p256.ts by name: p256BaseMultWith, p256BaseRecode, p256BaseDigit, p256BaseMove, p256BaseSelect, p256SetOrder, the generated p256BaseOffset, p256BaseHalf and p256BaseTable; scripts/gen-p256-table.mjs |
The fixed-base comb is signed (WP39 G4). The 4-tooth comb (15 entries a sub-table, a zero digit's sum computed and dropped by a masked keep) became a signed all-bits-set comb (Hamburg 2012): k is recoded to m = (k + 2^264 - 1) / 2 mod n by p256BaseRecode (a reduction mod n kept or dropped by fiat's conditional move, fiat's scalar add of the generated 2^264 - 1 mod n, and a scalar Montgomery multiply by 2^-1 R mod n), so that every bit of m stands for plus or minus its power of two; 11 combs of 6 teeth 4 bits apart read six bits each, the top one the sign and the other five one of 32 entries, none the identity. 44 mixed additions and 3 doublings replace 64 additions (and 64 masked keeps) and 3 doublings; the table grows from 240 entries (15 KiB) to 352 (22 KiB). A P256SignScratch builds its table on its first signature, in p256SignSha256Into before the call's arena block opens, where it built the 15 KiB one in its constructor, so a server that holds a signer (TlsP256Signer) carries none of it before its first handshake; whether the table is built yet is public (net_tls_memory: the first sign keeps the table and no more, 22,552 bytes, and none after it moves Arena.mark()). The read: p256BaseSelect scans all 32 entries of its comb, p256BaseMove ORing each entry's 16 limbs under an all-ones ctEq mask that is set for one entry only, and negates Y by fiat's subtraction from zero and conditional move on the top tooth: no address, branch or skipped addition follows the scalar. p256BaseDigit reads a position past bit 255 (comb 10's two top teeth) by a mask on the public position, not a branch, so its ct_asm copy holds none. Checked: tests/link/crypto_p256_agree rebuilds every entry from G by the complete doubling and addition and compares it byte for byte ("table: 352 of 352 entries rebuilt from G"), and sweeps each comb digit through its recoding so that all 656 reachable (comb, entry, sign) choices are read; the comb answers p256ScalarMult on every scalar as before. ct_asm_p256 holds copies of the recoding, p256FiatScalarAdd, the digit, the move, the read and the step, passing on x86-64, x86-64-v3 and aarch64. The wipe: p256BaseMultWith wipes the recoded scalar (s.comb) beside the selected entry, and p256WipeScratch wipes s.comb too: the pins move to p256BaseMultWith 4, p256PublicKeyExposed 22, p256SignExposed 99, p256SignSha256Into 62 and p256Ecdh / p256EcdhExposed 28. Not reached: the digit, its top tooth and the masks, in registers. Measured: valgrind (callgrind), Ir per call as the difference of 3 and 1 calls over 2, against a byte-identical copy of the base (0 Ir band): sign 1,908,671 → 1,411,845 (−26.0%), key generation 1,777,052 → 1,273,530 (−28.3%); ECDH and verification do not call it. |
|
| ECC-8 | None (a change after this audit, recorded) | std/crypto/p256.ts by name: p256FiatMul, p256FiatSquare, p256FiatAdd, p256FiatSub, and the helpers p256FiatWord64, p256FiatAddcarryxU64, p256FiatAddcarryxU64Out2, p256FiatSubborrowxU64, p256FiatSubborrowxU64Out2, p256FiatMulxU64Hi and p256FiatCmovznzU64 |
The field arithmetic is on 64-bit limbs (WP34 K5). Field multiply, square, add and subtract are fiat-crypto's p256_64.c (same commit), over four 64-bit limbs packed from and stored to the same eight u32 words, so the Montgomery R stays 2^256, the comb table needs no regeneration, and the scalar arithmetic, the encodings and the safegcd inversions are unchanged. Nish has no 128-bit integer: mulx_u64's high word is four 32 × 32 products (p256FiatMulxU64Hi), and the carry and borrow are bit 63 of `(a & b) |
((a |
Properties verified
Each property below held on the base commit and is now pinned by a test that would fail if it stopped holding.
P-256 verification (p256Verify; tests/link/crypto_p256/suite.ts, run by
crypto_p256 and, in f64 mode, crypto_p256_f64):
-
rorsequal to 0, to n or above n is refused (SEC 1 §4.1.4 step 1): "r = 0 is refused", "s = 0 is refused", "r = n is refused", "s = n is refused", "r = n + 1 is refused", "s = n + 1 is refused", and Wycheproof's range cases. -
A signature of any length other than 64 bytes is refused: "a 63-byte signature is refused" and "a 65-byte signature is refused".
-
A public key off the curve, with a coordinate of p or more, not 65 bytes, not prefixed 0x04, or the identity (0x00, or 65 zero bytes) is refused (SEC 1 §3.2.2): "a key with a flipped bit in x/y is off the curve", "the same point with x = 5 + p is refused", "a key with y = p is refused", "a key with prefix 0x03 is refused", "the identity's SEC 1 encoding, 0x00, is refused", "65 zero bytes are refused", "0x04 then (0, 0) is refused", and the 64- and 66-byte cases.
P-256 has cofactor 1, so a point on the curve is in the prime order group, and no invalid-curve or small-subgroup key survives the curve equation.
-
A sum u1·G + u2·Q at the identity is refused: "a sum u1 G + u2 Q at the identity is refused". It is refused twice over. The explicit check is
p256FiatNonzero(sum.z) === 0, and fiat's outputs are fully reduced, so a zero Z is exactly the all-zero limbs. And even without that check, the identity's x reads as 0, which norin [1, n) equals (see the mutation check above). -
A sum that is a doubling (u1·G = u2·Q) goes through the complete formulas and verifies: "a signature whose u1 G equals u2 Q (the sum is a doubling) verifies". u1 = 0 works too: "the signature of the digest 0 verifies (u1 = 0)".
-
The digest is taken as its leftmost 256 bits and reduced once modulo n (SEC 1 §4.1.4 step 5; RFC 6979 bits2int). "a 48-byte digest signs as its leftmost 32 bytes", "the digest n signs as the digest 0", "the digest n + 5 signs as the digest 5", "the signature of 5 verifies under the digest n + 5", and all 886 cases of the two SHA-512 files.
-
High
sis accepted, by design. ECDSA is malleable: (r, n − s) verifies whenever (r, s) does. FIPS 186-4 and SEC 1 require no low-srule, and this module adds none. "(r, n - s) of "sample" verifies as well: ECDSA is malleable".p256Verify's doc now says so, and says that a protocol needing one signature per message must refuse the upper half itself. -
Verification never panics on any length of key, digest or signature. The length tests above give it 1-, 64- and 66-byte keys and 63- and 65-byte signatures, and the 594 P1363 cases hand it signatures of 2, 16, 26, 32, 40, 66, 68 and 82 bytes as well as 64.
P-256 keys and signing (p256PublicKey, p256Sign; the same suite):
- A private key of 0, of n or above n, or not 32 bytes is refused by both functions: "p256PublicKey(0) is null", "(n)", "(n + 1)", "(2^256 - 1)", the 31- and 33-byte cases, "p256Sign with private key 0 is null", "… n is null", "… n + 1 is null", "… 2^256 - 1 is null", and "p256SignSha256 with a 31-byte key is null" and "… 33-byte key is null".
-
The nonce is RFC 6979 §3.2's for HMAC-SHA-256: A.2.5's
kis pinned throughrfor "sample" and "test", and the whole signatures agree byte for byte ("A.2.5 SHA-256 "sample": r || s", "… "test": r || s"). The differential run agreed on 408 more.h1is bits2octets, the digest reduced mod n, which is why the digests n and 0 sign identically. - The public keys of 1 and n − 1 are G and −G: "the public key of 1 is G" and "the public key of n - 1 is -G".
P-256 ECDH (p256Ecdh, added after this audit for TLS's secp256r1 share;
tests/link/crypto_p256_ecdh/main.ts, run by node tests/run.js crypto_p256_ecdh).
SEC 1 §3.3.1 over a validated peer point: the key must be in [1, n − 1] and
32 bytes, the point an uncompressed SEC 1 point on the curve
(p256DecodePoint), the product is computed inside exposeWith with
p256ScalarMult, and its x leaves as a Secret<u8[]>.
-
Wycheproof's
ecdh_secp256r1_ecpoint_test.json(the commit above), through the public function with the key as aSecret: "wycheproof ecdh: 330 shared secrets as published, 25 public keys refused, of 355". The 25 refused are the 24invalidcases and the oneacceptablecompressed point, which RFC 8446 §4.2.8.2 forbids. tcId 3's shared x is zero and isvalid, so a zero x is answered. A product at infinity is refused too, but defensively: the identity is refused by its length before it is decoded, and on a prime-order curve a key in [1, n) times a point on it never gives infinity, so that branch is not reached. - A key of 0, n, above n, or not 32 bytes, the identity, an empty or truncated point, a compressed point and a point off the curve are refused ("refusals: 12 keys and points checked"), and both sides of 25 exchanges over five keys agree, with 1 · G's x as G's ("exchanges: 25 of 25 pairs agree both ways").
-
Every intermediate is wiped: "crypto: the wipes survive opt -O2 (P-256
ECDH's product, scratch, 1 / Z and shared x in p256EcdhExposed)" in
tests/wipes/crypto.jspins 25 volatile wipes inp256Ecdh. What a wipe cannot reach is as ECC-2 records forp256Sign: values in registers and spill slots.
X25519 (x25519, x25519Base; tests/link/crypto_x25519/main.ts and
wycheproof.ts, with the Wycheproof run repeated in f64 mode by
crypto_x25519_f64):
- The scalar is clamped as RFC 7748 §5 says, on a copy: "the scalar is clamped on a copy, not in place", and every Wycheproof case, whose private keys are unclamped.
-
The top bit of
uis masked before anything else, and auof p or more is taken modulo p: "a u with its top bit set gives the same answer as with it clear", "u = p decodes as 0 …", "u = p + 1 decodes as 1", "u = p + 9 decodes as 9", "u = p with its top bit set still decodes as 0", and Wycheproof's 19NonCanonicalPubliccases. - The answer is always canonical, below p: "the answer for u = p + 1 is below p", "… p + 9 …", "an all-ones u … answers below p", and every Wycheproof shared secret compared byte for byte.
-
Low-order points answer all zeros, which is returned rather than refused, as
§6.1 leaves the check to the protocol: "u = 0 answers all zeros, not null",
six "low-order u … answers all zeros" checks, and Wycheproof's 31
cases flagged both
LowOrderPublicandZeroSharedSecret. - Twist points answer RFC 7748's value: Wycheproof's 221
Twistcases. -
Anything but 32-byte arguments answers
null: the seven length checks incrypto_x25519and "a 31-byte scalar answers null" incrypto_x25519_f64.
Constant time (node tests/run.js ct_asm): the P-256 field and scalar
arithmetic, its conditional move, the table read by a secret digit, the
complete addition and doubling and one window step, and the X25519 field
arithmetic, conditional swap and ladder step have no branch, no call the
checker cannot follow, and no load or store at a secret address, on x86-64 and
aarch64. The fixtures' copies were checked above to match the module code.
The loops around these steps, the inversions (square-and-multiply on the public exponents p − 2 and n − 2, or X25519's fixed addition chain; since #758 the nonce's is safegcd's twenty fixed batches, whose divsteps and matrix updates ct_asm reads as copies, ECC-4, and since #1430 the field's is the same safegcd modulo p, ECC-6), the encodings and the nonce derivation branch only on public positions. That was confirmed by reading, and it remains discipline rather than proof, as the module headers say. The one branch on a secret is RFC 6979's retry when a candidate nonce is not below n. The RFC prescribes it, it happens about once in 2^32 signatures, and it reveals only that a discarded value was large.
The fixed-base comb (#663, after this audit; anchors at 6e11fa6).
p256PublicKey and p256Sign now compute k·G with p256BaseMult
(std/crypto/p256.ts:4662, over p256BaseMultWith at :4675): a 4-tooth
comb over p256BaseTable (:4119), 240 affine multiples of G that
scripts/gen-p256-table.mjs computes with BigInt, in 4 rows of 16 mixed
additions with a doubling between rows. p256Verify kept
p256ScalarMult, which is also the comb's reference (since #1430 it runs one
variable-time wNAF pass over public values instead, ECC-6). The module had no ECDH
entry point then (p256Ecdh came later, see "P-256 ECDH"); the ECDH below is the test corpus, Wycheproof's
ecdh_secp256r1_ecpoint private keys multiplied through p256ScalarMult in
tests/link/crypto_p256_agree.
Since ECC-7 the comb is signed: 11 combs of 6 teeth 4 bits apart over 352 affine entries, the scalar recoded first, 44 mixed additions and 3 doublings. What follows describes it; the 4-tooth comb's 15-entry read and masked keep are gone.
-
Agreement. The comb answers what
p256ScalarMult(G, k)answers, byte for byte, on RFC 6979 A.2.5's three scalars, 779 edge and per-digit scalars (each comb's 64 digits swept through the recoding, so that all 656 reachable (comb, entry, sign) choices are read), therandsof all 1,104 64-byte signatures of Wycheproof's two P1363 files taken as scalars, the 355 private keys ofecdh_secp256r1_ecpoint(330 shared secrets as published, 25 keys refused), and a seeded corpus of 10,000 scalars, 625 of them also signing through bothp256SignSha256andp256SignSha256Into: "p256 agree: the fixed-base comb and the variable-base window give the same bytes for every scalar of tests/link/crypto_p256_agree, natively", and under Node's WASI, "p256 agree: the `--profile wasi` build (sysroot ${WASI_SYSROOT}) prints the same expected.out under Node's WASI".The table is what the generator writes: "p256: the comb table in std/crypto/p256.ts is what scripts/gen-p256-table.mjs generates"; and the same program rebuilds every entry from G with the module's complete doubling and addition, independently of the generator's BigInt, and compares it byte for byte ("table: 352 of 352 entries rebuilt from G" in its expected.out).
-
What ct_asm reads.
tests/cases/ct_asm_p256holds copies of fiat's scalar add (p256FiatScalarAdd), the reduction's subtraction (p256SubBorrow), the recoding (p256BaseRecode), the digit (p256BaseDigit), one entry's masked move (p256BaseMove), the 32-entry signed read (p256BaseSelect), the mixed addition (p256PointAddMixed, Renes, Costello and Batina's Algorithm 5) and one whole step of the comb (p256BaseStep, the body ofp256BaseMultWith's inner loop), and itsmainbuilds the signed table on the copies and reproduces A.2.5's public key and bothrs through them. Each passes on x86-64, x86-64-v3 and aarch64, following its calls into the field functions:ct_asm: ${name} ${spec.name} on ${at}: ${spec.promise}with the promise "no branch, call, secret-indexed access or secret-dependent latency". A read of one entry at the digit's offset is seeded to fail:ct_asm_refused'sleakyBaseRead, "refused for a load or store at a secret address" on both targets. -
What remains discipline. The copies compute their offsets with
wrappingAdd/wrappingMuland read withuncheckedGet, so they hold no branch at all; the module's own functions do not. Itsp256BaseSelectcomputes(c * entries + j) * P256_BASE_ENTRYwith checked arithmetic, whose overflow test branches on the publiccand loop counterj;p256BaseDigitandp256BaseMoveguard their lengths;p256BaseRecodereads the scalar's 32 bytes into limbs by public positions (p256LimbsFromBytes), and itsm - nins.t0is wiped with the scratch; and the 4-row and 11-comb loops ofp256BaseMultWith, with its test before each doubling, branch on loop counters. None of these is read by ct_asm; each was read here and depends on no bit of the scalar. -
The wipe.
p256BaseMultWithwipes the selected entry and the recoded scalar before it returns, and its callers wipe the scratch (the recoded scalar again among it) and the accumulator, as for the window: "crypto: the wipes survive opt -O2 (P-256's selected comb entry and recoded scalar in p256BaseMultWith; the scratch and accumulator in p256PublicKeyExposed, p256SignExposed and p256SignSha256Into)", a group oftests/wipes/crypto.jsthat pinsp256BaseMultWithat 4 volatile wipes,p256PublicKeyExposedat 22,p256SignExposedat 99 andp256SignSha256Intoat 62 (3, 18, 93 and 56 at #663; 96 and 59 after #758's inversion, ECC-4; 20, 97 and 60 after #1430, ECC-6; one more for the recoded scalar inp256BaseMultWithand one inp256WipeScratch, ECC-7).Not reached: the digit, its top tooth, the
ctEqmasks and the scalar's bytes as they are read, which live in registers or spill slots no store in the language names, as ECC-2 records for the ladder'sswapandbit. The table is a function of G alone and is not wiped.
Doc corrections for the security-policy stage
These lay outside this stage's files, so they were listed here rather than made; the security-policy stage made them all:
-
std/README.md, "Three rules hold across the modules": it said the TLS 1.3 module makes the check, and no such module existed yet. It should say, asx25519's doc now does, that nothing in the tree makes the all-zero check yet and that every caller must (ECC-1). -
std/README.md, thecrypto/p256.tsrow: "Reproduces" should name all four Wycheproof files now run (ecdsa_secp256r1_sha256,_sha256_p1363,_sha512,_sha512_p1363). The row could also say thatp256Verifyaccepts highs, since ECDSA is malleable. -
std/README.md, thecrypto/x25519.tsrow: "Reproduces" should add Wycheproofx25519_test.

