web3-systemic-agent 1.0.2__py3-none-any.whl
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.
- scripts/active_contract_hunter.py +262 -0
- scripts/block_contract_scanner.py +887 -0
- scripts/client_agent_x402.py +584 -0
- scripts/dex_pool_monitor.py +1418 -0
- scripts/governance_daemon.py +683 -0
- scripts/governance_listener.py +201 -0
- scripts/register_erc8004_agent.py +297 -0
- scripts/setup_buyer_wallet.py +193 -0
- src/api.py +5094 -0
- src/chain_inspector.py +256 -0
- src/discovery_hunter.py +1000 -0
- src/engine.py +281 -0
- src/governance_connector.py +548 -0
- src/mcp_server.py +2048 -0
- src/preflight_firewall.py +603 -0
- src/report.py +142 -0
- src/schemas.py +330 -0
- src/semantic_evaluator.py +981 -0
- src/source_resolver.py +792 -0
- src/storage.py +863 -0
- src/task_worker.py +325 -0
- src/test_cache_and_telemetry.py +488 -0
- src/x402_payment.py +1540 -0
- web3_systemic_agent-1.0.2.dist-info/METADATA +511 -0
- web3_systemic_agent-1.0.2.dist-info/RECORD +29 -0
- web3_systemic_agent-1.0.2.dist-info/WHEEL +5 -0
- web3_systemic_agent-1.0.2.dist-info/entry_points.txt +3 -0
- web3_systemic_agent-1.0.2.dist-info/licenses/LICENSE +201 -0
- web3_systemic_agent-1.0.2.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Preflight Firewall for Web3 Agent: Pre-Sign Static Analysis, EIP-712 Inspection,
|
|
3
|
+
Calldata Decoding, Indirect Prompt Injection (IPI) Defense, and On-Chain Simulation (eth_call).
|
|
4
|
+
|
|
5
|
+
Provides a deterministic zero-cost security gate before signing or executing transactions.
|
|
6
|
+
Evaluates:
|
|
7
|
+
1. Calldata selectors & arguments: flags unlimited ERC-20 approvals, Permit2, setApprovalForAll,
|
|
8
|
+
ownership transfers, and proxy upgrades.
|
|
9
|
+
2. EIP-712 Typed Data: inspects Permit / Permit2 allowances and detects Gnosis Safe SafeTx DelegateCall.
|
|
10
|
+
3. Indirect Prompt Injection (IPI): scans text and EIP-712 fields for hidden/zero-width Unicode
|
|
11
|
+
characters and adversarial prompt injection patterns.
|
|
12
|
+
4. On-chain eth_call Simulation: simulates transaction execution via AsyncWeb3 to catch EVM reverts
|
|
13
|
+
prior to signing.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Dict, Any, Optional, List, Tuple, Union, Literal
|
|
21
|
+
from web3 import Web3
|
|
22
|
+
from web3.exceptions import Web3Exception, ContractLogicError, ContractCustomError
|
|
23
|
+
|
|
24
|
+
# Ensure module search paths support running directly or as a package
|
|
25
|
+
_CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
26
|
+
_ROOT_DIR = os.path.abspath(os.path.join(_CURRENT_DIR, "..")) if os.path.basename(_CURRENT_DIR) == "src" else _CURRENT_DIR
|
|
27
|
+
_SRC_DIR = os.path.join(_ROOT_DIR, "src")
|
|
28
|
+
for _p in (_ROOT_DIR, _SRC_DIR):
|
|
29
|
+
if _p not in sys.path:
|
|
30
|
+
sys.path.insert(0, _p)
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
from src.schemas import (
|
|
34
|
+
PreflightRequest,
|
|
35
|
+
PreflightVerdict,
|
|
36
|
+
PreflightSimulationResult,
|
|
37
|
+
ChainId,
|
|
38
|
+
)
|
|
39
|
+
from src.chain_inspector import ChainInspector
|
|
40
|
+
except ImportError:
|
|
41
|
+
from schemas import (
|
|
42
|
+
PreflightRequest,
|
|
43
|
+
PreflightVerdict,
|
|
44
|
+
PreflightSimulationResult,
|
|
45
|
+
ChainId,
|
|
46
|
+
)
|
|
47
|
+
from chain_inspector import ChainInspector
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger(__name__)
|
|
50
|
+
|
|
51
|
+
# Regex for invisible, zero-width, and bidirectional override characters
|
|
52
|
+
INVISIBLE_UNICODE_RE = re.compile(r"[\u200b\u200c\u200d\ufeff\u202a-\u202e\u2066-\u2069]")
|
|
53
|
+
|
|
54
|
+
# Prompt injection & adversarial command patterns
|
|
55
|
+
PROMPT_INJECTION_PATTERNS = [
|
|
56
|
+
(re.compile(r"ignore\s+(?:all\s+|previous\s+|prior\s+)?instructions", re.IGNORECASE), "ignore instructions"),
|
|
57
|
+
(re.compile(r"disregard\s+(?:all\s+|previous\s+|prior\s+)?instructions", re.IGNORECASE), "disregard instructions"),
|
|
58
|
+
(re.compile(r"system\s+prompt", re.IGNORECASE), "system prompt"),
|
|
59
|
+
(re.compile(r"you\s+are\s+now", re.IGNORECASE), "you are now"),
|
|
60
|
+
(re.compile(r"override\s+security", re.IGNORECASE), "override security"),
|
|
61
|
+
(re.compile(r"approve\s+the\s+transaction", re.IGNORECASE), "approve the transaction"),
|
|
62
|
+
(re.compile(r"return\s+APPROVE", re.IGNORECASE), "return APPROVE"),
|
|
63
|
+
(re.compile(r"risk_score.*?0", re.IGNORECASE), "risk_score manipulation targeting 0"),
|
|
64
|
+
(re.compile(r"transfer.*?treasury", re.IGNORECASE), "unauthorized treasury transfer directive"),
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def extract_strings_from_obj(obj: Any) -> List[str]:
|
|
69
|
+
"""Recursively collects all string values from a nested data structure."""
|
|
70
|
+
strings: List[str] = []
|
|
71
|
+
if isinstance(obj, str):
|
|
72
|
+
strings.append(obj)
|
|
73
|
+
elif isinstance(obj, dict):
|
|
74
|
+
for k, v in obj.items():
|
|
75
|
+
if isinstance(k, str):
|
|
76
|
+
strings.append(k)
|
|
77
|
+
strings.extend(extract_strings_from_obj(v))
|
|
78
|
+
elif isinstance(obj, (list, tuple, set)):
|
|
79
|
+
for item in obj:
|
|
80
|
+
strings.extend(extract_strings_from_obj(item))
|
|
81
|
+
return strings
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def scan_prompt_injection(text: Optional[str]) -> Tuple[bool, List[str], float]:
|
|
85
|
+
"""
|
|
86
|
+
Scans text for:
|
|
87
|
+
- Invisible / zero-width / bidirectional override Unicode characters.
|
|
88
|
+
- Prompt injection / system override regex patterns.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
(prompt_injection_detected, matched_signals, risk_score)
|
|
92
|
+
Risk score is 9.5 if any signal matches, else 0.0.
|
|
93
|
+
"""
|
|
94
|
+
if not text or not isinstance(text, str):
|
|
95
|
+
return False, [], 0.0
|
|
96
|
+
|
|
97
|
+
signals: List[str] = []
|
|
98
|
+
|
|
99
|
+
# 1. Unicode invisible / bidi overrides
|
|
100
|
+
found_chars = INVISIBLE_UNICODE_RE.findall(text)
|
|
101
|
+
if found_chars:
|
|
102
|
+
signals.append(f"Detected {len(found_chars)} invisible or bidirectional override Unicode characters")
|
|
103
|
+
|
|
104
|
+
# 2. Injection patterns
|
|
105
|
+
for pattern, name in PROMPT_INJECTION_PATTERNS:
|
|
106
|
+
if pattern.search(text):
|
|
107
|
+
signals.append(f"Prompt injection pattern matched: '{name}'")
|
|
108
|
+
|
|
109
|
+
if signals:
|
|
110
|
+
return True, signals, 9.5
|
|
111
|
+
return False, [], 0.0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def decode_calldata_and_approvals(calldata: str) -> Tuple[Dict[str, Any], List[str], float]:
|
|
115
|
+
"""
|
|
116
|
+
Inspects 4-byte selector and 32-byte ABI words in calldata:
|
|
117
|
+
- 0x095ea7b3 (approve(address,uint256)), 0x39509351 (increaseAllowance(address,uint256)):
|
|
118
|
+
flags unlimited approval (>= 2**255 - 1) with risk >= 7.5.
|
|
119
|
+
- 0xa22cb465 (setApprovalForAll(address,bool)):
|
|
120
|
+
flags operator approval if true with risk >= 8.0.
|
|
121
|
+
- 0x87517c45 (Permit2 approve), 0x2b67b570 (Permit2 permit), 0xd505accf (EIP-2612 permit):
|
|
122
|
+
flags Permit2 / off-chain signature allowance delegation with risk >= 7.0.
|
|
123
|
+
- 0xf2fde38b (transferOwnership), 0x3659cfe6 (upgradeTo), 0x4f1ef286 (upgradeToAndCall):
|
|
124
|
+
flags critical administrative / proxy upgrade action with risk >= 8.5.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
(decoded_action_dict, approval_risks_list, base_risk_score)
|
|
128
|
+
"""
|
|
129
|
+
if not calldata or not isinstance(calldata, str):
|
|
130
|
+
return {"selector": "0x", "signature": "native_transfer_or_empty", "args": {}}, [], 0.0
|
|
131
|
+
|
|
132
|
+
raw = calldata.strip()
|
|
133
|
+
if raw.startswith("0x") or raw.startswith("0X"):
|
|
134
|
+
raw = raw[2:]
|
|
135
|
+
|
|
136
|
+
if len(raw) < 8:
|
|
137
|
+
return {"selector": "0x", "signature": "native_transfer_or_empty", "args": {}}, [], 0.0
|
|
138
|
+
|
|
139
|
+
selector = "0x" + raw[:8].lower()
|
|
140
|
+
payload = raw[8:]
|
|
141
|
+
words = [payload[i : i + 64] for i in range(0, len(payload), 64)]
|
|
142
|
+
|
|
143
|
+
def get_address(idx: int) -> Optional[str]:
|
|
144
|
+
if idx < len(words) and len(words[idx]) >= 40:
|
|
145
|
+
hex_addr = words[idx][-40:]
|
|
146
|
+
try:
|
|
147
|
+
return Web3.to_checksum_address("0x" + hex_addr)
|
|
148
|
+
except Exception:
|
|
149
|
+
return "0x" + hex_addr
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
def get_uint(idx: int) -> int:
|
|
153
|
+
if idx < len(words):
|
|
154
|
+
try:
|
|
155
|
+
return int(words[idx], 16)
|
|
156
|
+
except ValueError:
|
|
157
|
+
return 0
|
|
158
|
+
return 0
|
|
159
|
+
|
|
160
|
+
def get_bool(idx: int) -> bool:
|
|
161
|
+
return get_uint(idx) != 0
|
|
162
|
+
|
|
163
|
+
# 1. ERC-20 approve(address,uint256)
|
|
164
|
+
if selector == "0x095ea7b3":
|
|
165
|
+
spender = get_address(0)
|
|
166
|
+
amount = get_uint(1)
|
|
167
|
+
decoded = {
|
|
168
|
+
"selector": selector,
|
|
169
|
+
"signature": "approve(address,uint256)",
|
|
170
|
+
"args": {"spender": spender, "amount": amount},
|
|
171
|
+
}
|
|
172
|
+
risks: List[str] = []
|
|
173
|
+
risk_score = 0.0
|
|
174
|
+
if amount >= (2**255 - 1):
|
|
175
|
+
risks.append("Unlimited ERC-20 token approval (MAX_UINT256) detected")
|
|
176
|
+
risk_score = 7.5
|
|
177
|
+
return decoded, risks, risk_score
|
|
178
|
+
|
|
179
|
+
# 2. ERC-20 increaseAllowance(address,uint256)
|
|
180
|
+
if selector == "0x39509351":
|
|
181
|
+
spender = get_address(0)
|
|
182
|
+
amount = get_uint(1)
|
|
183
|
+
decoded = {
|
|
184
|
+
"selector": selector,
|
|
185
|
+
"signature": "increaseAllowance(address,uint256)",
|
|
186
|
+
"args": {"spender": spender, "amount": amount},
|
|
187
|
+
}
|
|
188
|
+
risks = []
|
|
189
|
+
risk_score = 0.0
|
|
190
|
+
if amount >= (2**255 - 1):
|
|
191
|
+
risks.append("Unlimited ERC-20 token approval (MAX_UINT256) detected")
|
|
192
|
+
risk_score = 7.5
|
|
193
|
+
return decoded, risks, risk_score
|
|
194
|
+
|
|
195
|
+
# 3. ERC-721 / ERC-1155 setApprovalForAll(address,bool)
|
|
196
|
+
if selector == "0xa22cb465":
|
|
197
|
+
operator = get_address(0)
|
|
198
|
+
approved = get_bool(1)
|
|
199
|
+
decoded = {
|
|
200
|
+
"selector": selector,
|
|
201
|
+
"signature": "setApprovalForAll(address,bool)",
|
|
202
|
+
"args": {"operator": operator, "approved": approved},
|
|
203
|
+
}
|
|
204
|
+
risks = []
|
|
205
|
+
risk_score = 0.0
|
|
206
|
+
if approved:
|
|
207
|
+
risks.append("Full collection operator approval (setApprovalForAll=true) detected")
|
|
208
|
+
risk_score = 8.0
|
|
209
|
+
return decoded, risks, risk_score
|
|
210
|
+
|
|
211
|
+
# 4. Permit2 approve(address,address,uint160,uint48)
|
|
212
|
+
if selector == "0x87517c45":
|
|
213
|
+
token = get_address(0)
|
|
214
|
+
spender = get_address(1)
|
|
215
|
+
amount = get_uint(2)
|
|
216
|
+
expiration = get_uint(3)
|
|
217
|
+
decoded = {
|
|
218
|
+
"selector": selector,
|
|
219
|
+
"signature": "approve(address,address,uint160,uint48)",
|
|
220
|
+
"args": {"token": token, "spender": spender, "amount": amount, "expiration": expiration},
|
|
221
|
+
}
|
|
222
|
+
risks = ["Permit2 off-chain signature allowance delegation detected"]
|
|
223
|
+
risk_score = 7.0
|
|
224
|
+
if amount >= (2**159 - 1) or amount >= (2**255 - 1):
|
|
225
|
+
risks.append("Unlimited Permit2 token allowance (MAX_UINT) detected")
|
|
226
|
+
risk_score = 7.5
|
|
227
|
+
return decoded, risks, risk_score
|
|
228
|
+
|
|
229
|
+
# 5. Permit2 permit(address,PermitSingle,bytes)
|
|
230
|
+
if selector == "0x2b67b570":
|
|
231
|
+
owner = get_address(0)
|
|
232
|
+
decoded = {
|
|
233
|
+
"selector": selector,
|
|
234
|
+
"signature": "permit(address,PermitSingle,bytes)",
|
|
235
|
+
"args": {"owner": owner},
|
|
236
|
+
}
|
|
237
|
+
risks = ["Permit2 off-chain signature allowance delegation detected"]
|
|
238
|
+
return decoded, risks, 7.0
|
|
239
|
+
|
|
240
|
+
# 6. EIP-2612 permit(address,address,uint256,uint256,uint8,bytes32,bytes32)
|
|
241
|
+
if selector == "0xd505accf":
|
|
242
|
+
owner = get_address(0)
|
|
243
|
+
spender = get_address(1)
|
|
244
|
+
value = get_uint(2)
|
|
245
|
+
deadline = get_uint(3)
|
|
246
|
+
decoded = {
|
|
247
|
+
"selector": selector,
|
|
248
|
+
"signature": "permit(address,address,uint256,uint256,uint8,bytes32,bytes32)",
|
|
249
|
+
"args": {"owner": owner, "spender": spender, "value": value, "deadline": deadline},
|
|
250
|
+
}
|
|
251
|
+
risks = ["EIP-2612 off-chain signature permit delegation detected"]
|
|
252
|
+
risk_score = 7.0
|
|
253
|
+
if value >= (2**255 - 1):
|
|
254
|
+
risks.append("Unlimited ERC-20 token approval (MAX_UINT256) detected")
|
|
255
|
+
risk_score = 7.5
|
|
256
|
+
return decoded, risks, risk_score
|
|
257
|
+
|
|
258
|
+
# 7. transferOwnership(address)
|
|
259
|
+
if selector == "0xf2fde38b":
|
|
260
|
+
new_owner = get_address(0)
|
|
261
|
+
decoded = {
|
|
262
|
+
"selector": selector,
|
|
263
|
+
"signature": "transferOwnership(address)",
|
|
264
|
+
"args": {"newOwner": new_owner},
|
|
265
|
+
}
|
|
266
|
+
risks = ["Critical administrative action: transferOwnership detected"]
|
|
267
|
+
return decoded, risks, 8.5
|
|
268
|
+
|
|
269
|
+
# 8. upgradeTo(address)
|
|
270
|
+
if selector == "0x3659cfe6":
|
|
271
|
+
new_impl = get_address(0)
|
|
272
|
+
decoded = {
|
|
273
|
+
"selector": selector,
|
|
274
|
+
"signature": "upgradeTo(address)",
|
|
275
|
+
"args": {"newImplementation": new_impl},
|
|
276
|
+
}
|
|
277
|
+
risks = ["Critical proxy upgrade action (upgradeTo) detected"]
|
|
278
|
+
return decoded, risks, 8.5
|
|
279
|
+
|
|
280
|
+
# 9. upgradeToAndCall(address,bytes)
|
|
281
|
+
if selector == "0x4f1ef286":
|
|
282
|
+
new_impl = get_address(0)
|
|
283
|
+
decoded = {
|
|
284
|
+
"selector": selector,
|
|
285
|
+
"signature": "upgradeToAndCall(address,bytes)",
|
|
286
|
+
"args": {"newImplementation": new_impl},
|
|
287
|
+
}
|
|
288
|
+
risks = ["Critical proxy upgrade action (upgradeToAndCall) detected"]
|
|
289
|
+
return decoded, risks, 8.5
|
|
290
|
+
|
|
291
|
+
# 10. Standard transfer(address,uint256)
|
|
292
|
+
if selector == "0xa9059cbb":
|
|
293
|
+
to = get_address(0)
|
|
294
|
+
amount = get_uint(1)
|
|
295
|
+
decoded = {
|
|
296
|
+
"selector": selector,
|
|
297
|
+
"signature": "transfer(address,uint256)",
|
|
298
|
+
"args": {"to": to, "amount": amount},
|
|
299
|
+
}
|
|
300
|
+
return decoded, [], 0.0
|
|
301
|
+
|
|
302
|
+
# 11. Standard transferFrom(address,address,uint256)
|
|
303
|
+
if selector == "0x23b872dd":
|
|
304
|
+
sender = get_address(0)
|
|
305
|
+
recipient = get_address(1)
|
|
306
|
+
amount = get_uint(2)
|
|
307
|
+
decoded = {
|
|
308
|
+
"selector": selector,
|
|
309
|
+
"signature": "transferFrom(address,address,uint256)",
|
|
310
|
+
"args": {"from": sender, "to": recipient, "amount": amount},
|
|
311
|
+
}
|
|
312
|
+
return decoded, [], 0.0
|
|
313
|
+
|
|
314
|
+
# Unknown or unhandled selector
|
|
315
|
+
decoded = {
|
|
316
|
+
"selector": selector,
|
|
317
|
+
"signature": "unknown_selector",
|
|
318
|
+
"args": {},
|
|
319
|
+
}
|
|
320
|
+
return decoded, [], 0.0
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def inspect_eip712_typed_data(
|
|
324
|
+
typed_data: Optional[Dict[str, Any]],
|
|
325
|
+
) -> Tuple[List[str], float]:
|
|
326
|
+
"""
|
|
327
|
+
Safely inspects domain, primaryType, and message of EIP-712 typed data:
|
|
328
|
+
- Detects PermitSingle, PermitBatch, PermitTransferFrom, Permit:
|
|
329
|
+
checks details.amount or value for unlimited/huge allowance (>= 2**159 - 1 for uint160
|
|
330
|
+
or >= 2**255 - 1 for uint256), spender/to, and excessive expiration/sigDeadline.
|
|
331
|
+
- Detects Gnosis Safe SafeTx: if operation == 1 (DelegateCall), flags critical risk (>= 9.0).
|
|
332
|
+
- Checks if domain.verifyingContract is missing when primaryType is a permit or transaction type.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
(findings_list, eip712_risk_score)
|
|
336
|
+
"""
|
|
337
|
+
if not typed_data or not isinstance(typed_data, dict):
|
|
338
|
+
return [], 0.0
|
|
339
|
+
|
|
340
|
+
findings: List[str] = []
|
|
341
|
+
risk_score = 0.0
|
|
342
|
+
|
|
343
|
+
domain = typed_data.get("domain", {})
|
|
344
|
+
primary_type = typed_data.get("primaryType", "")
|
|
345
|
+
message = typed_data.get("message", {})
|
|
346
|
+
types = typed_data.get("types", {})
|
|
347
|
+
|
|
348
|
+
if not isinstance(domain, dict):
|
|
349
|
+
domain = {}
|
|
350
|
+
if not isinstance(message, dict):
|
|
351
|
+
message = {}
|
|
352
|
+
|
|
353
|
+
sensitive_types = {"Permit", "PermitSingle", "PermitBatch", "PermitTransferFrom", "SafeTx"}
|
|
354
|
+
is_sensitive = (
|
|
355
|
+
primary_type in sensitive_types
|
|
356
|
+
or "permit" in primary_type.lower()
|
|
357
|
+
or "safetx" in primary_type.lower()
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
# 1. Missing verifyingContract check
|
|
361
|
+
verifying_contract = domain.get("verifyingContract")
|
|
362
|
+
if is_sensitive and (
|
|
363
|
+
not verifying_contract
|
|
364
|
+
or verifying_contract == "0x"
|
|
365
|
+
or verifying_contract == "0x0000000000000000000000000000000000000000"
|
|
366
|
+
):
|
|
367
|
+
findings.append("Missing verifyingContract in EIP-712 domain for sensitive signing payload")
|
|
368
|
+
risk_score = max(risk_score, 7.5)
|
|
369
|
+
|
|
370
|
+
# 2. Gnosis Safe SafeTx: operation == 1 (DelegateCall)
|
|
371
|
+
if primary_type == "SafeTx" or "SafeTx" in types:
|
|
372
|
+
op = message.get("operation")
|
|
373
|
+
if op == 1 or str(op).strip() == "1" or str(op).upper() == "DELEGATECALL":
|
|
374
|
+
findings.append("Critical SafeTx DelegateCall (operation=1) detected in EIP-712 payload")
|
|
375
|
+
risk_score = max(risk_score, 9.0)
|
|
376
|
+
|
|
377
|
+
# 3. Permit amounts & expirations inspection
|
|
378
|
+
def inspect_amount_and_expiration(amt_val: Any, exp_val: Any):
|
|
379
|
+
nonlocal risk_score
|
|
380
|
+
if amt_val is not None:
|
|
381
|
+
try:
|
|
382
|
+
amt_int = int(str(amt_val), 0)
|
|
383
|
+
if amt_int >= (2**159 - 1) or amt_int >= (2**255 - 1):
|
|
384
|
+
findings.append(f"Unlimited/excessive allowance ({amt_int}) requested in EIP-712 permit payload")
|
|
385
|
+
risk_score = max(risk_score, 7.5)
|
|
386
|
+
except (ValueError, TypeError):
|
|
387
|
+
pass
|
|
388
|
+
|
|
389
|
+
if exp_val is not None:
|
|
390
|
+
try:
|
|
391
|
+
exp_int = int(str(exp_val), 0)
|
|
392
|
+
if exp_int >= (2**47 - 1) or exp_int > 2524608000:
|
|
393
|
+
findings.append(f"Excessive expiration timestamp ({exp_int}) detected in EIP-712 permit payload")
|
|
394
|
+
risk_score = max(risk_score, 7.0)
|
|
395
|
+
except (ValueError, TypeError):
|
|
396
|
+
pass
|
|
397
|
+
|
|
398
|
+
if (
|
|
399
|
+
primary_type in ("Permit", "PermitSingle", "PermitBatch", "PermitTransferFrom")
|
|
400
|
+
or "permit" in primary_type.lower()
|
|
401
|
+
):
|
|
402
|
+
details = message.get("details")
|
|
403
|
+
if isinstance(details, dict):
|
|
404
|
+
inspect_amount_and_expiration(details.get("amount"), details.get("expiration"))
|
|
405
|
+
elif isinstance(details, list):
|
|
406
|
+
for item in details:
|
|
407
|
+
if isinstance(item, dict):
|
|
408
|
+
inspect_amount_and_expiration(item.get("amount"), item.get("expiration"))
|
|
409
|
+
|
|
410
|
+
inspect_amount_and_expiration(
|
|
411
|
+
message.get("amount") or message.get("value"),
|
|
412
|
+
message.get("expiration") or message.get("sigDeadline") or message.get("deadline"),
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
if risk_score == 0.0:
|
|
416
|
+
risk_score = 6.0
|
|
417
|
+
findings.append(f"EIP-712 permit allowance delegation ({primary_type}) detected")
|
|
418
|
+
|
|
419
|
+
return findings, risk_score
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
class PreflightFirewall:
|
|
423
|
+
"""
|
|
424
|
+
Preflight Security Firewall for Web3 Transactions and Typed Data.
|
|
425
|
+
Enforces deterministic zero-cost security verification:
|
|
426
|
+
- Calldata decoding & approval risk detection
|
|
427
|
+
- EIP-712 permit & SafeTx DelegateCall inspection
|
|
428
|
+
- Indirect Prompt Injection (IPI) defense
|
|
429
|
+
- AsyncWeb3 eth_call on-chain simulation
|
|
430
|
+
"""
|
|
431
|
+
|
|
432
|
+
def __init__(self, rpc_url: Optional[Union[str, List[str]]] = None):
|
|
433
|
+
self.rpc_url = rpc_url
|
|
434
|
+
|
|
435
|
+
async def simulate_eth_call(
|
|
436
|
+
self, req: PreflightRequest, target_addr: str
|
|
437
|
+
) -> PreflightSimulationResult:
|
|
438
|
+
"""
|
|
439
|
+
Executes an on-chain eth_call simulation using AsyncWeb3.
|
|
440
|
+
Distinguishes EVM reverts from infrastructure/network RPC errors with automatic failover.
|
|
441
|
+
"""
|
|
442
|
+
tx_dict: Dict[str, Any] = {
|
|
443
|
+
"to": target_addr,
|
|
444
|
+
"data": req.calldata or "0x",
|
|
445
|
+
"value": int(req.value_wei),
|
|
446
|
+
}
|
|
447
|
+
if req.from_address:
|
|
448
|
+
tx_dict["from"] = req.from_address
|
|
449
|
+
|
|
450
|
+
try:
|
|
451
|
+
rpc_urls = ChainInspector.resolve_rpc_urls(int(req.chain_id), self.rpc_url)
|
|
452
|
+
except Exception as exc:
|
|
453
|
+
return PreflightSimulationResult(
|
|
454
|
+
executed=False,
|
|
455
|
+
success=None,
|
|
456
|
+
rpc_error=f"Failed to resolve RPC URL for chain {req.chain_id}: {exc}",
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
last_rpc_error: Optional[Exception] = None
|
|
460
|
+
|
|
461
|
+
for url in rpc_urls:
|
|
462
|
+
try:
|
|
463
|
+
w3 = ChainInspector._get_or_create_w3(int(req.chain_id), url)
|
|
464
|
+
res = await w3.eth.call(tx_dict)
|
|
465
|
+
hex_res = res.hex() if isinstance(res, (bytes, bytearray)) else str(res)
|
|
466
|
+
if not hex_res.startswith("0x"):
|
|
467
|
+
hex_res = "0x" + hex_res
|
|
468
|
+
return PreflightSimulationResult(
|
|
469
|
+
executed=True,
|
|
470
|
+
success=True,
|
|
471
|
+
return_data=hex_res,
|
|
472
|
+
revert_reason=None,
|
|
473
|
+
rpc_error=None,
|
|
474
|
+
)
|
|
475
|
+
except (ContractLogicError, ContractCustomError) as rev_exc:
|
|
476
|
+
return PreflightSimulationResult(
|
|
477
|
+
executed=True,
|
|
478
|
+
success=False,
|
|
479
|
+
return_data=None,
|
|
480
|
+
revert_reason=str(rev_exc),
|
|
481
|
+
rpc_error=None,
|
|
482
|
+
)
|
|
483
|
+
except Exception as exc:
|
|
484
|
+
msg = str(exc).lower()
|
|
485
|
+
# Check for EVM revert indicators returned by RPC provider
|
|
486
|
+
if any(k in msg for k in ("revert", "execution reverted", "vm exception", "out of gas", "invalid opcode")):
|
|
487
|
+
return PreflightSimulationResult(
|
|
488
|
+
executed=True,
|
|
489
|
+
success=False,
|
|
490
|
+
return_data=None,
|
|
491
|
+
revert_reason=str(exc),
|
|
492
|
+
rpc_error=None,
|
|
493
|
+
)
|
|
494
|
+
# Network or infrastructure error: record and attempt fallback RPC
|
|
495
|
+
last_rpc_error = exc
|
|
496
|
+
continue
|
|
497
|
+
|
|
498
|
+
return PreflightSimulationResult(
|
|
499
|
+
executed=False,
|
|
500
|
+
success=None,
|
|
501
|
+
return_data=None,
|
|
502
|
+
revert_reason=None,
|
|
503
|
+
rpc_error=str(last_rpc_error) if last_rpc_error else "All RPC endpoints failed",
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
async def evaluate(self, req: PreflightRequest) -> PreflightVerdict:
|
|
507
|
+
"""
|
|
508
|
+
Evaluates a PreflightRequest through the firewall pipeline:
|
|
509
|
+
1. Decodes calldata & inspects ERC-20/Permit2/admin approvals.
|
|
510
|
+
2. Inspects EIP-712 typed data (Permit / SafeTx DelegateCall).
|
|
511
|
+
3. Scans untrusted text and EIP-712 payloads for indirect prompt injection.
|
|
512
|
+
4. Simulates eth_call on-chain (if enabled and target address is provided).
|
|
513
|
+
5. Applies deterministic security verdict policy (ALLOW, MANUAL_REVIEW, or BLOCK).
|
|
514
|
+
"""
|
|
515
|
+
target_addr = req.to_address or req.target_address
|
|
516
|
+
|
|
517
|
+
# 1. Calldata decoding & approval checks
|
|
518
|
+
decoded_action, approval_risks, calldata_score = decode_calldata_and_approvals(req.calldata)
|
|
519
|
+
|
|
520
|
+
# 2. EIP-712 typed data inspection
|
|
521
|
+
eip712_findings, eip712_score = inspect_eip712_typed_data(req.eip712_typed_data)
|
|
522
|
+
|
|
523
|
+
# 3. Indirect prompt injection scan
|
|
524
|
+
ipi_detected = False
|
|
525
|
+
ipi_signals: List[str] = []
|
|
526
|
+
ipi_score = 0.0
|
|
527
|
+
|
|
528
|
+
if req.untrusted_text:
|
|
529
|
+
d_txt, s_txt, sc_txt = scan_prompt_injection(req.untrusted_text)
|
|
530
|
+
if d_txt:
|
|
531
|
+
ipi_detected = True
|
|
532
|
+
ipi_signals.extend(s_txt)
|
|
533
|
+
ipi_score = max(ipi_score, sc_txt)
|
|
534
|
+
|
|
535
|
+
if req.eip712_typed_data:
|
|
536
|
+
eip_strings = extract_strings_from_obj(req.eip712_typed_data)
|
|
537
|
+
for s_val in eip_strings:
|
|
538
|
+
d_eip, s_eip, sc_eip = scan_prompt_injection(s_val)
|
|
539
|
+
if d_eip:
|
|
540
|
+
ipi_detected = True
|
|
541
|
+
ipi_signals.extend(s_eip)
|
|
542
|
+
ipi_score = max(ipi_score, sc_eip)
|
|
543
|
+
|
|
544
|
+
# 4. On-chain simulation
|
|
545
|
+
simulation = PreflightSimulationResult()
|
|
546
|
+
sim_revert_score = 0.0
|
|
547
|
+
|
|
548
|
+
if req.run_simulation and target_addr:
|
|
549
|
+
try:
|
|
550
|
+
simulation = await self.simulate_eth_call(req, target_addr)
|
|
551
|
+
if simulation.executed and simulation.success is False:
|
|
552
|
+
sim_revert_score = 8.5
|
|
553
|
+
except Exception as e:
|
|
554
|
+
simulation = PreflightSimulationResult(executed=False, rpc_error=str(e))
|
|
555
|
+
|
|
556
|
+
# 5. Combined risk score calculation
|
|
557
|
+
risk_score = min(10.0, max(calldata_score, eip712_score, ipi_score, sim_revert_score))
|
|
558
|
+
|
|
559
|
+
# 6. Flagged issues compilation
|
|
560
|
+
flagged_issues: List[str] = []
|
|
561
|
+
flagged_issues.extend(approval_risks)
|
|
562
|
+
flagged_issues.extend(eip712_findings)
|
|
563
|
+
if ipi_detected:
|
|
564
|
+
flagged_issues.extend([f"Prompt injection signal: {sig}" for sig in ipi_signals])
|
|
565
|
+
if simulation.executed and simulation.success is False:
|
|
566
|
+
flagged_issues.append(f"Simulation reverted: {simulation.revert_reason or 'execution reverted'}")
|
|
567
|
+
if simulation.rpc_error:
|
|
568
|
+
flagged_issues.append(f"Simulation RPC error: {simulation.rpc_error}")
|
|
569
|
+
|
|
570
|
+
# 7. Deterministic verdict policy
|
|
571
|
+
if risk_score >= 8.0 or ipi_detected or (simulation.executed and simulation.success is False):
|
|
572
|
+
verdict: Literal["ALLOW", "BLOCK", "MANUAL_REVIEW"] = "BLOCK"
|
|
573
|
+
elif risk_score >= 5.0:
|
|
574
|
+
verdict = "MANUAL_REVIEW"
|
|
575
|
+
else:
|
|
576
|
+
verdict = "ALLOW"
|
|
577
|
+
|
|
578
|
+
# 8. Human-readable summary
|
|
579
|
+
if verdict == "BLOCK":
|
|
580
|
+
issues_summary = "; ".join(flagged_issues[:3]) if flagged_issues else "Risk threshold exceeded"
|
|
581
|
+
summary = f"Preflight BLOCKED: Risk score {risk_score:.1f}/10. Reason(s): {issues_summary}."
|
|
582
|
+
elif verdict == "MANUAL_REVIEW":
|
|
583
|
+
issues_summary = "; ".join(flagged_issues[:3]) if flagged_issues else "Elevated risk parameters"
|
|
584
|
+
summary = f"Preflight MANUAL_REVIEW: Risk score {risk_score:.1f}/10. Needs confirmation: {issues_summary}."
|
|
585
|
+
else:
|
|
586
|
+
summary = f"Preflight ALLOWED: Risk score {risk_score:.1f}/10. Transaction parameters validated successfully."
|
|
587
|
+
|
|
588
|
+
return PreflightVerdict(
|
|
589
|
+
verdict=verdict,
|
|
590
|
+
risk_score=round(risk_score, 2),
|
|
591
|
+
chain_id=int(req.chain_id),
|
|
592
|
+
target_address=target_addr,
|
|
593
|
+
decoded_action=decoded_action,
|
|
594
|
+
approval_risks=approval_risks,
|
|
595
|
+
eip712_findings=eip712_findings,
|
|
596
|
+
prompt_injection_detected=ipi_detected,
|
|
597
|
+
prompt_injection_signals=ipi_signals,
|
|
598
|
+
simulation=simulation,
|
|
599
|
+
flagged_issues=flagged_issues,
|
|
600
|
+
summary=summary,
|
|
601
|
+
llm_invoked=False,
|
|
602
|
+
payment=None,
|
|
603
|
+
)
|