# Internal security review: Pige Guard contracts, protocol v2 Date: 2026-12-04. Scope: `contracts/src/` (`PQCGuardModule.sol`, `MLDSA65Verifier.sol`, `MLDSAProofVerifier.sol`, `AttestationPQCVerifier.sol`), `contracts/script/Deploy.s.sol`, and the matching signing code in `crates/pqc-engine`. > This is an internal review done with an AI assistant. Every finding below was reproduced with a test against a > real Safe v1.4.1, and every fix is covered by a regression test. It is **not** a substitute for an independent > audit by a professional firm. Get one before protecting significant funds, especially for `MLDSA65Verifier`, > which is hand-written assembly. ## Summary | ID | Severity | Finding (v1) | Status in v2 | |---|---|---|---| | C-1 | Critical | Safe refund parameters were not covered: an exempt or pre-authorized Safe transaction with `gasPrice`/`gasToken`/`refundReceiver` could pay all tokens and ETH to an attacker holding only the ECDSA keys | Fixed | | H-1 | High | Rotate and cancel proofs shared the digest format with `preAuthorize`, so a relayed proof could be front-run and burned through the other path | Fixed | | H-2 | High | Safe modules and EIP-1271 signatures (fallback handler) bypass transaction guards entirely | Fixed (mitigated by design) | | H-3 | High | `AttestationPQCVerifier` is not post-quantum, and its owner could add attesters or lower the threshold and forge proofs | Fixed (owner removed) and documented | | M-1 | Medium | Direct-path proofs could be consumed through `preAuthorize` (griefing) | Fixed | | M-2 | Medium | Safe pre-authorizations did not bind `operation` (CALL vs DELEGATECALL) | Fixed | | M-3 | Medium | Pre-authorizations survived key rotation and reset; there was no way to revoke them | Fixed | | L-1 | Low | Duplicate pre-authorizations of the same transaction collapsed into one slot | Fixed | | L-2 | Low | `safeTxGas != 0` let a failing inner call succeed at the Safe level and burn the pre-authorization | Fixed (via C-1) | | L-3 | Low | Verifiers could revert or return malformed data instead of `false` | Fixed | | L-4 | Low | Registration and `setGuard` ordering could let a front-runner register first | Documented: register in the same Safe transaction | | L-5 | Low | `rotatePQCKey` silently dropped a pending reset without an event | Fixed | | I-1 | Info | A 3-day reset delay is short if an L2 sequencer is down | Raised to 7 days | | I-2 | Info | Reset requests can be spammed by a holder of the ECDSA keys | Mitigated: 7-day cooldown after each veto | | I-3 | Info | Deploy script made the deployer the attestation owner | Fixed: no owner | | I-4 | Info | CREATE2 address equality assumed the canonical factory exists | Fixed: the script checks | | I-5 | Info | ERC-4337 Safe module setups | Not supported in Safe mode (modules are refused) | | I-6 | Info | EOAs and EIP-7702 delegated EOAs | Out of scope: the ECDSA key keeps full control | ## Fixes in detail **Typed actions (H-1, M-1).** EIP-712 domain version is now `"2"`. Each action has its own struct: `PQCCall`, `PQCSafeTx` (includes `operation`), `PQCRotateKey`, `PQCCancelReset` and `PQCRevoke`. `PQCCancelReset` names the exact pending key, verifier and `executeAfter`. A signature for one action cannot verify as any other. **Account modes (M-1).** An account is registered once as Direct (`registerPQCKey`, uses `authorize`) or Safe (`registerSafe`, uses `preAuthorize` + guard hooks). Each path checks the mode. **Refund parameters (C-1, L-2).** `checkTransaction` first requires `safeTxGas`, `baseGas`, `gasPrice`, `gasToken` and `refundReceiver` to be zero, before any exemption is considered. With `safeTxGas == 0` and `gasPrice == 0`, Safe reverts the whole transaction if the inner call fails (GS013), so a pre-authorization is only consumed by a successful execution. **Modules and fallback handler (H-2).** `registerSafe` and `checkAfterExecution` require that the Safe has no modules (`getModulesPaginated(SENTINEL, 1)` is empty) and no fallback handler (slot read with `getStorageAt`). Any transaction that adds either, by any route including batches, reverts. Without a fallback handler a Safe has no `isValidSignature`, so there is no EIP-1271 bypass either. The check fails closed if the Safe cannot answer. **Epochs and revocation (M-3, L-1).** Each account has an epoch. It is bumped on rotation, completed reset and `revokePreAuthorizations`. A pre-authorization stores `{deadline, epoch}` and is valid only for the current epoch. An active duplicate is rejected with `AlreadyPreAuthorized`. On-chain deadlines are capped at 7 days. **Verifier calls (L-3).** The guard and `MLDSAProofVerifier` call verifiers with a low-level `staticcall` and accept only exactly 32 bytes of return data equal to `true`. A revert, out-of-gas, empty return (precompile style) or oversized return counts as an invalid proof. **Attestation verifier (H-3, I-3).** The attester set and threshold are immutable; there is no owner. The contract documents that it is not post-quantum. The recommended verifier is now `MLDSAProofVerifier` with `MLDSA65Verifier`, which checks ML-DSA-65 fully on-chain. **Recovery (I-1, I-2, L-5).** `KEY_RESET_DELAY` is 7 days. A vetoed account cannot request a new reset for 7 days. `rotatePQCKey` emits `KeyResetCancelled` when it drops a pending reset. **Deployment (I-4).** `Deploy.s.sol` deploys the guard, `MLDSA65Verifier` and `MLDSAProofVerifier` through the canonical CREATE2 factory, and refuses to run where the factory is missing. ## The ML-DSA-65 verifier `MLDSA65Verifier` implements FIPS 204 verification in Yul: - SHAKE128/256 over an unrolled Keccak-f[1600]; - ExpandA (RejNTTPoly); - SampleInBall; - NTT and inverse NTT; - hint decoding with all canonical-encoding checks; - the z-norm check; - UseHint and w1Encode. Evidence of correctness: - **Two independent implementations:** signatures from Node.js/OpenSSL (`gen-node.mjs`) and from the Rust engine (`fips204` crate) verify, with messages of 0, 32 and 300 bytes. - **Rejection tests:** - wrong message, context and public key; - flips in `rho` and `t1`; - each signature region; - malformed hints (count above omega, decreasing counts, non-zero padding); - z out of range; - bad lengths; - a fuzz test that flips any single bit of the signature. - **SHAKE output** matches Node's reference for several input lengths around the rate boundaries. - **The cached path** (per-key data contracts for A, tr and NTT(t1)) is tested with valid and invalid signatures. Gas (Foundry): | Path | Gas | |---|---| | Verify, no cache | 17.4M | | `precompute`, once per key | 20.2M | | Verify, cached | 4.06M | The cached figure was 6.68M before this review. It came down after: - a radix-4 NTT with lazy reduction; - caching NTT(t1); - reading A straight from the cache. Risks that remain: - **No formal verification yet.** The verifier is hand-written assembly and has not been formally verified or externally audited. - **Memory layout.** It assumes a fixed memory region from 0xec0. It reverts if the free-memory pointer is already beyond that, so it fails closed. - **Cache contracts are public data.** Anyone can create them for any public key. That is harmless: the cache is keyed by `keccak256(publicKey)`, and its contents are only the expanded public key. ## Static analysis `forge lint` warnings left after review, all accepted: - **reentrancy-events:** the only external calls are `STATICCALL`s to verifiers or view calls on the Safe. They cannot change state. - **unsafe-typecast:** - `uint64(deadline)` comes after the 7-day cap; - `uint64(block.timestamp + 7 days)` and `uint8(op)` come after `op <= 1`. - **divide-before-multiply:** NTT strides divide powers of two exactly. - **uninitialized-local:** Yul locals intentionally start at zero. - **block-timestamp:** deadlines and timelocks are measured in hours and days, far above validator drift. - **require-revert-in-loop:** constructor validation of the attester list. Compilation uses the legacy pipeline (`via_ir = false`). The hand-written Yul is about 3.4x more expensive under via-IR. The guard reads the 11-argument `checkTransaction` from calldata through `fallback` for the same reason, with explicit bounds checks. ## Tests | Suite | Tests | What it covers | |---|---|---| | `contracts/test/PQCGuardModule.t.sol` | 30 | Direct path; real Safe 1.4.1 path; one regression test per finding; fuzzing of random Safe calls; cross-language digest vectors | | `contracts/test/MLDSA65Verifier.t.sol` | 12 | ML-DSA vectors, rejection cases, gas, cached path | | `contracts/test/Verifiers.t.sol` | 7 | Attestation verifier (fixed set, malleability, threshold); proof adapter (bad backends) | | `crates/pqc-engine` | 52 unit + e2e | Digests for all five actions, pinned to the same vectors as Solidity; Safe operation selection; cancel proofs built from the on-chain pending reset | The Anvil end-to-end test verifies ML-DSA on-chain through the whole lifecycle, including a vetoed hostile reset. ## Account scope: what is and is not protected Post-quantum protection is enforced by the guard contract, so it covers only accounts whose transactions go through it: | Account | On-chain ML-DSA-65 protection | |---|---| | Safe registered in Safe mode, guard set to `PQCGuardModule`, no modules, no fallback handler | Yes. Every Safe transaction needs a pre-authorization, including `setGuard` to remove the guard. `checkAfterExecution` reverts any transaction that adds a module or fallback handler. | | Smart account registered in Direct mode | Only if the account's own code calls `guard.authorize()` before every execution. | | EOA, or EOA delegated with EIP-7702 | No. The ECDSA key keeps full control (I-6). The desktop firewall still checks what is signed. | | Safe with modules or a fallback handler | No. `registerSafe` refuses it (H-2), because modules and EIP-1271 bypass transaction guards. | Exemptions in Safe mode: `registerSafe`, `requestKeyReset` and `finalizeKeyReset` need no ML-DSA proof, so owners can recover a lost key. A reset waits 7 days and the current key can veto it with `cancelKeyReset`. The account checker on pigeguard.com (section "Is your account protected?") reads these conditions for any address: its code (EOA, EIP-7702), registration and mode, verifier, pending reset, the Safe guard slot, modules and fallback handler. ## Running the released build The released Windows app was run and tested through its local daemon with `scripts/daemon-selftest.mjs`. The WebAssembly build of the engine that pigeguard.com runs was tested with `scripts/engine-selftest.mjs`, including a signature verified by the deployed verifier on Robinhood Chain. Logs: https://pigeguard.com/proof/ ## Out of scope and known limits - **Wallet-level compromise.** If the device running the desktop app is compromised while the vault is unlocked, an attacker can request signatures. The firewall and the approval prompt are the defence. - **Safe mode excludes some setups.** No modules or fallback handler means no Safe{Wallet} 4337 module and no EIP-1271 contract signatures. - **Safe DELEGATECALL** is accepted by the contract when the PQC key signed `operation = 1`. The engine refuses to sign it until MultiSend decoding exists. - **Mainnet cost.** On Ethereum mainnet, on-chain ML-DSA costs about 4M gas per action.