-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlocaldns.py
executable file
·247 lines (208 loc) · 5.5 KB
/
localdns.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
#! /usr/bin/env python
import socket
import select
import gfw
import dns
import struct
import time
import pdb
import signal
import cStringIO
import os
import sys
import pwd
g = globals()
FOREIGN_SERVER = ("8.8.8.8", 53)
LOCAL_SERVER = ("114.114.114.114", 53)
SERVER = ("", 53)
LOG = "/tmp/localdns.log"
PID = "/tmp/localdns.pid"
USER = "nobody"
#2s
REQUEST_TIMEOUT = 2
#ident -> client
itable = {}
#local, foreign -> ident
has_epoll = False
if hasattr(select, "epoll"):
has_epoll = True
def set_globals():
g["myloc"] = os.path.join(os.getcwd(), __file__)
g["sock"] = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
g["sockfd"] = sock.fileno()
sock.bind(SERVER)
sock.settimeout(0)
if has_epoll:
g["p"] = select.epoll()
p.register(sockfd, select.EPOLLIN |select.EPOLLERR)
def cat_test(packet):
found = True
for i in packet["answer"]:
if not "addr" in i:
return False
if i["addr"] in gfw.CATS:
found = False
if not found:
return True
else:
return False
def get_ident2(ident):
if ident > 2:
return ident - 1, ident - 2
else:
return ident + 1, ident + 2
def print_query(query, client):
for k in query["question"]:
if "name" in k:
print "query name: ", k["name"], "from: %s" % (client[0])
def send_foreign(ident, payload):
if not ident in itable:
return
foreign_ctx = itable[ident]
#send foreign
sock.sendto(struct.pack(">H", foreign_ctx["ident"]) + payload,
foreign_ctx["client"])
del itable[ident]
#drop local
del itable[foreign_ctx["local"]]
def sent_local(ident, payload):
if not ident in itable:
return
local_ctx = itable[ident]
#send local
sock.sendto(struct.pack(">H", local_ctx["ident"]) + payload,
local_ctx["client"])
del itable[ident]
#drop foreign
del itable[local_ctx["foreign"]]
def send2(ident, payload, client):
i1, i2 = get_ident2(ident)
local = {
"foreign": i2,
"time": time.time(),
"client": client,
"ident": ident,
}
foreign = {
"local": i1,
"time": time.time(),
"client": client,
"ident": ident,
}
itable[i1] = local
itable[i2] = foreign
sock.sendto(struct.pack(">H", i1) + payload, LOCAL_SERVER)
sock.sendto(struct.pack(">H", i2) + payload, FOREIGN_SERVER)
def handle_pollin():
data, client = sock.recvfrom(4096)
if len(data) < 12:
#not a dns packet
return
b = cStringIO.StringIO(data)
unknown = False
try:
ret = dns.parse_stream(b)
except ValueError:
unknown = True
print "parse error, ignore"
finally:
b.close()
if unknown:
ident = struct.unpack(">H", data[:2])[0]
else:
ident = ret["ident"]
if cat_test(ret):
print "GFW: you shall not pass"
return
payload = data[2:]
if client == FOREIGN_SERVER:
send_foreign(ident, payload)
elif client == LOCAL_SERVER:
sent_local(ident, payload)
else:
if not unknown:
print_query(ret, client)
send2(ident, payload, client)
def wait_request_epoll(timeout):
for fd, event in p.poll(timeout):
if event & select.EPOLLIN:
try:
handle_pollin()
except IOError:
pass
if event & select.EPOLLERR:
raise Exception("Failed")
def wait_request_select(timeout):
r, _, e = select.select([sockfd], [], [sockfd], timeout)
if sockfd in r:
try:
handle_pollin()
except IOError:
pass
if sockfd in e:
raise Exception("Failed")
def bgrun():
log_file = open(LOG, "w+", buffering=False)
pid_file = open(PID, "w+", buffering=False)
try:
status = os.fork()
except OSError as e:
print e
if not status:
os.setsid()
sys.stdin = open("/dev/null", "r")
sys.stdout = log_file
sys.stderr = log_file
try:
status2 = os.fork()
except OSError as e:
print e
if status2:
pid_file.write(str(status2))
pid_file.close()
exit()
else:
exit()
def run_as_user(user):
try:
db = pwd.getpwnam(user)
except KeyError:
raise Exception("user doesn't exists")
try:
os.setgid(db.pw_gid)
except OSError:
raise Exception("change gid failed")
try:
os.setuid(db.pw_uid)
except OSError:
raise Exception("change uid failed")
def clients_gc():
now = time.time()
for k, v in itable.items():
if now - v["time"] > REQUEST_TIMEOUT:
del itable[k]
def sigusr1_reload(*args):
print "reload localdns"
os.execvp("python", ["python", myloc])
def main():
signal.signal(signal.SIGUSR1, sigusr1_reload)
wait_request = wait_request_select
if has_epoll:
wait_request = wait_request_epoll
set_globals()
bgrun()
run_as_user(USER)
end = 0
prev = time.time()
while True:
end = time.time()
try:
wait_request(2)
except:
pass
if end - prev > REQUEST_TIMEOUT:
clients_gc()
prev = time.time()
if __name__ == "__main__":
main()