/**
* Tests that drive the compiled module directly through its integer ABI, below
- * the host layer, for two properties the public API cannot observe.
+ * the host layer, for three properties the public API cannot observe.
*
* **No secret residue.** After `derive`, `sign` and a failed `sign`, followed
* by the `clearMemory()` the host runs on every unlock, linear memory must not
* reads it with a strict `=== 1`; this is the property that keeps a looser
* comparison there from ever mattering.
*
+ * **Inputs scrubbed on every path.** Each export must leave the input buffers
+ * it reads zeroed when it returns or throws, before `clearMemory()` repeats the
+ * job. The residue diff runs after `clearMemory()`, so it cannot see this. Each
+ * buffer is located by a pattern written through its setter, the message
+ * buffer is also written past the length the call declares, and every success
+ * and throw path is read back before `clearMemory()`.
+ *
* Positive controls prove each check can fire: the search finds the public key
* before `clearMemory()`, the diff sees the public key output, a second probe
- * with `clear_t()` removed from `crypto_derive` must show residue, and both
- * result values must actually occur.
+ * with `clear_t()` removed from `crypto_derive` must show residue, a third with
+ * the `INPUT_SIG` scrub removed from the length check in `verify` must fail the
+ * input check there and nowhere else, and both result values must actually
+ * occur.
*
* Probes are compiled under `build/module/` with the project's own
* `asconfig.json`, changed only in the copy.
/** The line a dropped scrub removes; `from` must occur once inside `fn`. */
const DROPPED_SCRUB = { file: 'src/assembly/crypto_derive.ts', fn: 'crypto_derive', from: '\n\tclear_t()' }
+/** A throw-path scrub that only the input-buffer check can see. */
+const DROPPED_INPUT_SCRUB = { file: 'src/assembly/index.ts', fn: 'verify', from: '\n\t\tINPUT_SIG.fill(0)' }
+
/** Copies the sources, exports memory, optionally drops one line, and compiles. */
async function probe (name, drop) {
const dir = new URL(`${name}/`, work)
/** Input-dependent bytes left after `clearMemory()`, by memory diff. */
const residue = (mod, op) => differing(run(mod, op, keyOf(1)).after, run(mod, op, keyOf(2)).after)
+/**
+ * Nonzero bytes that occur nowhere else in memory, so a search finds exactly the
+ * buffer written. Hashed from the name: patterns sharing an arithmetic step
+ * would contain one another.
+ */
+const pattern = (name, n) => createHash('blake2b512').update(name).digest().subarray(0, n).map(b => b | 1)
+const PATTERNS = { INPUT_MSG: pattern('INPUT_MSG', 32), INPUT_PRV: pattern('INPUT_PRV', 32), INPUT_PUB: pattern('INPUT_PUB', 32), INPUT_SIG: pattern('INPUT_SIG', 64) }
+
+/**
+ * Locates each input buffer by writing its pattern through its setter, and
+ * returns the address and byte length of each, with memory cleared again.
+ */
+function inputBuffers (x) {
+ x.setInputMsg(0, ...words(PATTERNS.INPUT_MSG))
+ x.setInputPrv(...words(PATTERNS.INPUT_PRV))
+ x.setInputPub(...words(PATTERNS.INPUT_PUB))
+ x.setInputSig(...words(PATTERNS.INPUT_SIG))
+ const mem = Buffer.from(x.memory.buffer)
+ const lengths = { INPUT_MSG: x.MAX_MESSAGE_BYTELENGTH.value, INPUT_PRV: 32, INPUT_PUB: 32, INPUT_SIG: 64 }
+ const found = {}
+ for (const [name, bytes] of Object.entries(PATTERNS)) {
+ const at = mem.indexOf(bytes)
+ if (at < 0 || mem.indexOf(bytes, at + 1) >= 0) throw new Error(`cannot locate ${name}`)
+ found[name] = [at, lengths[name]]
+ }
+ x.clearMemory()
+ return found
+}
+
+/**
+ * Every success and throw path of every export, each given only the inputs it
+ * reads. The message is also written at the top of its buffer, past the
+ * declared length, so a scrub scoped to that length leaves it behind.
+ */
+function inputPaths (mod) {
+ const prv = keyOf(1)
+ const pub = derive(instance(mod), prv)
+ const max = instance(mod).MAX_MESSAGE_BYTELENGTH.value
+ const msg = (x) => {
+ x.setInputMsg(0, ...words(PATTERNS.INPUT_MSG))
+ x.setInputMsg(max - 32, ...words(PATTERNS.INPUT_MSG))
+ }
+ const keys = (x, p = pub) => { x.setInputPrv(...words(prv)); x.setInputPub(...words(p)) }
+ const sig = (x) => x.setInputSig(...words(PATTERNS.INPUT_SIG))
+ const record = (x) => { x.setInputMsg(0, ...words(PATTERNS.INPUT_SIG.subarray(0, 32))); x.setInputMsg(32, ...words(PATTERNS.INPUT_SIG.subarray(32))); x.setInputMsg(64, ...words(PATTERNS.INPUT_MSG)); x.setInputMsg(max - 32, ...words(PATTERNS.INPUT_MSG)) }
+ return {
+ 'derive': (x) => { x.setInputPrv(...words(prv)); x.derive() },
+ 'sign': (x) => { msg(x); keys(x); x.sign(32) },
+ 'sign, mismatched public key': (x) => { msg(x); keys(x, PATTERNS.INPUT_PUB); x.sign(32) },
+ 'sign, invalid length': (x) => { msg(x); keys(x); x.sign(max + 1) },
+ 'verify': (x) => { msg(x); x.setInputPub(...words(pub)); sig(x); x.verify(32) },
+ 'verify, invalid length': (x) => { msg(x); x.setInputPub(...words(pub)); sig(x); x.verify(-1) },
+ 'verify_blocks': (x) => { record(x); x.setInputPub(...words(pub)); x.verify_blocks(1) },
+ 'verify_blocks, invalid count': (x) => { record(x); x.setInputPub(...words(pub)); x.verify_blocks(0) },
+ }
+}
+
+/** `path: BUFFER` for every input buffer a path leaves nonzero, read before `clearMemory()`. */
+function unscrubbed (mod) {
+ const left = []
+ for (const [path, call] of Object.entries(inputPaths(mod))) {
+ const x = instance(mod)
+ const buffers = inputBuffers(x)
+ try { call(x) } catch { }
+ const mem = new Uint8Array(x.memory.buffer)
+ for (const [name, [at, length]] of Object.entries(buffers)) {
+ if (mem.subarray(at, at + length).some(b => b !== 0)) left.push(`${path}: ${name}`)
+ }
+ }
+ return left
+}
+
let passes = 0
let failures = 0
function check (name, test, detail = '') {
try {
// a control that cannot be seeded is a failed check, not a crash, so the
// residue checks below still run and report
- const [clean, dropped] = await Promise.all([probe('clean'), probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err)])
+ const [clean, dropped, droppedInput] = await Promise.all([
+ probe('clean'),
+ probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err),
+ probe('dropped-input-scrub', DROPPED_INPUT_SCRUB).catch((err) => err),
+ ])
// positive controls: the search and the diff can both fire
const control = run(clean, 'derive', keyOf(1))
check(`no copy of any secret representation after ${op}`, found.length === 0, found.join(', '))
}
+ // inputs scrubbed by each export itself, on success and throw paths alike
+ const seededInput = droppedInput instanceof WebAssembly.Module ? unscrubbed(droppedInput) : [String(droppedInput?.message ?? droppedInput)]
+ check('input check sees the INPUT_SIG left by a verify length check without its scrub',
+ seededInput.includes('verify, invalid length: INPUT_SIG'), seededInput.join('; ') || 'nothing seen')
+ const left = unscrubbed(clean)
+ check(`every export leaves its input buffers zeroed on all ${Object.keys(inputPaths(clean)).length} success and throw paths`, left.length === 0, left.join('; '))
+
// OUTPUT_VERIFY must only ever hold 0 or 1, across valid, forged, malformed,
// undecodable and degenerate inputs on both verification paths
const x = instance(clean)
console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
-console.log(`2 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+console.log(`3 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
process.exitCode = failures > 0 ? 1 : 0
//! SPDX-License-Identifier: GPL-3.0-or-later
import { constants, derive, sign, verify, verify_blocks } from 'nano25519'
-import { IDENTITY, NANO_ORG_VECTOR, PROBLEM_VECTOR, PYTHON_ED25519_BLAKE2B_VECTORS } from './vectors.mjs'
+import { IDENTITY, NANO_ORG_VECTOR, PROBLEM_VECTOR, PYTHON_ED25519_BLAKE2B_VECTORS, TORSION_VECTORS } from './vectors.mjs'
/**
* @param {string} name
console.log(`${test ? '\x1b[32mPASS' : '\x1b[31mFAIL'}\x1b[0m: ${name}`)
}
+/**
+ * Runs `f`, turning a throw into a string so it can be compared as a result.
+ * @param {() => unknown} f
+ */
+function attempt (f) {
+ try {
+ return f()
+ } catch (err) {
+ return `threw ${typeof err === 'object' && err != null && 'message' in err ? err.message : err}`
+ }
+}
+
const bigBuf = new Uint8Array(128).fill(255)
let inbuf, outbuf, result, test, passes = 0, failures = 0
// and not only in the 64 KiB message sweeps further down.
{
const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
- /** @param {() => unknown} f */
- const attempt = (f) => {
- try {
- return f()
- } catch (err) {
- return `threw ${typeof err === 'object' && err != null && 'message' in err ? err.message : err}`
- }
- }
// the checks below only assert rejections, so assert the baseline too or they die quietly
test = verify(sig, hash, pub) === true && verify_blocks(pub, [{ hash, signature: sig }])[0] === true
failures += +!test
}
+// A nonce offset by a small-order point, R' = rB + T, with S recomputed by the
+// key holder. These are the only signatures whose final equation leaves a
+// torsion difference, so they are the only ones that tell a cofactored check
+// from a cofactorless one, or from a broken one: verify() once rejected every
+// order-8 offset while accepting orders 2 and 4, and the suite stayed green.
+{
+ const { publicKey, blockHash, signatures } = TORSION_VECTORS
+ /** @param {string} hex */
+ const bytes = (hex) => new Uint8Array(hex.match(/.{2}/g)?.map(b => parseInt(b, 16)) ?? [])
+ const offsets = signatures.filter(({ order }) => order > 1)
+ /** @param {{ order: number, torsion: string }} v */
+ const label = ({ order, torsion }) => `order ${order} ${torsion.slice(0, 8)}`
+
+ // the checks below are only as good as the vectors, so pin what they cover
+ test = signatures.map(({ order }) => order).join() === '1,2,4,4,8,8,8,8'
+ && signatures[0].signature === NANO_ORG_VECTOR.signature
+ && verify(signatures[0].signature, blockHash, publicKey) === true
+ && verify_blocks(publicKey, [{ signature: signatures[0].signature, hash: blockHash }])[0] === true
+ check('torsion vectors cover all eight small-order points, and the order-1 row is the verified nano.org signature', test)
+ passes += +test
+ failures += +!test
+
+ let missed = offsets.filter((v) => attempt(() => verify(v.signature, blockHash, publicKey)) !== true
+ || attempt(() => verify(bytes(v.signature), bytes(blockHash), bytes(publicKey))) !== true).map(label)
+ test = missed.length === 0
+ check(`verify accepts a nonce offset by each point of order 2, 4 and 8${test ? '' : ` (rejected ${missed.join(', ')})`}`, test)
+ passes += +test
+ failures += +!test
+
+ missed = offsets.filter((v) => attempt(() => verify_blocks(publicKey, [{ signature: v.signature, hash: blockHash }])[0]) !== false).map(label)
+ result = attempt(() => verify_blocks(publicKey, signatures.map(({ signature }) => ({ signature, hash: blockHash }))))
+ test = missed.length === 0 && Array.isArray(result) && result.join() === 'true,false,false,false,false,false,false,false'
+ check(`verify_blocks rejects a nonce offset by each point of order 2, 4 and 8${test ? '' : ` (accepted ${missed.join(', ')}; batch ${result})`}`, test)
+ passes += +test
+ failures += +!test
+
+ // acceptance must come from the equation, not from the torsion: the same
+ // nonces with the unmodified S, or with one bit of S flipped, must fail
+ missed = []
+ for (const v of offsets) {
+ const stale = v.signature.slice(0, 64) + signatures[0].signature.slice(64)
+ const flipped = bytes(v.signature)
+ flipped[32] ^= 1
+ if (attempt(() => verify(stale, blockHash, publicKey)) !== false || attempt(() => verify(flipped, bytes(blockHash), bytes(publicKey))) !== false) {
+ missed.push(label(v))
+ }
+ }
+ test = missed.length === 0
+ check(`verify rejects a torsion-offset nonce whose S does not match it${test ? '' : ` (accepted ${missed.join(', ')})`}`, test)
+ passes += +test
+ failures += +!test
+}
+
+// An error raised while the mutex is held must release it. derive() and sign()
+// validate their inputs, and verify_blocks() its block count, before taking the
+// lock, so those throws never reach the finally that unlocks; these do.
+{
+ const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
+ /** @type {[string, () => unknown][]} */
+ const inside = [
+ ['verify, invalid message', () => verify(sig, 'zz', pub)],
+ ['verify, invalid public key', () => verify(sig, hash, new Uint8Array(31))],
+ ['verify_blocks, invalid public key', () => verify_blocks(new Uint8Array(31), [{ hash, signature: sig }])],
+ ['verify_blocks, invalid second block', () => verify_blocks(pub, [{ hash, signature: sig }, { hash, signature: 'zz' }])],
+ ['verify_blocks, throwing block getter', () => verify_blocks(pub, [{ hash, get signature () { throw new Error('getter') } }])],
+ ['sign, mismatched public key (wasm abort)', () => sign(hash, prv, new Uint8Array(32))],
+ ]
+ /** @type {string[]} */
+ const leaked = []
+ for (const [name, f] of inside) {
+ const raised = attempt(() => { f(); return 'returned' })
+ const after = attempt(() => verify(sig, hash, pub))
+ if (typeof raised !== 'string' || !raised.startsWith('threw') || raised.includes('mutex') || after !== true) {
+ leaked.push(`${name}: ${raised}; next call ${after}`)
+ }
+ }
+ test = leaked.length === 0
+ check(`errors raised inside the lock release it${test ? '' : ` (${leaked.join('; ')})`}`, test)
+ passes += +test
+ failures += +!test
+
+ // a getter that calls back into the package mid-call must be refused, and the
+ // outer call must still complete
+ let inner = null
+ result = attempt(() => verify_blocks(pub, [{ hash, get signature () { inner = attempt(() => verify(sig, hash, pub)); return sig } }]))
+ test = typeof inner === 'string' && inner.includes('Failed to acquire mutex') && Array.isArray(result) && result[0] === true
+ check(`re-entrant call from a block getter is refused and the outer call completes${test ? '' : ` (inner ${inner}, outer ${result})`}`, test)
+ passes += +test
+ failures += +!test
+}
+
+// Hexadecimal input is decoded arithmetically, not by table lookup, so check
+// the arithmetic against every byte value in either case, and every invalid
+// character at every position, including code units above 0xff whose low byte
+// is a valid digit or letter.
+{
+ const { privateKey, privateKeyBytes, publicKeyBytes } = NANO_ORG_VECTOR
+ const message = Uint8Array.from({ length: 256 }, (_, i) => i)
+ const lower = [...message].map(b => b.toString(16).padStart(2, '0')).join('')
+ const expected = sign(message, privateKeyBytes, publicKeyBytes)
+ /** @type {Record<string, string>} */
+ const cases = { lower, upper: lower.toUpperCase(), mixed: [...lower].map((c, i) => i & 1 ? c.toUpperCase() : c).join('') }
+ const wrong = Object.entries(cases).filter(([, hex]) => attempt(() => sign(hex, privateKeyBytes, publicKeyBytes)) !== expected).map(([name]) => name)
+ test = wrong.length === 0
+ check(`hex input decodes every byte value in lower, upper and mixed case${test ? '' : ` (wrong: ${wrong.join(', ')})`}`, test)
+ passes += +test
+ failures += +!test
+
+ const invalid = ['/', ':', '@', 'G', '`', 'g', ' ', '\0', 'İ', 'Ł', 'š', 'Ȱ', '0', '٠', '\ud83d']
+ /** @type {{ position: number, code: string, result: unknown }[]} */
+ const accepted = []
+ for (let i = 0; i < privateKey.length; i++) {
+ for (const c of invalid) {
+ const r = attempt(() => derive(privateKey.slice(0, i) + c + privateKey.slice(i + 1)))
+ if (r !== 'threw Invalid hexadecimal character') {
+ accepted.push({ position: i, code: `0x${c.charCodeAt(0).toString(16)}`, result: r })
+ }
+ }
+ }
+ test = accepted.length === 0
+ check(`invalid hex character rejected at every position of a private key${test ? '' : ` (${accepted.length} not rejected, first ${JSON.stringify(accepted.slice(0, 4))})`}`, test)
+ passes += +test
+ failures += +!test
+}
+
// Check output buffer offset handling
try {
outbuf = new Uint8Array(33)
const truth = derive(NANO_ORG_VECTOR.privateKeyBytes)
const patchedMessage = new Uint8Array(65).map((_, i) => (i * 37 + 11) & 255)
const truthSignature = sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes)
-const patchedBlocks = [{ hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes }]
+// one valid and one forged block: a patch that answers `true` for every result
+// passes a valid-only batch, so the forged block is what exposes it
+const patchedForgery = NANO_ORG_VECTOR.signatureBytes.slice()
+patchedForgery[40] ^= 1
+const patchedBlocks = [
+ { hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes },
+ { hash: NANO_ORG_VECTOR.blockHashBytes, signature: patchedForgery },
+]
const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype)
/** @type {[string, (() => () => void)][]} */
const patches = [
//@ts-expect-error
globalThis.Uint32Array = () => { throw new Error('patched') }
return () => { globalThis.Uint32Array = real }
+ }],
+ // An index accessor on Array.prototype intercepts every [[Set]] on an index
+ // an array does not own yet: assignment, push and fill alike. Results must be
+ // defined as own properties, or a forged block reads as verified.
+ ['Array.prototype index accessors', () => {
+ for (let i = 0; i < constants.MAX_VERIFY_BLOCKS; i++) {
+ Object.defineProperty(Array.prototype, i, { get () { return true }, set () { }, configurable: true })
+ }
+ return () => {
+ for (let i = 0; i < constants.MAX_VERIFY_BLOCKS; i++) {
+ delete Array.prototype[i]
+ }
+ }
+ }],
+ ['Array.prototype.push', () => {
+ const real = Array.prototype.push
+ Array.prototype.push = function () { return 0 }
+ return () => { Array.prototype.push = real }
+ }],
+ ['Array.prototype.fill', () => {
+ const real = Array.prototype.fill
+ //@ts-expect-error
+ Array.prototype.fill = function () { return this }
+ return () => { Array.prototype.fill = real }
+ }],
+ // descriptor objects and array-likes inherit from Object.prototype unless
+ // they are built without one, as the second definition here would without
+ // its own null prototype
+ ['Object.prototype get and set', () => {
+ Object.defineProperty(Object.prototype, 'get', { __proto__: null, value () { return true }, configurable: true, writable: true })
+ Object.defineProperty(Object.prototype, 'set', { __proto__: null, value () { }, configurable: true, writable: true })
+ return () => {
+ //@ts-expect-error
+ delete Object.prototype.get
+ //@ts-expect-error
+ delete Object.prototype.set
+ }
+ }],
+ ['Object.prototype[Symbol.iterator]', () => {
+ Object.defineProperty(Object.prototype, Symbol.iterator, { * value () { yield true; yield true }, configurable: true, writable: true })
+ //@ts-expect-error
+ return () => { delete Object.prototype[Symbol.iterator] }
}]
]
/** @type {[string, () => boolean][]} */
['derive', () => derive(NANO_ORG_VECTOR.privateKeyBytes) === truth],
['sign', () => sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) === truthSignature],
['verify', () => verify(truthSignature, patchedMessage, NANO_ORG_VECTOR.publicKeyBytes) === true],
- ['verify_blocks', () => verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, patchedBlocks)[0] === true]
+ ['verify_blocks', () => {
+ const r = verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, patchedBlocks)
+ return r.length === 2 && Object.keys(r).length === 2 && r[0] === true && r[1] === false
+ }]
]
for (const [name, apply] of patches) {
for (const [primitive, run] of patchedPrimitives) {