Executive Summary
When designing novel cryptographic primitives, mathematical elegance on paper frequently collides with subtle implementation realities. Following our initial release announcement of AURA (@epoch32/aura), we conducted an exhaustive, multi-pass adversarial cryptanalysis session paired with Claude Sonnet to audit the algorithm's end-to-end security proofs, memory DAG mechanics, and trapdoor constructions.
Over two intensive audit rounds, this collaborative review surfaced 15 distinct security findings ranging from mathematical bypasses to subtle stateful concurrency hazards:
- 3 Critical Vulnerabilities: Including a flawed outer anchor construction that rendered the trapdoor key unnecessary, and an insidious regression during mitigation that caused masked-mode verification to accept arbitrary candidate passwords.
- 5 High-Severity Flaws: Hash chain entropy decay in block expansion, silent domain truncation, shared address buffer data races, and an entropy-collapse vulnerability in KMS integration documentation.
- 5 Medium-Severity Defects: Canonical length-prefix omission in HMAC inputs, PHC parameter downgrade attacks via duplicate keys, missing key entropy validation, and in-place state mutation corruption.
- 2 Low/Validation Hazards: Constant-time comparison short-circuit leaks and unvalidated PHC specification version strings.
Every vulnerability identified has been mitigated, verified with targeted negative test vectors, and patched in @epoch32/aura.
More importantly, this audit forced us to confront a profound theoretical realization: the fundamental tension between O(1) verification shortcuts and offline brute-force asymmetry.
Here is the complete technical post-mortem.
The Core Architectural Breakdown
AURA layers three distinct subsystems:
- Memory-Hard Directed Acyclic Graph (DAG): Argon2id-style memory hardness operating across contiguous ArrayBuffer lanes.
- 2D ARX Word Permutation: Quarter-round bit-mixing inspired by ChaCha20 to ensure non-linear diffusion across all 1,024 bytes of each memory block.
- Asymmetric Trapdoor Construction: A keyed envelope mechanism leveraging HMAC-SHA256 and HKDF to decouple legitimate verification from offline attacker complexity.
The cryptanalysis targeted each subsystem and the composition boundaries between them.
Round 1: Breaking the Initial Assumptions
Critical Findings
C1 - The Trapdoor Anchor Was Bypassable Without Key K
The Vulnerability: The original public anchor was computed as:
Anchor = SHA-256(dagOutput || T || salt)
where T = HMAC-SHA256(K, password || salt)Both dagOutput and Anchor were stored directly in the sealed envelope payload. Critically, the outermost wrapper was an unkeyed SHA-256 hash rather than an HMAC. Because the verifier simply tested hash equivalence against Anchor, the secret key K was not positioned at the root of authentication.
An adversary who extracted dagOutput and Anchor from a compromised database could treat T as an unkeyed target: candidate passwords could be hashed into candidate T' tokens if K leaked, or T could be tested against the outer hash without ever evaluating the full memory matrix. The intermediate token T provided zero formal cryptographic binding over direct evaluation.
The Resolution: We eliminated computeTrapdoorToken entirely. The anchor was re-engineered so that K serves directly as the HMAC key over a length-prefixed tuple:
Anchor = HMAC-SHA256(K, LengthPrefix(dagOutput, salt))Without possession of K, generating or validating this anchor is computationally intractable.
C2 - Standard (Unmasked) Mode Claimed Asymmetry It Did Not Possess
The Vulnerability: In standard unmasked mode, the raw dagOutput was stored directly in plaintext within the envelope. While legitimate users verified via the trapdoor, an offline attacker dumping the hash did not need to touch the anchor: they could simply compute candidate DAG outputs MHF(P', salt) and compare them directly against dagOutput. The threat model was strictly symmetric-identical to standard Argon2id.
The Resolution: We revised the specification and API documentation to make this explicit: true asymmetric offline-resistance is guaranteed exclusively when masked: true is enabled, which blinds the stored output under a one-time HKDF keystream.
High-Severity Findings
H1 - Block Expansion Was an Entropy-Decaying Hash Chain, Not a XOF
The Vulnerability: To expand the 64-byte initial seed H0 into a 1,024-byte base block, the generator chained hashes sequentially:
Chunk[0] = SHA-512(H0 || Lane || BlockIndex)
Chunk[1] = SHA-512(Chunk[0])
Chunk[2] = SHA-512(Chunk[1])After Chunk[0], the lane and block position headers were entirely discarded. If two independent blocks shared identical state at Chunk[0], their remaining 15 chunks (960 bytes) were mathematically identical. This failed the requirement of an Extendable Output Function (XOF) and drastically reduced cross-lane initialization entropy.
The Resolution: Every chunk now binds the full position context independently:
Chunk[i] = SHA-512(H0 || Lane || BlockIndex || uint32LE(i))H2 - outputLength Truncated to 8 Bits in Seed Extraction
The Vulnerability: The 16-byte domain separation header used DataView.setUint8 to encode outputLength. Requesting outputLength = 256 resulted in an integer overflow down to 0, causing outputLength = 256 and outputLength = 0 to yield identical H0 root seeds and destroying domain separation.
// Demonstration of 8-bit truncation in parameter headers
function encodeHeaderV1(
memoryKb: number,
timeCost: number,
outputLength: number,
): Uint8Array {
const buf = new ArrayBuffer(16);
const view = new DataView(buf);
view.setUint32(0, memoryKb, true);
view.setUint32(4, timeCost, true);
// Flaw: setUint8 truncates outputLength.
// 256 mod 256 = 0.
view.setUint8(8, outputLength);
return new Uint8Array(buf);
}
function encodeHeaderV2(
memoryKb: number,
timeCost: number,
outputLength: number,
): Uint8Array {
const buf = new ArrayBuffer(20);
const view = new DataView(buf);
view.setUint32(0, memoryKb, true);
view.setUint32(4, timeCost, true);
// Fix: setUint32 preserves the full 32-bit output length.
view.setUint32(16, outputLength, true);
return new Uint8Array(buf);
}
const headerLen0 = encodeHeaderV1(4096, 2, 0);
const headerLen256 = encodeHeaderV1(4096, 2, 256);
// V1 produces identical headers for outputLength=0 and outputLength=256.
console.log(
Buffer.from(headerLen0).equals(Buffer.from(headerLen256)),
); // true (Domain collision)
const safeHeader0 = encodeHeaderV2(4096, 2, 0);
const safeHeader256 = encodeHeaderV2(4096, 2, 256);
// V2 maintains domain separation.
console.log(
Buffer.from(safeHeader0).equals(Buffer.from(safeHeader256)),
); // false (Distinct domains)The Resolution: The domain header was expanded to 20 bytes, encoding outputLength explicitly as a 32-bit unsigned integer via setUint32 at byte offset 16.
H3 - Shared addressBuffer State Created Latent Race Conditions
The Vulnerability: In computeReferenceIndex, a single pre-allocated Uint32Array instance was retained as a class-level property. While JavaScript in a single thread executes sequentially, parallel worker isolates or asynchronous lane workers would silently overwrite each other's pseudo-random addresses mid-pass, corrupting the deterministic DAG topology and breaking Time-Memory Trade-Off (TMTO) defenses.
The Resolution: Removed class-level state. Data-independent addressing now scopes array allocation cleanly within function bounds.
Medium & Low Findings (Round 1)
- M1 (Canonical Encoding Violation): HMAC payloads previously concatenated
password || saltwithout delimiters. An input ofpwd="abc", salt="defg"generated the exact same digest aspwd="abcd", salt="efg". We implemented strict length-prefixing (encodeLengthPrefixed) prepending 4-byte LE lengths to every element.
// Demonstration of 8-bit truncation in parameter headers
function encodeHeaderV1(
memoryKb: number,
timeCost: number,
outputLength: number,
): Uint8Array {
const buf = new ArrayBuffer(16);
const view = new DataView(buf);
view.setUint32(0, memoryKb, true);
view.setUint32(4, timeCost, true);
// Flaw: setUint8 truncates outputLength.
// 256 mod 256 = 0.
view.setUint8(8, outputLength);
return new Uint8Array(buf);
}
function encodeHeaderV2(
memoryKb: number,
timeCost: number,
outputLength: number,
): Uint8Array {
const buf = new ArrayBuffer(20);
const view = new DataView(buf);
view.setUint32(0, memoryKb, true);
view.setUint32(4, timeCost, true);
// Fix: setUint32 preserves the full 32-bit output length.
view.setUint32(16, outputLength, true);
return new Uint8Array(buf);
}
const headerLen0 = encodeHeaderV1(4096, 2, 0);
const headerLen256 = encodeHeaderV1(4096, 2, 256);
// V1 produces identical headers for outputLength=0 and outputLength=256.
console.log(
Buffer.from(headerLen0).equals(Buffer.from(headerLen256)),
); // true (Domain collision)
const safeHeader0 = encodeHeaderV2(4096, 2, 0);
const safeHeader256 = encodeHeaderV2(4096, 2, 256);
// V2 maintains domain separation.
console.log(
Buffer.from(safeHeader0).equals(Buffer.from(safeHeader256)),
); // false (Distinct domains)- M2 (PHC Parameter Downgrade Attack): The Modular Crypt Format / PHC parser iterated key-value pairs into a
Mapusing last-write-wins semantics. An adversary could inject duplicate keys into a serialized hash (e.g.,m=65536,...,m=64), causing the parser to silently downgrade memory cost by a factor of 1,024x. The parser now enforces duplicate key rejection. - L1 (Timing Oracle in Byte Comparison):
constantTimeEqualimmediately returnedfalseifa.length !== b.length, leaking length disparity through execution timing. The routine was refactored to always iterate through the maximum length with zero-padding and folded XOR accumulators.
Round 2: The Deep Trapdoor Regression & The O(1) Paradox
With Round 1 mitigations in place, we initiated a second adversarial sweep with Claude Sonnet to verify the fixes. It was during this round that the most critical flaw of the audit was uncovered-introduced directly by our attempt to preserve an O(1) verification path.
Critical Regression: C3 - Masked Verification Accepted Any Password
During the Round 1 fix for C1, we attempted to preserve the O(1) fast-path in masked mode by evaluating the anchor directly against the stored ciphertext:
// The Fatal Shortcut (Introduced in Round 1 Fix):
return TrapdoorEngine.verifyWithTrapdoor(
rawDagStored,
salt,
publicAnchor,
trapdoorKey
);Notice the fatal flaw:
rawDagStoredis the blinded ciphertext:D_stored = D ^ HKDF(K, S).- The anchor was defined as
HMAC(K, D_plaintext || S). - Because evaluating the ciphertext against the anchor caused legitimate verifications to fail, a secondary logic patch attempted to normalize the check against the stored envelope itself.
The catastrophe: The verification check became entirely divorced from the candidate password's actual memory DAG output. Because the check merely verified whether the hardware key K matched the stored ciphertext envelope, any string submitted as the candidate password returned true. A completely empty or incorrect password passed verification instantaneously.
interface StoredEnvelope {
salt: Uint8Array;
rawDagStored: Uint8Array; // dagPlaintext ^ keystream
anchor: Uint8Array; // HMAC(K, LengthPrefix(dagPlaintext, salt))
}
// Broken logic (C3 regression):
// The stored ciphertext is checked against the anchor,
// while the candidate password is never evaluated.
async function verifyBroken(
candidatePassword: string,
envelope: StoredEnvelope,
keyK: CryptoKey,
): Promise<boolean> {
// candidatePassword is never derived into a DAG.
// The check only verifies the stored record against K.
const recomputedAnchor = await computeHmac(
keyK,
envelope.rawDagStored,
envelope.salt,
);
return constantTimeEqual(
recomputedAnchor,
envelope.anchor,
);
}
// Correct logic:
// The candidate password must be evaluated through the
// memory-hard function before authentication can succeed.
async function verifyCorrect(
candidatePassword: string,
envelope: StoredEnvelope,
keyK: CryptoKey,
): Promise<boolean> {
// 1. Evaluate the candidate through the memory-hard function.
const candidateDag = await computeMemoryHardDag(
candidatePassword,
envelope.salt,
);
// 2. Authenticate the resulting candidate DAG output.
const expectedAnchor = await computeHmac(
keyK,
candidateDag,
envelope.salt,
);
return constantTimeEqual(
expectedAnchor,
envelope.anchor,
);
}The Deeper Insight: The O(1) Fast-Path Paradox
This regression illuminated an immutable cryptographic law regarding password verifiers:
You cannot simultaneously achieve an O(1) password verification shortcut and correct negative password rejection using a single cryptographic anchor.
Consider the mathematical fork:
- If the Anchor commits to the plaintext DAG output (
D): - The verifier must re-evaluate the memory-hard function over the candidate password
P'to obtainD'. If the verifier does not run the MHF, they cannot know whetherP' == P. Verification is inherently Ω(M × T) compute-bound. - If the Anchor commits only to the stored ciphertext (
D_stored): - The verifier can check the integrity of the record in O(1) using
K, but this operation does not involve the password candidateP'at all. Any arbitrary candidate will be accepted.
A genuine mathematical O(1) shortcut requires an algebraic trapdoor function-such as the generalized birthday problem or modular inversion pioneered by Biryukov and Khovratovich-where a prover can present a mathematical certificate that verifies in O(1) without re-evaluating the graph.
An HMAC/HKDF envelope is a peppering and blinding scheme, not an algebraic trapdoor. While it provides mathematically absolute offline brute-force protection (an attacker without K faces pure uniform random noise), the verifying server must run the MHF to authenticate the password.
We eliminated the false O(1) bypass: all verification paths now deterministically re-evaluate the candidate MHF, guaranteeing 100% rejection of invalid credentials while preserving complete offline attack immunity under masked mode.
High & Medium Findings (Round 2)
H4 - KMS Integration Guide Collapsed Entropy to ~6.5 Bits/Byte
Our integration documentation for Cloudflare Workers and AWS KMS suggested importing keys via:
// DANGEROUS: Do NOT use
new TextEncoder().encode(env.KMS_SECRET)TextEncoder outputs printable UTF-8/ASCII bytes. Because standard base64 or hex characters represent only a fraction of the 0–255 byte spectrum, a 32-character string parsed this way possesses at most ~210 bits of entropy-and far less if formatted as a UUID (~122 bits) or passphrase. WebCrypto imports arbitrary byte buffers without length validation. We revised the guides to mandate strict base64UrlToBytes decoding and added explicit entropy checks.
// Demonstrating the difference between text encoding
// and decoding an encoded binary key.
// This is a Base64 representation of binary key material.
const base64Key =
"q3s7v9yBCEhJQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo=";
// Flawed pattern:
// TextEncoder encodes the Base64 characters themselves.
//
// The resulting bytes represent the textual encoding,
// not the original binary key material.
const flawedKeyBytes =
new TextEncoder().encode(base64Key);
// Correct pattern:
// Decode the Base64 representation back into
// the underlying binary bytes.
//
// Each decoded byte can span the full 0x00-0xFF range.
function base64ToBytes(
base64: string,
): Uint8Array {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
const correctKeyBytes =
base64ToBytes(base64Key);
console.log(
flawedKeyBytes.length,
); // 48 bytes of ASCII text
console.log(
correctKeyBytes.length,
); // 32 bytes of binary key material
console.log(
Buffer.from(flawedKeyBytes).equals(
Buffer.from(correctKeyBytes),
),
); // falseH5 - Self-Referential Block Hazard on Pass > 0
In mixBlocks, when traversing passes t > 0 at the final block index i = N - 1, quadratic index biasing could occasionally select the current block itself (j = i). When currentBlock === refBlock, mixBlocks read and wrote to the same contiguous Uint32Array simultaneously, destroying state before the step-3 feed-forward operation. We instituted an explicit collision guard that redirects self-referential passes:
if (refLane === lane && refIndex === i) {
refIndex = (i - 1 + blocksPerLane) % blocksPerLane;
}M3, M4, M5 - Safety Invariants & Idempotency
- M3 (Key Length Enforcement):
computePublicAnchorandderiveMaskKeynow throw an explicitRangeErrorifK < 16bytes, preventing accidental 8-bit key initialization. - M4 (Execution Idempotency):
MemoryDag.execute()mutates internal buffers in-place. A second invocation on the same instance would execute against stale memory. We added an internal executed lifecycle latch that throws on reuse. - M5 (Digest Clamping): Instantiating AURA with
outputLength > 64silently clamped output bytes due to SHA-512 limits. The constructor now strictly asserts1 <= outputLength <= 64.
The Audit Scorecard
Security Metric | Baseline | Post-Round 1 | Post-Round2 |
|---|---|---|---|
Automated Test Suite | 12/12 | 12/12 | 19/19 |
Critical Vulnerabilities | 2 | 0 | 0 |
High-Severity Vulnerabilities | 3 | 0 | 0 |
Medium Severity Defects | 3 | 1 | 0 |
Regressions Active | 0 | 1(C3) | 0 |
Outer Anchor Construction | SHA-256 | HMAC-SHA256 | HMA-SHA256 |
Block XOF Expansion | Hash Chain | Domain-Tag LE | Domain-Tag LE |
Minimum Key Length Guard | None | None | >= 16 Bytes |
Self-Referential DAG Guard | Absent | Absent | Enforced |
DAG In-Place Idempotency Latch | Absent | Absent | Enforced |
Lessons for Systems Cryptography
- AI-Assisted Adversarial Review Works: Pairing with Claude Sonnet allowed us to rapidly explore boundary edge cases, trace multi-file data flows, and probe mathematical assumptions far faster than traditional manual audits alone.
- Never Mask a Peppering Scheme as an Algebraic Shortcut: Terminology matters. Using the word "trapdoor" led to architectural expectations that violated password verification fundamentals. Precision in cryptographic naming prevents lethal security shortcuts.
- Example Code is Attack Surface: A flaw in your documentation (
TextEncoder.encode) will become a flaw in your user's production infrastructure. Treat tutorials with the same verification rigor as your core algorithms.
The complete patched reference implementation, updated formal specifications, and expanded 19-test automated test harness are available now on GitHub:
* Repository: https://github.com/Epoch32/aura
* Package: @epoch32/aura



No comments yet