forked from bieberg0n/bjdns
/
bjdns2.py
executable file
·180 lines (149 loc) · 4.39 KB
/
bjdns2.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
#!/usr/bin/env python3
import json
# from gevent import (
# monkey,
# ssl,
# )
# monkey.patch_all()
# from gevent.pywsgi import WSGIServer
import requests
from flask import (
Flask,
request,
)
from utils import (
log,
dlog,
resp_from_json,
is_private_ip,
# config,
)
from cache import Cache
import config
app = Flask(__name__)
def whitelist():
with open('whitelist.json') as f:
txt = f.read()
d = json.loads(txt)
return d
def make_resp(name, ip, ttl):
if not name.endswith('.'):
name += '.'
resp = {
"TC": False,
"RD": True,
"RA": True,
"AD": True,
"CD": False,
"Question": [
{
"name": name,
"type": 1
}
],
}
if ip:
resp['Status'] = 0
resp["Answer"] = [
{
"name": name,
"type": 1,
"TTL": ttl,
"data": ip
}
]
else:
resp['Status'] = 2
return resp
def is_cn_host(whitelist, host):
h = [part for part in reversed(host.split('.')) if part]
if h[0] == 'cn':
return True
elif len(h) > 1:
return whitelist.get(h[0], {}).get(h[1]) == 1
else:
return False
class Query:
def __init__(self, by_proxy):
self.cache = Cache()
self.wl = whitelist()
self.s_cn = requests.session()
self.s_proxy = requests.session()
if by_proxy:
self.s_proxy.proxies = {
'http': 'socks5h://127.0.0.1:1080',
'https': 'socks5h://127.0.0.1:1080'
}
def cn_query(self, cn_host, client_ip) -> map:
url_template = 'http://119.29.29.29/d?dn={}&ip={}'
if is_private_ip(client_ip):
url = url_template.format(cn_host, '')
else:
url = url_template.format(cn_host, client_ip)
r = self.s_cn.get(url)
result = r.text.split(';')[0]
ip = result if result else ''
ttl = 3600
return make_resp(cn_host, ip, ttl)
def foreign_query(self, name, dns_type) -> map:
try:
url = 'https://1.1.1.1/dns-query?ct=application/dns-json&name={}&type={}'
r = self.s_proxy.get(url.format(name, dns_type), timeout=2)
except Exception as e:
log(e)
url = 'https://8.8.8.8/resolve?name={}&type={}'
r = self.s_proxy.get(url.format(name, dns_type), verify=False)
finally:
return json.loads(r.text)
def query(self, question: map, src_ip: str) -> map:
name, dns_type = question['name'], question['type']
if is_cn_host(self.wl, name):
cn_flag = True
else:
cn_flag = False
src_ip = '0.0.0.0'
resp = self.cache.select(src_ip, question)
if not resp:
if cn_flag and dns_type in (1, '1', 'A'):
resp = self.cn_query(name, src_ip)
else:
resp = self.foreign_query(name, dns_type)
if resp['Status'] == 0:
dlog('src ip:', src_ip, 'resp:', resp)
self.cache.write(src_ip, question, resp, b'')
cache_flag = ''
else:
cache_flag = '[Cache] '
return resp, cache_flag
class Bjdns:
def __init__(self, by_proxy):
self.query = Query(by_proxy)
def bjdns(self, question: map, src_ip: str) -> map:
name, dns_type = question['name'], question['type']
resp, cache_flag = self.query.query(question, src_ip)
if resp['Status'] == 0:
data, ttl = resp_from_json(resp)
log('{0} {1} {2}{3} (ttl: {4})'.format(src_ip, name, cache_flag, data, ttl))
else:
log('{} {}'.format(src_ip, name))
return resp
@app.route('/', methods=['GET'])
def index():
host = request.args.get('dn')
cli_ip = request.args.get('ip')
dns_type = int(request.args.get('type', 1))
if host:
cli_ip = cli_ip if cli_ip else request.remote_addr.split(':')[-1]
question = dict(name=host, type=dns_type)
# try:
resp = bjdns.bjdns(question, cli_ip)
# except Exception as e:
# log(e)
# resp = make_resp('', '', 0)
# finally:
return json.dumps(resp).encode()
else:
return 'BJDNS'
bjdns = Bjdns(config.by_proxy)
if __name__ == '__main__':
app.run(debug=True)