-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnaf-ce.py
executable file
·243 lines (186 loc) · 5.91 KB
/
naf-ce.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
import logging
import socket, json, subprocess, os.path, sys
from functools import wraps
RULES_FILE = "/etc/naf/rules.json"
DEFAULT_ALLOW_RULE = "-P INPUT -s {ip}/32 ACCEPT"
logger = logging.getLogger("naf-ce")
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh = logging.FileHandler("/var/log/naf_ce.log")
fh.setFormatter(formatter)
sh = logging.StreamHandler()
logger.addHandler(fh)
logger.addHandler(sh)
logger.setLevel(logging.INFO)
"""
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <samuellopezsaura@gmail.com> wrote this file.
* As long as you retain this notice you can do whatever you want with this
* stuff. If we meet some day, and you think this stuff is worth it, you can
* buy me a beer in return. Samuel López Saura
* ----------------------------------------------------------------------------
*/
"""
print(
r"""
_ _ _ _____
| \ | | / \ | ___|
| \| | / _ \ | |_
| |\ |/ ___ \| _|
|_| \_/_/ \_\_|
Not Another Firewall - CE
Release 0.1
@elchicodepython
"""
)
def issafe(rule):
if "&" in rule or ";" in rule:
return False
return True
def just_boot():
try:
with open("/tmp/naf-ce", "r"):
return False
except IOError:
return True
def initialize():
with open("/tmp/naf-ce", "w") as f:
f.write("# Delete me if restart")
def list_iptables():
data = subprocess.check_output("/sbin/iptables -S", shell=True).decode()
return data.split("\n")
def delete_iptables_rule(rule):
subprocess.check_output(
"/sbin/iptables -D %s" % rule.replace("-A", ""), shell=True
)
logger.info("Rule [{}] deleted".format(rule))
def add_iptables_rule(rule):
subprocess.check_output("/sbin/iptables %s" % rule, shell=True)
logger.info("Rule [{}] added".format(rule))
def get_rules():
with open(RULES_FILE, "r") as file:
rules = json.loads(file.read())
return rules
def save_rules(rules):
with open(RULES_FILE, "w") as file:
file.write(json.dumps(rules))
def check_domains():
rules = get_rules()
current_iptables = list_iptables()
allow_rule = rules.get("allow_rule", DEFAULT_ALLOW_RULE)
for domain in rules.get("domains", []):
domain_name = domain.get("name", None)
if domain_name:
print(("Checking %s" % domain_name).format(80, "="))
ip_data = domain.get("ip")
try:
real_ip = socket.gethostbyname(domain_name)
except socket.gaierror:
logger.error("Error on name resolution for %s" % domain_name)
continue
if issafe(real_ip):
print("IP FOUND %s" % real_ip)
rule_ip_data = allow_rule.format(ip=ip_data)
rule_real_ip = allow_rule.format(ip=real_ip)
first_check = just_boot()
initialize()
if (rule_ip_data != rule_real_ip) or first_check:
logger.info(
"%s IP saved [%s] != real IP [%s]"
% (domain_name, ip_data, real_ip)
)
if rule_ip_data in current_iptables:
delete_iptables_rule(rule_ip_data)
if rule_real_ip not in current_iptables:
add_iptables_rule(rule_real_ip)
else:
print("Without changes")
domain["ip"] = real_ip
save_rules(rules)
def edit_rules():
action = ""
print(
"""Choose an option
1) Add a domain
2) Delete a domain
3) List configuration
4) Update rules
x) Exit"""
)
while action != "x":
action = input("> ")
if action == "1":
edit_rules_add_domain()
elif action == "2":
edit_rules_delete_domain()
elif action == "3":
list_rules()
elif action == "4":
check_domains()
elif action == "x":
return
def rules_context(f):
@wraps(f)
def foo(*args, **kwargs):
rules = get_rules()
o = f(rules, *args, **kwargs)
save_rules(rules)
return o
return foo
@rules_context
def edit_rules_add_domain(rules):
dom = input("[\033[1;32ma\033[0m] Domain: ")
rules["domains"].append({"name": dom, "ip": ""})
@rules_context
def edit_rules_delete_domain(rules):
founded = False
dom = input("[\033[1;31md\033[0m] Domain: ")
for idx, domain in enumerate(rules["domains"]):
if domain["name"] == dom:
founded = True
break
if founded:
print("[200] Deleted")
del rules["domains"][idx]
else:
print("[404] Not Found")
def list_rules():
rules = get_rules()
print(
"\033[1;32mALLOW RULE: %s\033[0m"
% rules.get("allow_rule", DEFAULT_ALLOW_RULE)
)
print("Domains:")
if rules["domains"]:
for domain in rules["domains"]:
print(
domain["name"].ljust(50)
+ (
domain["ip"]
or "[\033[1;31m404\033[0m] Run update to save"
)
)
else:
print("There are no domains registered yet")
def print_help():
print(
"""NAF-CE is based on a configuration file placed on /etc/naf/rules.json
\033[1;32mnaf-ce [update|edit|list]\033[0m
NAF-CE check the domain resolution for each domain and add or delete the defined "allow_rule" rule replacing the {ip} keyword with the resolution of the domain name
"""
)
if __name__ == "__main__":
if len(sys.argv) == 2:
if sys.argv[1] == "update":
check_domains()
elif sys.argv[1] == "edit":
edit_rules()
elif sys.argv[1] == "list":
list_rules()
else:
print_help()
else:
print_help()