-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
97 lines (73 loc) · 1.96 KB
/
Copy pathparser.py
File metadata and controls
97 lines (73 loc) · 1.96 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
from lark import Lark, Transformer
grammar = r"""
start: statement+
?statement: role_def
| network_def
| service_def
| vpn_def
| rule
role_def: "role" NAME
network_def: "network" NAME CIDR
service_def: "service" NAME PROTOCOL PORT
vpn_def: "vpn" NAME CIDR
rule: ACTION NAME "->" NAME "service" NAME
ACTION: "allow" | "deny"
PROTOCOL: "tcp" | "udp" | "ip"
NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
CIDR: /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+/
PORT: /[0-9]+/
%import common.WS
%ignore WS
"""
parser = Lark(grammar, parser="lalr")
class PolicyTransformer(Transformer):
def start(self, items):
return items
def role_def(self, items):
return {
"type": "role",
"name": str(items[0])
}
def network_def(self, items):
return {
"type": "network",
"name": str(items[0]),
"cidr": str(items[1])
}
def service_def(self, items):
return {
"type": "service",
"name": str(items[0]).upper(),
"protocol": str(items[1]),
"port": int(items[2])
}
def vpn_def(self, items):
return {
"type": "vpn",
"name": str(items[0]),
"cidr": str(items[1])
}
def rule(self, items):
return {
"type": "rule",
"action": str(items[0]),
"src": str(items[1]),
"dst": str(items[2]),
"service": str(items[3]).upper()
}
def clean_policy(text):
cleaned = []
for line in text.splitlines():
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
if "#" in line:
line = line.split("#", 1)[0].strip()
cleaned.append(line)
return "\n".join(cleaned)
def parse_policy(text):
text = clean_policy(text)
tree = parser.parse(text)
return PolicyTransformer().transform(tree)