This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 262
/
auto_block.py
293 lines (246 loc) · 9.86 KB
/
auto_block.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import fcntl
import logging
import os
import platform
import socket
import configloader
from shadowsocks import common
class AutoBlock(object):
def __init__(self):
from multiprocessing import Event
self.event = Event()
self.start_line = self.file_len("/etc/hosts.deny")
self.has_stopped = False
def get_ip(self, text):
if common.match_ipv4_address(text) is not None:
return common.match_ipv4_address(text)
else:
if common.match_ipv6_address(text) is not None:
return common.match_ipv6_address(text)
return None
def file_len(self, fname):
return sum(1 for line in open(fname))
def auto_block_thread(self):
global webapi
server_ip = socket.gethostbyname(configloader.get_config().MYSQL_HOST)
if configloader.get_config().API_INTERFACE == "modwebapi":
# 读取节点IP
node_ip_list = []
data = webapi.getApi("nodes")
for node in data:
temp_list = node["node_ip"].split(",")
node_ip_list.append(temp_list[0])
deny_file = open("/etc/hosts.deny")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
deny_lines = deny_file.readlines()
deny_file.close()
logging.info("Read hosts.deny from line " + str(self.start_line))
real_deny_list = deny_lines[self.start_line:]
denyed_ip_list = []
data = []
for line in real_deny_list:
if self.get_ip(line) and line.find("#") != 0:
ip = self.get_ip(line)
if str(ip).find(str(server_ip)) != -1:
i = 0
for line in deny_lines:
if line.find(ip) != -1:
del deny_lines[i]
i = i + 1
deny_file = open("/etc/hosts.deny", "w+")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
for line in deny_lines:
deny_file.write(line)
deny_file.close()
continue
has_match_node = False
for node_ip in node_ip_list:
if str(ip).find(node_ip) != -1:
i = 0
for line in deny_lines:
if line.find(ip) != -1:
del deny_lines[i]
i = i + 1
deny_file = open("/etc/hosts.deny", "w+")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
for line in deny_lines:
deny_file.write(line)
deny_file.close()
has_match_node = True
continue
if has_match_node:
continue
if configloader.get_config().API_INTERFACE == "modwebapi":
data.append({"ip": ip})
logging.info("Block ip:" + str(ip))
else:
cur = conn.cursor()
cur.execute(
"SELECT * FROM `blockip` where `ip` = '"
+ str(ip)
+ "'"
)
rows = cur.fetchone()
cur.close()
if rows is not None:
continue
cur = conn.cursor()
cur.execute(
"INSERT INTO `blockip` (`id`, `nodeid`, `ip`, `datetime`) VALUES (NULL, '"
+ str(configloader.get_config().NODE_ID)
+ "', '"
+ str(ip)
+ "', unix_timestamp())"
)
cur.close()
logging.info("Block ip:" + str(ip))
denyed_ip_list.append(ip)
if configloader.get_config().API_INTERFACE == "modwebapi":
webapi.postApi(
"func/block_ip",
{"node_id": configloader.get_config().NODE_ID},
{"data": data},
)
if configloader.get_config().API_INTERFACE == "modwebapi":
rows = webapi.getApi("func/block_ip")
else:
cur = conn.cursor()
cur.execute(
"SELECT * FROM `blockip` where `datetime`>unix_timestamp()-60"
)
rows = cur.fetchall()
cur.close()
deny_str = ""
deny_str_at = ""
for row in rows:
if configloader.get_config().API_INTERFACE == "modwebapi":
node = row["nodeid"]
ip = self.get_ip(row["ip"])
else:
node = row[1]
ip = self.get_ip(row[2])
if ip is not None:
if str(node) == str(configloader.get_config().NODE_ID):
if (
configloader.get_config().ANTISSATTACK == 1
and configloader.get_config().CLOUDSAFE == 1
and ip not in denyed_ip_list
):
if common.is_ip(ip):
if common.is_ip(ip) == socket.AF_INET:
os.system(
"route add -host %s gw 127.0.0.1" % str(ip)
)
deny_str = deny_str + "\nALL: " + str(ip)
else:
os.system(
"ip -6 route add ::1/128 via %s/128"
% str(ip)
)
deny_str = (
deny_str + "\nALL: [" + str(ip) + "]/128"
)
logging.info("Remote Block ip:" + str(ip))
else:
if common.is_ip(ip):
if common.is_ip(ip) == socket.AF_INET:
os.system(
"route add -host %s gw 127.0.0.1" % str(ip)
)
deny_str = deny_str + "\nALL: " + str(ip)
else:
os.system(
"ip -6 route add ::1/128 via %s/128" % str(ip)
)
deny_str = (
deny_str + "\nALL: [" + str(ip) + "]/128"
)
logging.info("Remote Block ip:" + str(ip))
deny_file = open("/etc/hosts.deny", "a")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
deny_file.write(deny_str)
deny_file.close()
if (
configloader.get_config().ANTISSATTACK == 1
and configloader.get_config().CLOUDSAFE == 1
):
deny_file = open("/etc/hosts.deny", "a")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
deny_file.write(deny_str_at)
deny_file.close()
if configloader.get_config().API_INTERFACE == "modwebapi":
rows = webapi.getApi("func/unblock_ip")
else:
cur = conn.cursor()
cur.execute(
"SELECT * FROM `unblockip` where `datetime`>unix_timestamp()-60"
)
rows = cur.fetchall()
cur.close()
conn.close()
deny_file = open("/etc/hosts.deny")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
deny_lines = deny_file.readlines()
deny_file.close()
i = 0
for line in deny_lines:
for row in rows:
if configloader.get_config().API_INTERFACE == "modwebapi":
ip = str(row["ip"])
else:
ip = str(row[1])
if line.find(ip) != -1:
del deny_lines[i]
if common.is_ip(ip):
if common.is_ip(ip) == socket.AF_INET:
os.system(
"route del -host %s gw 127.0.0.1" % str(ip)
)
else:
os.system(
"ip -6 route del ::1/128 via %s/128" % str(ip)
)
logging.info("Unblock ip:" + str(ip))
i = i + 1
deny_file = open("/etc/hosts.deny", "w+")
fcntl.flock(deny_file.fileno(), fcntl.LOCK_EX)
for line in deny_lines:
deny_file.write(line)
deny_file.close()
self.start_line = self.file_len("/etc/hosts.deny")
@staticmethod
def thread_db(obj):
if (
configloader.get_config().CLOUDSAFE == 0
or platform.system() != "Linux"
):
return
if configloader.get_config().API_INTERFACE == "modwebapi":
import webapi_utils
global webapi
webapi = webapi_utils.WebApi()
global db_instance
db_instance = obj()
try:
while True:
try:
db_instance.auto_block_thread()
except Exception as e:
import traceback
trace = traceback.format_exc()
logging.error(trace)
# logging.warn('db thread except:%s' % e)
if db_instance.event.wait(60):
break
if db_instance.has_stopped:
break
except KeyboardInterrupt as e:
pass
db_instance = None
@staticmethod
def thread_db_stop():
global db_instance
db_instance.has_stopped = True
db_instance.event.set()