audit-system 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +351 -0
  3. package/agents/AGENT_REGISTRY.md +150 -0
  4. package/agents/assumption-analyzer.json +7 -0
  5. package/agents/assumption-analyzer.md +37 -0
  6. package/agents/composition-attacker.json +7 -0
  7. package/agents/composition-attacker.md +46 -0
  8. package/agents/economic-attacker.json +7 -0
  9. package/agents/economic-attacker.md +43 -0
  10. package/agents/exploit-writer.json +7 -0
  11. package/agents/exploit-writer.md +48 -0
  12. package/agents/orchestrator.json +16 -0
  13. package/agents/orchestrator.md +46 -0
  14. package/agents/report-writer.json +7 -0
  15. package/agents/report-writer.md +52 -0
  16. package/agents/state-machine-hacker.json +7 -0
  17. package/agents/state-machine-hacker.md +43 -0
  18. package/agents/test-generator.json +7 -0
  19. package/agents/test-generator.md +49 -0
  20. package/cli.js +93 -0
  21. package/config.json +74 -0
  22. package/lib/detect-lang.js +109 -0
  23. package/lib/install.js +229 -0
  24. package/lib/utils.js +41 -0
  25. package/obsidian-vault/README.md +103 -0
  26. package/obsidian-vault/attack-patterns/state-inconsistency.md +90 -0
  27. package/obsidian-vault/exploits/_index.md +109 -0
  28. package/obsidian-vault/exploits/beanstalk-2022.md +334 -0
  29. package/obsidian-vault/exploits/nomad-2022.md +295 -0
  30. package/obsidian-vault/exploits/ronin-2022.md +251 -0
  31. package/obsidian-vault/exploits/wormhole-2022.md +284 -0
  32. package/obsidian-vault/failed-hypotheses/_template.md +77 -0
  33. package/obsidian-vault/hypotheses/_template.md +43 -0
  34. package/obsidian-vault/hypotheses/bridge-protocol-template.md +254 -0
  35. package/obsidian-vault/hypotheses/dex-protocol-template.md +185 -0
  36. package/obsidian-vault/hypotheses/governance-protocol-template.md +263 -0
  37. package/obsidian-vault/hypotheses/lending-protocol-template.md +218 -0
  38. package/obsidian-vault/hypotheses/staking-protocol-template.md +223 -0
  39. package/obsidian-vault/invariant-catalog/defi-invariants.md +307 -0
  40. package/obsidian-vault/invariant-catalog/solana-invariants.md +213 -0
  41. package/obsidian-vault/novel-patterns/pattern-mutation-framework.md +316 -0
  42. package/obsidian-vault/reports/_template.md +92 -0
  43. package/obsidian-vault/research/cross-protocol-analysis/.gitkeep +0 -0
  44. package/obsidian-vault/research/emerging-threats/.gitkeep +0 -0
  45. package/obsidian-vault/research/protocol-specific/.gitkeep +0 -0
  46. package/obsidian-vault/test-strategies/fuzzing.md +75 -0
  47. package/obsidian-vault/vulnerabilities/access-control.md +122 -0
  48. package/obsidian-vault/vulnerabilities/flash-loan-attack.md +66 -0
  49. package/obsidian-vault/vulnerabilities/oracle-manipulation.md +135 -0
  50. package/obsidian-vault/vulnerabilities/reentrancy.md +141 -0
  51. package/obsidian-vault/vulnerabilities/rust-unsafe-deserialization.md +128 -0
  52. package/obsidian-vault/vulnerabilities/solana-account-confusion.md +125 -0
  53. package/obsidian-vault/vulnerabilities/solana-close-account.md +141 -0
  54. package/obsidian-vault/vulnerabilities/solana-cpi-attacks.md +131 -0
  55. package/obsidian-vault/vulnerabilities/solana-signer-authorization.md +119 -0
  56. package/package.json +56 -0
  57. package/skills/audit-connect.md +385 -0
  58. package/skills/auditor.md +280 -0
  59. package/skills/exploit-generator.md +394 -0
  60. package/skills/novel-discovery.md +551 -0
  61. package/skills/test-generator.md +511 -0
@@ -0,0 +1,254 @@
1
+ # Hypothesis Template: Bridge Protocol
2
+
3
+ ## Protocol Context
4
+ - **Type:** Cross-Chain Bridge / Token Wrapper / Message Relay
5
+ - **Key Components:** Lock/mint mechanism, validators/oracles, message passing, replay protection
6
+ - **Critical Invariants:** Wrapped supply = locked amount, message uniqueness, validator consensus
7
+
8
+ ---
9
+
10
+ ## Assumption Mapping
11
+
12
+ ### Developer Assumptions About Validators
13
+ ```
14
+ ASSUMPTION: Validators are honest and independent
15
+ REALITY: Validators can be compromised or collude
16
+ HYPOTHESIS: Threshold signature scheme can be attacked
17
+
18
+ ASSUMPTION: Validator set is secure
19
+ REALITY: Validator addition/removal may have bugs
20
+ HYPOTHESIS: Attacker can add controlled validator
21
+ ```
22
+
23
+ ### Developer Assumptions About Messages
24
+ ```
25
+ ASSUMPTION: Each message is unique and non-replayable
26
+ REALITY: Replay protection may have edge cases
27
+ HYPOTHESIS: Same message can be executed multiple times
28
+
29
+ ASSUMPTION: Message data cannot be tampered
30
+ REALITY: Signature verification may have bugs
31
+ HYPOTHESIS: Modify message content while keeping valid signature
32
+ ```
33
+
34
+ ### Developer Assumptions About Locked Tokens
35
+ ```
36
+ ASSUMPTION: Locked tokens remain secure until redemption
37
+ REALITY: Lock mechanism may be bypassed
38
+ HYPOTHESIS: Direct transfer or reentrancy bypasses lock
39
+
40
+ ASSUMPTION: Wrapped supply always matches locked
41
+ REALITY: Minting may not be properly backed
42
+ HYPOTHESIS: Mint unwrapped tokens without locking
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Attack Vectors Specific to Bridges
48
+
49
+ ### 1. Signature Malleability / Replay Attack
50
+ ```solidity
51
+ HYPOTHESIS ID: H-BRIDGE-001
52
+ ASSUMPTION BROKEN: "Each bridge message can only be executed once"
53
+ VIOLATION METHOD: Replay valid signature on different chain or with modified data
54
+ PRECONDITIONS:
55
+ - Replay protection uses simple nonce or hash
56
+ - Chain ID not included in signature
57
+ - Signature scheme allows malleability (ECDSA s-value)
58
+ ATTACK SEQUENCE:
59
+ 1. Observe valid bridge transaction
60
+ 2. Modify signature (malleability) or reuse with different parameters
61
+ 3. Execute same transfer again
62
+ 4. Or: Execute on wrong chain if Chain ID not checked
63
+ SUCCESS CONDITION: Same deposit redeemed multiple times
64
+ ESTIMATED IMPACT: Infinite minting of wrapped tokens
65
+ NOVELTY: Signature scheme specific vulnerability
66
+ ```
67
+
68
+ ### 2. Validator Threshold Attack
69
+ ```solidity
70
+ HYPOTHESIS ID: H-BRIDGE-002
71
+ ASSUMPTION BROKEN: "Validator threshold prevents malicious consensus"
72
+ REALITY: Attacker can control enough validators
73
+ PRECONDITIONS:
74
+ - Threshold < 100% (e.g., 5/9 validators)
75
+ - Validator set can be influenced
76
+ ATTACK SEQUENCE:
77
+ 1. Gain control of threshold number of validators
78
+ - Sybil attack if validator selection is weak
79
+ - Bribe or compromise existing validators
80
+ - Exploit validator rotation mechanism
81
+ 2. Sign fraudulent withdrawal
82
+ 3. Drain bridge liquidity
83
+ SUCCESS CONDITION: Fraudulent withdrawal approved
84
+ ESTIMATED IMPACT: Full bridge drain
85
+ NOVELTY: Governance/economic attack on validator set
86
+ ```
87
+
88
+ ### 3. Lock/Unlock Reentrancy
89
+ ```solidity
90
+ HYPOTHESIS ID: H-BRIDGE-003
91
+ ASSUMPTION BROKEN: "Lock mechanism is reentrancy-safe"
92
+ REALITY: External calls during lock/unlock can be exploited
93
+ PRECONDITIONS:
94
+ - Lock function makes external call (token callback, event)
95
+ - State updated after external call
96
+ ATTACK SEQUENCE:
97
+ 1. Call bridge lock function
98
+ 2. In callback, call lock function again
99
+ 3. State not updated, same tokens "locked" twice
100
+ 4. Receive double wrapped tokens
101
+ OR:
102
+ 1. Initiate withdrawal
103
+ 2. Reenter during transfer
104
+ 3. Withdraw multiple times before balance updated
105
+ SUCCESS CONDITION: Wrapped tokens > locked tokens
106
+ ESTIMATED IMPACT: Unbacked wrapped tokens, bridge insolvency
107
+ NOVELTY: Bridge-specific reentrancy pattern
108
+ ```
109
+
110
+ ### 4. Chain ID / Domain Separation Bypass
111
+ ```solidity
112
+ HYPOTHESIS ID: H-BRIDGE-004
113
+ ASSUMPTION BROKEN: "Messages are valid only on specific chain"
114
+ REALITY: Chain ID not properly checked in signature
115
+ PRECONDITIONS:
116
+ - Signature does not include chainId
117
+ - Same validator set across chains
118
+ ATTACK SEQUENCE:
119
+ 1. Get valid signature from Chain A
120
+ 2. Replay exact same signature on Chain B
121
+ 3. Validators approve because signature is valid
122
+ 4. Double-spend same deposit on multiple chains
123
+ SUCCESS CONDITION: Same deposit redeemed on multiple chains
124
+ ESTIMATED IMPACT: Multiple wrapped tokens for single deposit
125
+ NOVELTY: Cross-chain replay
126
+ ```
127
+
128
+ ### 5. Price/Value Discrepancy Attack
129
+ ```solidity
130
+ HYPOTHESIS ID: H-BRIDGE-005
131
+ ASSUMPTION BROKEN: "Bridge correctly values assets across chains"
132
+ REALITY: Different chains may have different price oracles
133
+ PRECONDITIONS:
134
+ - Bridge handles multiple assets
135
+ - Value calculation differs across chains
136
+ ATTACK SEQUENCE:
137
+ 1. Deposit overvalued asset on Chain A
138
+ 2. Receive credit based on inflated value
139
+ 3. Withdraw undervalued asset on Chain B
140
+ 4. Profit from discrepancy
141
+ SUCCESS CONDITION: Withdraw value > deposit value
142
+ ESTIMATED IMPACT: Gradual bridge drain through arbitrage
143
+ NOVELTY: Economic exploitation of price oracle differences
144
+ ```
145
+
146
+ ### 6. Message Ordering / Front-Running
147
+ ```solidity
148
+ HYPOTHESIS ID: H-BRIDGE-006
149
+ ASSUMPTION BROKEN: "Message order does not affect security"
150
+ REALITY: Ordering can be exploited for front-running
151
+ PRECONDITIONS:
152
+ - Messages processed in received order
153
+ - No commitment scheme
154
+ ATTACK SEQUENCE:
155
+ 1. Observe large bridge transfer in mempool
156
+ 2. Front-run with own transfer
157
+ 3. Manipulate state (price, liquidity) before victim
158
+ 4. Extract value from price movement
159
+ SUCCESS CONDITION: Profit from front-running
160
+ ESTIMATED IMPACT: Systematic MEV extraction
161
+ NOVELTY: Bridge-specific MEV pattern
162
+ ```
163
+
164
+ ---
165
+
166
+ ## Invariants to Test
167
+
168
+ ```solidity
169
+ // INVARIANT 1: Wrapped supply = locked amount
170
+ assert(wrappedToken.totalSupply() == lockedToken.balanceOf(bridge));
171
+
172
+ // INVARIANT 2: Each message executed exactly once
173
+ assert(!executedMessages[messageHash]);
174
+
175
+ // INVARIANT 3: Validator threshold properly enforced
176
+ assert(validSignatures >= threshold);
177
+
178
+ // INVARIANT 4: Chain ID included in all signatures
179
+ // (Test by attempting replay on different chain)
180
+
181
+ // INVARIANT 5: No reentrancy during lock/unlock
182
+ // (Use reentrancy guard or checks-effects-interactions)
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Foundry Test Skeleton
188
+
189
+ ```solidity
190
+ contract BridgeHypothesisTest is Test {
191
+ IBridge bridge;
192
+ IERC20 lockedToken;
193
+ IERC20 wrappedToken;
194
+ address[] validators;
195
+
196
+ function test_signatureReplay() public {
197
+ // Setup: Create valid bridge signature
198
+ // Attack: Modify signature or replay on different chain
199
+ // Assert: Same message executed twice
200
+ }
201
+
202
+ function test_validatorThresholdAttack() public {
203
+ // Setup: Create malicious validators
204
+ // Attack: Reach threshold with controlled validators
205
+ // Assert: Fraudulent withdrawal approved
206
+ }
207
+
208
+ function test_lockReentrancy() public {
209
+ // Setup: Malicious contract as depositor
210
+ // Attack: Reenter during lock callback
211
+ // Assert: Double tokens minted
212
+ }
213
+
214
+ function test_chainIdBypass() public {
215
+ // Setup: Signature from Chain A
216
+ // Attack: Replay on Chain B (fork test)
217
+ // Assert: Valid execution on wrong chain
218
+ }
219
+
220
+ function test_valueDiscrepancy() public {
221
+ // Setup: Multi-asset bridge with different oracles
222
+ // Attack: Deposit overvalued, withdraw undervalued
223
+ // Assert: Profit from discrepancy
224
+ }
225
+ }
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Related Vulnerabilities
231
+ - [[../vulnerabilities/reentrancy]]
232
+ - [[../vulnerabilities/oracle-manipulation]]
233
+ - [[../vulnerabilities/access-control]]
234
+
235
+ ---
236
+
237
+ ## Real-World Bridge Exploits (Reference)
238
+ | Bridge | Year | Loss | Vector |
239
+ |--------|------|------|--------|
240
+ | Ronin | 2022 | $625M | Validator key compromise (5/9 threshold) |
241
+ | Wormhole | 2022 | $325M | Signature verification bypass |
242
+ | Nomad | 2022 | $190M | Replay attack (merkle root replay) |
243
+ | Harmony | 2022 | $100M | Multi-sig compromise (2/5 threshold) |
244
+ | Qubit | 2022 | $80M | Fake deposit proof |
245
+
246
+ ---
247
+
248
+ ## Validation Checklist
249
+ - [ ] Hypothesis accounts for cross-chain complexity
250
+ - [ ] Considers validator economics
251
+ - [ ] Tests signature verification thoroughly
252
+ - [ ] Checks replay protection on all chains
253
+ - [ ] Verifies wrapped supply matches locked
254
+ - [ ] Considers MEV and front-running vectors
@@ -0,0 +1,185 @@
1
+ # Hypothesis Template: DEX Protocol
2
+
3
+ ## Protocol Context
4
+ - **Type:** DEX / AMM / Order Book
5
+ - **Key Components:** Liquidity pools, price oracle, swap logic, LP tokens
6
+ - **Critical Invariants:** Constant product (x*y=k), price accuracy, LP share correctness
7
+
8
+ ---
9
+
10
+ ## Assumption Mapping
11
+
12
+ ### Developer Assumptions About Price
13
+ ```
14
+ ASSUMPTION: Spot price accurately reflects market price
15
+ REALITY: Spot price can be manipulated with flash loans
16
+ HYPOTHESIS: Attack can manipulate price to extract value from dependent protocols
17
+
18
+ ASSUMPTION: TWAP cannot be manipulated within single block
19
+ REALITY: Multiple swaps in same block can affect TWAP window
20
+ HYPOTHESIS: Gradual manipulation over TWAP period
21
+ ```
22
+
23
+ ### Developer Assumptions About Liquidity
24
+ ```
25
+ ASSUMPTION: LP providers are honest participants
26
+ REALITY: LP can be malicious with majority liquidity
27
+ HYPOTHESIS: Malicious LP can drain fees or manipulate exits
28
+
29
+ ASSUMPTION: Liquidity is always available for swaps
30
+ REALITY: Liquidity can be removed atomically
31
+ HYPOTHESIS: Sandwich attack with liquidity removal
32
+ ```
33
+
34
+ ### Developer Assumptions About LP Tokens
35
+ ```
36
+ ASSUMPTION: LP token supply matches pool reserves
37
+ REALITY: Fee-on-transfer LP tokens break accounting
38
+ HYPOTHESIS: Use malicious LP token with fee-on-transfer
39
+
40
+ ASSUMPTION: LP token transfers are simple
41
+ REALITY: LP token may have callbacks or hooks
42
+ HYPOTHESIS: Reentrancy via LP token callback
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Attack Vectors Specific to DEX
48
+
49
+ ### 1. Flash Loan Price Manipulation
50
+ ```solidity
51
+ HYPOTHESIS ID: H-DEX-001
52
+ ASSUMPTION BROKEN: "Price cannot be manipulated without significant capital"
53
+ VIOLATION METHOD: Flash loan + massive swap + reverse swap
54
+ PRECONDITIONS:
55
+ - Pool has insufficient liquidity relative to flash loan capacity
56
+ - No price sanity checks
57
+ - Dependent protocol reads spot price
58
+ ATTACK SEQUENCE:
59
+ 1. Flash loan 10M USDC
60
+ 2. Swap USDC→ETH, pushing ETH price 10x
61
+ 3. Call vulnerable protocol that reads manipulated price
62
+ 4. Extract over-collateralized loan or liquidate unfairly
63
+ 5. Swap ETH→USDC (reverse)
64
+ 6. Repay flash loan
65
+ SUCCESS CONDITION: Profit > flash loan fee + gas
66
+ ESTIMATED IMPACT: Full protocol insolvency
67
+ NOVELTY: Specific to this pool's liquidity depth
68
+ ```
69
+
70
+ ### 2. Liquidity Removal Attack
71
+ ```solidity
72
+ HYPOTHESIS ID: H-DEX-002
73
+ ASSUMPTION BROKEN: "Liquidity is stable during user operations"
74
+ VIOLATION METHOD: Atomic liquidity add/remove sandwich
75
+ PRECONDITIONS:
76
+ - User transaction visible in mempool
77
+ - No slippage protection or weak checks
78
+ ATTACK SEQUENCE:
79
+ 1. Front-run: Add liquidity
80
+ 2. Victim: Swaps at worse rate due to added liquidity
81
+ 3. Back-run: Remove liquidity + captured fees
82
+ SUCCESS CONDITION: Captured value > gas costs
83
+ ESTIMATED IMPACT: Systematic value extraction from all traders
84
+ NOVELTY: MEV extraction pattern
85
+ ```
86
+
87
+ ### 3. Fee-on-Transfer Token Attack
88
+ ```solidity
89
+ HYPOTHESIS ID: H-DEX-003
90
+ ASSUMPTION BROKEN: "token.transfer(amount) transfers exactly amount"
91
+ VIOLATION METHOD: Use malicious token with 99% fee
92
+ PRECONDITIONS:
93
+ - DEX accepts arbitrary tokens
94
+ - Accounting assumes transferIn == transferOut
95
+ ATTACK SEQUENCE:
96
+ 1. Deposit malicious token with fee
97
+ 2. DEX credits based on expected amount
98
+ 3. Withdraw: DEX sends less due to fee
99
+ 4. DEX absorbs loss or breaks invariant
100
+ SUCCESS CONDITION: DEX becomes insolvent
101
+ ESTIMATED IMPACT: LP loss proportional to fee discrepancy
102
+ NOVELTY: Token behavior assumption
103
+ ```
104
+
105
+ ### 4. Reentrancy via Flash Callback
106
+ ```solidity
107
+ HYPOTHESIS ID: H-DEX-004
108
+ ASSUMPTION BROKEN: "Flash loan callback is the only reentry point"
109
+ VIOLATION METHOD: Reenter swap function during callback
110
+ PRECONDITIONS:
111
+ - Flash loan callback not properly guarded
112
+ - State updated after external call
113
+ ATTACK SEQUENCE:
114
+ 1. Flash loan token A
115
+ 2. Swap A→B (callback triggered)
116
+ 3. In callback, swap B→A before state update
117
+ 4. Extract profit from price discrepancy
118
+ SUCCESS CONDITION: Profit > flash loan fee
119
+ ESTIMATED IMPACT: Pool drained through repeated swaps
120
+ NOVELTY: Cross-function reentrancy
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Invariants to Test
126
+
127
+ ```solidity
128
+ // INVARIANT 1: Pool solvency
129
+ assert(address(pool).balance >= totalLPShares * pricePerShare);
130
+
131
+ // INVARIANT 2: Price bounds
132
+ assert(currentPrice >= minPrice && currentPrice <= maxPrice);
133
+
134
+ // INVARIANT 3: LP token accounting
135
+ assert(totalLPShares == sum(allUserBalances));
136
+
137
+ // INVARIANT 4: Constant product (for AMM)
138
+ assert(reserveA * reserveB >= initialK); // Allow increase from fees
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Foundry Test Skeleton
144
+
145
+ ```solidity
146
+ contract DEXHypothesisTest is Test {
147
+ IDEX dex;
148
+ IMaliciousToken maliciousToken;
149
+ address flashLoanProvider;
150
+
151
+ function test_flashLoanPriceManipulation() public {
152
+ // Setup: Get flash loan, identify target pool
153
+ // Attack: Execute swap sequence
154
+ // Assert: Price was manipulated and profit extracted
155
+ }
156
+
157
+ function test_feeOnTransferDrain() public {
158
+ // Setup: Deposit malicious LP token
159
+ // Attack: Trigger withdrawal
160
+ // Assert: Pool accounting broken
161
+ }
162
+
163
+ function test_liquiditySandwich() public {
164
+ // Setup: Identify pending swap in mempool
165
+ // Attack: Add/remove liquidity around victim tx
166
+ // Assert: Value extracted from victim
167
+ }
168
+ }
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Related Vulnerabilities
174
+ - [[../vulnerabilities/oracle-manipulation]]
175
+ - [[../vulnerabilities/flash-loan-attack]]
176
+ - [[../attack-patterns/state-inconsistency]]
177
+
178
+ ---
179
+
180
+ ## Validation Checklist
181
+ - [ ] Hypothesis is testable with Foundry
182
+ - [ ] Preconditions are achievable
183
+ - [ ] Attack sequence is specific to THIS DEX
184
+ - [ ] Would NOT be found by Slither/Mythril
185
+ - [ ] Economic incentive exists for attacker
@@ -0,0 +1,263 @@
1
+ # Hypothesis Template: Governance Protocol
2
+
3
+ ## Protocol Context
4
+ - **Type:** DAO / Governance / Voting System
5
+ - **Key Components:** Proposal creation, voting mechanisms, timelocks, execution
6
+ - **Critical Invariants:** One token = one vote, quorum requirements, execution delay
7
+
8
+ ---
9
+
10
+ ## Assumption Mapping
11
+
12
+ ### Developer Assumptions About Voting Power
13
+ ```
14
+ ASSUMPTION: Voting power accurately represents stakeholder interest
15
+ REALITY: Voting power can be borrowed or manipulated
16
+ HYPOTHESIS: Flash loan voting allows proposal capture
17
+
18
+ ASSUMPTION: Voters are long-term stakeholders
19
+ REALITY: Governance tokens can be traded or borrowed
20
+ HYPOTHESIS: Short-term actors can capture long-term decisions
21
+ ```
22
+
23
+ ### Developer Assumptions About Proposal Process
24
+ ```
25
+ ASSUMPTION: Proposals are submitted in good faith
26
+ REALITY: Proposals can be malicious or exploitative
27
+ HYPOTHESIS: Malicious proposal can drain treasury
28
+
29
+ ASSUMPTION: Timelock provides adequate review time
30
+ REALITY: Timelock can be bypassed or rushed
31
+ HYPOTHESIS: Emergency mechanisms bypass timelock
32
+ ```
33
+
34
+ ### Developer Assumptions About Execution
35
+ ```
36
+ ASSUMPTION: Proposal execution is atomic and safe
37
+ REALITY: Execution may have reentrancy or ordering issues
38
+ HYPOTHESIS: Execution can be manipulated mid-flight
39
+ ```
40
+
41
+ ---
42
+
43
+ ## Attack Vectors Specific to Governance
44
+
45
+ ### 1. Flash Loan Governance Attack
46
+ ```solidity
47
+ HYPOTHESIS ID: H-GOV-001
48
+ ASSUMPTION BROKEN: "Voters have long-term alignment with protocol"
49
+ VIOLATION METHOD: Borrow voting power, pass malicious proposal, repay
50
+ PRECONDITIONS:
51
+ - Voting power based on token balance at snapshot
52
+ - No minimum lockup or delegation period
53
+ - Proposal threshold achievable with flash loan
54
+ ATTACK SEQUENCE:
55
+ 1. Flash loan massive amount of governance tokens
56
+ 2. Delegate voting power to attacker address
57
+ 3. Create and vote on malicious proposal (e.g., "send treasury to attacker")
58
+ 4. Proposal passes with borrowed voting power
59
+ 5. Execute after timelock (or if no timelock)
60
+ 6. Repay flash loan (if same-block execution possible)
61
+ OR wait for timelock with rented tokens
62
+ SUCCESS CONDITION: Malicious proposal passes and executes
63
+ ESTIMATED IMPACT: Treasury drain, protocol capture
64
+ NOVELTY: Governance-specific flash attack
65
+ ```
66
+
67
+ ### 2. Proposal Front-Running
68
+ ```solidity
69
+ HYPOTHESIS ID: H-GOV-002
70
+ ASSUMPTION BROKEN: "Proposal order does not affect outcomes"
71
+ REALITY: Competing proposals can pre-empt legitimate ones
72
+ PRECONDITIONS:
73
+ - Multiple proposals can coexist
74
+ - First proposal to reach quorum executes
75
+ ATTACK SEQUENCE:
76
+ 1. Monitor mempool for legitimate proposal
77
+ 2. Front-run with competing proposal (similar but malicious)
78
+ 3. Use flash loan or pre-positioned tokens to vote first
79
+ 4. Legitimate proposal becomes irrelevant
80
+ SUCCESS CONDITION: Attacker proposal executes instead of legitimate one
81
+ ESTIMATED IMPACT: Governance capture, user funds at risk
82
+ NOVELTY: Proposal-level MEV
83
+ ```
84
+
85
+ ### 3. Vote Manipulation Through Token Economics
86
+ ```solidity
87
+ HYPOTHESIS ID: H-GOV-003
88
+ ASSUMPTION BROKEN: "Token distribution reflects governance power fairly"
89
+ REALITY: Token concentration allows capture
90
+ PRECONDITIONS:
91
+ - Top holders control majority of votes
92
+ - No quadratic voting or caps
93
+ ATTACK SEQUENCE:
94
+ 1. Accumulate or borrow majority of tokens
95
+ 2. Delegate to single address
96
+ 3. Pass any proposal regardless of community interest
97
+ 4. Or: Hold community hostage for ransom
98
+ SUCCESS CONDITION: Attacker controls all governance outcomes
99
+ ESTIMATED IMPACT: Governance centralization, community disempowerment
100
+ NOVELTY: Economic capture of decentralized governance
101
+ ```
102
+
103
+ ### 4. Timelock Bypass Through Emergency Mechanisms
104
+ ```solidity
105
+ HYPOTHESIS ID: H-GOV-004
106
+ ASSUMPTION BROKEN: "Timelock cannot be bypassed"
107
+ REALITY: Emergency functions may override timelock
108
+ PRECONDITIONS:
109
+ - Emergency pause or guardian exists
110
+ - Guardian has elevated privileges
111
+ ATTACK SEQUENCE:
112
+ 1. Compromise or coerce guardian (economic attack, social engineering)
113
+ 2. Use emergency function to bypass timelock
114
+ 3. Execute malicious action immediately
115
+ 4. Disable governance response
116
+ SUCCESS CONDITION: Action executed without timelock delay
117
+ ESTIMATED IMPACT: Immediate protocol capture
118
+ NOVELTY: Privilege escalation through emergency mechanism
119
+ ```
120
+
121
+ ### 5. Quorum Manipulation
122
+ ```solidity
123
+ HYPOTHESIS ID: H-GOV-005
124
+ ASSUMPTION BROKEN: "Quorum requirement ensures broad participation"
125
+ REALITY: Quorum can be manipulated through token economics
126
+ PRECONDITIONS:
127
+ - Quorum based on outstanding tokens, not active voters
128
+ - Many tokens are inactive or lost
129
+ ATTACK SEQUENCE:
130
+ 1. Identify inactive token holders (lost keys, dead addresses)
131
+ 2. Calculate effective quorum (much lower than nominal)
132
+ 3. Accumulate just enough active tokens to reach effective quorum
133
+ 4. Pass proposals with tiny fraction of total supply
134
+ SUCCESS CONDITION: Proposal passes with minimal support
135
+ ESTIMATED IMPACT: Minority capture of protocol
136
+ NOVELTY: Quorum calculation exploit
137
+ ```
138
+
139
+ ### 6. Proposal Griefing / Censorship
140
+ ```solidity
141
+ HYPOTHESIS ID: H-GOV-006
142
+ ASSUMPTION BROKEN: "Legitimate proposals can always be submitted"
143
+ REALITY: Proposal process can be griefed
144
+ PRECONDITIONS:
145
+ - Proposal requires deposit or fee
146
+ - No protection against censorship
147
+ ATTACK SEQUENCE:
148
+ 1. Monitor for proposals you oppose
149
+ 2. Outvote or censor before they reach quorum
150
+ 3. Or: Flood governance with spam proposals
151
+ 4. Legitimate proposals cannot get attention or quorum
152
+ SUCCESS CONDITION: Governance gridlock, attacker preferences enforced
153
+ ESTIMATED IMPACT: Governance paralysis
154
+ NOVELTY: Denial of service on governance
155
+ ```
156
+
157
+ ### 7. Execution Reentrancy
158
+ ```solidity
159
+ HYPOTHESIS ID: H-GOV-007
160
+ ASSUMPTION BROKEN: "Proposal execution is reentrancy-safe"
161
+ REALITY: External calls during execution can be exploited
162
+ PRECONDITIONS:
163
+ - Proposal execution makes external calls
164
+ - State updated after external call
165
+ ATTACK SEQUENCE:
166
+ 1. Create proposal that calls malicious contract
167
+ 2. During execution, reenter governance contract
168
+ 3. Modify proposal state or execute again
169
+ 4. Extract value or double-execute
170
+ SUCCESS CONDITION: Proposal executes multiple times or state corrupted
171
+ ESTIMATED IMPACT: Fund loss, governance state corruption
172
+ NOVELTY: Reentrancy in governance execution
173
+ ```
174
+
175
+ ---
176
+
177
+ ## Invariants to Test
178
+
179
+ ```solidity
180
+ // INVARIANT 1: Voting power = token balance (or delegated amount)
181
+ assert(votingPower[user] == tokenBalance[user] + delegatedIn[user] - delegatedOut[user]);
182
+
183
+ // INVARIANT 2: Proposal executed exactly once
184
+ assert(!proposalExecuted[id] || proposal[id].executed);
185
+
186
+ // INVARIANT 3: Timelock enforced
187
+ assert(block.timestamp >= proposal[id].executionTime);
188
+
189
+ // INVARIANT 4: Quorum properly calculated
190
+ assert(quorumReached[id] == (votesFor[id] + votesAgainst[id] + votesAbstain[id]) >= quorum);
191
+
192
+ // INVARIANT 5: No double voting
193
+ for each user: assert(voted[user][proposalId] == false || voteWeight[user] counted once);
194
+ ```
195
+
196
+ ---
197
+
198
+ ## Foundry Test Skeleton
199
+
200
+ ```solidity
201
+ contract GovernanceHypothesisTest is Test {
202
+ IGovernance gov;
203
+ IERC20 govToken;
204
+ ITimelock timelock;
205
+ ITreasury treasury;
206
+
207
+ function test_flashLoanGovernanceAttack() public {
208
+ // Setup: Flash loan provider, governance tokens available
209
+ // Attack: Borrow, vote, pass malicious proposal, execute, repay
210
+ // Assert: Treasury drained or protocol captured
211
+ }
212
+
213
+ function test_proposalFrontRunning() public {
214
+ // Setup: Legitimate proposal pending
215
+ // Attack: Front-run with competing proposal
216
+ // Assert: Attacker proposal wins
217
+ }
218
+
219
+ function test_timelockBypass() public {
220
+ // Setup: Emergency guardian exists
221
+ // Attack: Compromise guardian, bypass timelock
222
+ // Assert: Action executed immediately
223
+ }
224
+
225
+ function test_quorumManipulation() public {
226
+ // Setup: Identify inactive token supply
227
+ // Attack: Accumulate just enough for effective quorum
228
+ // Assert: Proposal passes with minimal support
229
+ }
230
+
231
+ function test_executionReentrancy() public {
232
+ // Setup: Malicious proposal target
233
+ // Attack: Reenter during execution
234
+ // Assert: Double execution or state corruption
235
+ }
236
+ }
237
+ ```
238
+
239
+ ---
240
+
241
+ ## Related Vulnerabilities
242
+ - [[../vulnerabilities/reentrancy]]
243
+ - [[../vulnerabilities/access-control]]
244
+ - [[../vulnerabilities/oracle-manipulation]]
245
+
246
+ ---
247
+
248
+ ## Real-World Governance Exploits (Reference)
249
+ | Protocol | Year | Loss | Vector |
250
+ |----------|------|------|--------|
251
+ | Beanstalk | 2022 | $180M | Flash loan governance (majority vote capture) |
252
+ | DAO (Classic) | 2016 | $60M | Reentrancy during execution |
253
+ | Various DAOs | 2023+ | Multiple | Governance token concentration |
254
+
255
+ ---
256
+
257
+ ## Validation Checklist
258
+ - [ ] Hypothesis exploits governance-specific mechanics
259
+ - [ ] Considers flash loan capabilities
260
+ - [ ] Tests timelock and emergency bypasses
261
+ - [ ] Accounts for voting power manipulation
262
+ - [ ] Checks proposal lifecycle thoroughly
263
+ - [ ] Considers economic and social attack vectors