Repository navigation
Expand file tree
/
Copy pathaccess_matrix.py
More file actions
180 lines (147 loc) · 5.44 KB
/
Copy pathaccess_matrix.py
File metadata and controls
180 lines (147 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
from __future__ import annotations
import re
import argparse
import sys
from typing import List, Dict, Any
from path_security import sanitize_cli_path
# --- CONFIGURATION ---
# Regex to capture function headers:
# function name(...) visibility modifiers returns(...)
FUNCTION_PATTERN = re.compile(
r"function\s+(\w+)\s*\((.*?)\)\s*(.*?)(?:\{|;)",
re.DOTALL | re.MULTILINE,
)
# Keywords that indicate a function is Read-Only (Safe)
READ_ONLY_MODIFIERS = ["view", "pure"]
# Modifiers that indicate Authorization (Admin/Restricted)
AUTH_MODIFIERS = ["onlyOwner", "onlyRole", "onlyMinter", "auth", "requiresAuth"]
def parse_solidity_source(content: str) -> List[Dict[str, Any]]:
"""Parse Solidity source and extract function information.
Args:
content: Solidity source content.
Returns:
List of dictionaries containing function information.
"""
# Remove comments to avoid false positives
# (Simple removal of // and /* ... */)
content = re.sub(r"//.*", "", content)
content = re.sub(r"/\*.*?\*/", "", content, flags=re.DOTALL)
matches = FUNCTION_PATTERN.findall(content)
functions: List[Dict] = []
for match in matches:
name = match[0]
params = match[1] # Not used for matrix but good for debug
decorators = match[2]
# Clean up whitespace
decorators = " ".join(decorators.split())
# Determine Visibility
visibility = "default"
if "external" in decorators:
visibility = "external"
elif "public" in decorators:
visibility = "public"
elif "internal" in decorators:
visibility = "internal"
elif "private" in decorators:
visibility = "private"
# Determine Mutability (Read vs Write)
is_read_only = any(x in decorators for x in READ_ONLY_MODIFIERS)
state_mutability = "READ" if is_read_only else "WRITE"
# Extract Modifiers (excluding visibility/mutability keywords)
keywords = [
"external",
"public",
"internal",
"private",
"view",
"pure",
"payable",
"virtual",
"override",
"returns",
]
raw_mods = [
m.strip()
for m in decorators.split()
if m.strip() and m not in keywords and "(" not in m
]
# Check for auth
auth_mechanisms = [
m for m in raw_mods if any(auth in m for auth in AUTH_MODIFIERS)
]
other_mods = [m for m in raw_mods if m not in auth_mechanisms]
# RISK ASSESSMENT
# Critical Risk: External/Public + WRITE + No Auth
risk = "LOW"
if state_mutability == "WRITE" and visibility in ["public", "external"]:
if auth_mechanisms:
risk = "ADMIN" # Protected by owner/role
else:
risk = "HIGH" # Anyone can call this! (Open access)
functions.append(
{
"name": name,
"visibility": visibility,
"mutability": state_mutability,
"auth": auth_mechanisms,
"mods": other_mods,
"risk": risk,
}
)
return functions
def parse_solidity_file(filepath: str) -> List[Dict[str, Any]]:
"""Parse a Solidity file and extract function information."""
safe_path = sanitize_cli_path(filepath, allowed_suffixes={".sol"})
with open(safe_path, "r", encoding="utf-8") as f:
return parse_solidity_source(f.read())
def generate_matrix_report(functions: List[Dict[str, Any]]) -> None:
"""Generate and print an access control matrix report.
Args:
functions: List of function information dictionaries.
"""
print("\n" + "=" * 80)
print(" 🔑 ACCESS CONTROL MATRIX")
print("=" * 80)
print(f"{'RISK':<10} | {'FUNCTION NAME':<25} | {'ACCESS':<10} | {'AUTH / MODIFIERS':<30}")
print("-" * 80)
for f in functions:
# Filter: We usually don't care about internal/private for this matrix
if f["visibility"] in ["internal", "private"]:
continue
# Color Coding
color = "\033[0m" # Reset
risk_label = f["risk"]
if f["risk"] == "HIGH":
color = "\033[91m" # Red (Critical)
risk_label = "🚨 PUBLIC"
elif f["risk"] == "ADMIN":
color = "\033[96m" # Cyan (Protected)
risk_label = "🛡️ ADMIN"
elif f["mutability"] == "READ":
color = "\033[90m" # Gray (View only)
risk_label = " VIEW"
# Format Auth/Modifiers
auth_str = ", ".join(f["auth"]) if f["auth"] else "Anyone"
if f["mods"]:
auth_str += f" (+{', '.join(f['mods'])})"
print(
f"{color}{risk_label:<10} | {f['name']:<25} | {f['visibility']:<10} | {auth_str}\033[0m"
)
print("-" * 80 + "\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Generate Access Control Matrix from Solidity.",
)
parser.add_argument(
"file",
type=argparse.FileType("r", encoding="utf-8"),
help="The .sol file to analyze",
)
args = parser.parse_args()
try:
sanitize_cli_path(args.file.name, allowed_suffixes={".sol"})
except Exception as e:
print(f"[!] Error: {e}")
sys.exit(1)
data = parse_solidity_source(args.file.read())
generate_matrix_report(data)