-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.py
288 lines (258 loc) · 9.59 KB
/
request.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
import copy
import hashlib
import os
import ssl
import time
import urllib.request
import http.cookiejar
import pyotp
from config import *
user_agent = "CorpLink/20500 (GooglePixel; Android 10; en)"
url_params = {
"os": "Android",
"os_version": "2",
"app_version": "2.0.5",
"brand": "Google",
"model": "Pixel",
"language": "en",
"build_number": "2021051719",
}
_url_params = []
for k, v in url_params.items():
_url_params.append(f"{k}={v}")
url_postfix = "?" + "&".join(_url_params)
get_login_method_url = f"https://%s/api/lookup{url_postfix}"
send_code_url = f"https://%s/api/login/code/send{url_postfix}"
verify_url = f"https://%s/api/login/code/verify{url_postfix}"
login_url = f"https://%s/api/login{url_postfix}"
list_vpn_url = f"https://%s/api/vpn/list{url_postfix}"
fa2_url = f"https://%s/api/mfa/code/verify{url_postfix}"
ping_url = f"https://%s:%d/vpn/ping{url_postfix}"
conn_url = f"https://%s:%d/vpn/conn{url_postfix}"
keep_alive_url = f"https://%s:%d/vpn/report{url_postfix}"
def build_cookie(domain, name, value) -> http.cookiejar.Cookie:
t = int(time.time()) + 3600 * 24 * 30
return http.cookiejar.Cookie(
version=0,
name=name, value=value,
port=None, port_specified=False,
domain=domain, domain_specified=False, domain_initial_dot=False,
path="/", path_specified=False,
secure=False,
expires=t,
discard=False,
comment=None,
comment_url=None,
rest={}
)
class Client:
def __init__(self, server: str, device_id, device_name, conf_path="."):
self._cookiejar = None
self._server = server
self._domain = server.split(":")[0]
self._api_opener = self._build_opener(os.path.join(conf_path, "cookie.txt"), device_id, device_name, True)
self._vpn_opener = self._build_opener(os.path.join(conf_path, "cookie.txt"), device_id, device_name)
def _ok(self, resp) -> bool:
return resp["code"] == 0
def no_verify_ctx(self):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
def _build_opener(self, cookie_path, device_id, device_name,
load_csrf_token=False) -> urllib.request.OpenerDirector:
if self._cookiejar is None:
self._cookiejar = http.cookiejar.MozillaCookieJar(cookie_path)
try:
self._cookiejar.load()
except FileNotFoundError:
pass
except Exception as e:
raise e
if len(self._cookiejar) == 0:
self._cookiejar.set_cookie(build_cookie(self._domain, "device_id", device_id))
self._cookiejar.set_cookie(build_cookie(self._domain, "device_name", device_name))
handlers = []
ctx = self.no_verify_ctx()
handlers.append(urllib.request.HTTPSHandler(context=ctx))
# for mitm debug
# handlers.append(urllib.request.ProxyHandler({"https": "http://192.168.1.233:8001/"}))
handlers.append(urllib.request.HTTPCookieProcessor(self._cookiejar))
opener = urllib.request.build_opener(*handlers)
opener.addheaders.clear()
opener.addheaders.append(("User-Agent", user_agent))
csrf_token = self._find_in_cookie("csrf-token")
if load_csrf_token and len(csrf_token) != 0:
opener.addheaders.append(("Csrf-Token", csrf_token))
return opener
def _open(self, url: str, data: typing.Optional[typing.Dict]):
if "%s" in url:
url = url % (self._server,)
if data is None:
req = urllib.request.Request(url)
else:
data = json.dumps(data).encode()
req = urllib.request.Request(url, data, headers={"Content-Type": "application/json"})
if self._server in url:
resp = self._api_opener.open(req).read()
self._cookiejar.save()
return json.loads(resp)
else:
resp = self._vpn_opener.open(req).read()
return json.loads(resp)
def get_login_method(self, username) -> [str]:
data = {
"forget_password": False,
"platform": "",
"user_name": username
}
resp = self._open(get_login_method_url, data)
if not self._ok(resp):
return []
return resp["data"]["auth"]
def request_email_verify_code(self, username):
data = {
"code_type": "email",
"forget_password": False,
"platform": "",
"user_name": username
}
resp = self._open(send_code_url, data)
if not self._ok(resp):
print(f"Failed to request email code: {resp}")
return False
print("code has been sent to your email")
def _login_internal(self, url, data) -> typing.Optional[pyotp.TOTP]:
resp = self._open(url, data)
if not self._ok(resp):
print(f"Failed to login: {resp}")
return None
csrf_token = self._find_in_cookie("csrf-token")
if len(csrf_token) != 0:
self._api_opener.addheaders.append(("Csrf-Token", csrf_token))
url = resp["data"]["url"]
otp = pyotp.parse_uri(url)
if isinstance(otp, pyotp.TOTP):
return otp
class_name = otp.__class__.__name__
print(f"{class_name} not support yet")
return None
def login_with_code(self, code) -> typing.Optional[pyotp.TOTP]:
data = {
"code": code,
"code_type": "email",
"forget_password": False,
}
return self._login_internal(verify_url, data)
def login_with_password(self, username: str, password: str) -> typing.Optional[pyotp.TOTP]:
sh = hashlib.sha256(password.encode())
data = {
"user_name": username,
"password": sh.hexdigest(),
"forget_password": False,
}
return self._login_internal(login_url, data)
def verify(self, code) -> bool:
data = {
"action": "vpn",
"code": code,
"code_type": "otp"
}
resp = self._open(fa2_url, data)
if not self._ok(resp):
print(f"Failed to verify 2fa: {resp}")
return False
return True
def list_vpn(self) -> typing.Optional[list]:
resp = self._open(list_vpn_url, None)
if not self._ok(resp):
print(f"Failed to list vpn: {resp}")
if resp["code"] == 101:
return None
return []
"""
{
"api_port": 8001,
"en_name": "CN",
"icon": "123",
"id": 1,
"ip": "1.2.3.4",
"name": "中国",
"protocol_mode": 2,
"timeout": 5,
"vpn_port": 8002
}
"""
vpn_list = []
for item in resp["data"]:
vpn_list.append({
"ip": item["ip"],
"api_port": item["api_port"],
"vpn_port": item["vpn_port"]
})
return vpn_list
def ping_vpn(self, ip, port) -> bool:
resp = self._open(ping_url % (ip, port), None)
if not self._ok(resp):
print(f"Failed to ping {ip}:{port}: {resp}")
return False
cookies = self._cookiejar._cookies
for k, v in cookies.items():
if k != self._domain:
continue
v = copy.deepcopy(v)
for cs in v.values():
for k in cs:
cs[k].domain = ip
cookies[ip] = v
break
self._cookiejar.save()
return True
def _find_in_cookie(self, key) -> str:
for v in self._cookiejar._cookies.values():
for cs in v.values():
for k, v in cs.items():
if k == key:
return v.value
return ""
def _cookie_to_str(self, cookiejar) -> str:
cookies = []
for v in cookiejar._cookies.values():
for cs in v.values():
for k, v in cs.items():
cookies.append(f"{k}={v.value}")
cookie = "; ".join(cookies)
return cookie
def fetch_peer_info(self, ip, port, your_key, otp) -> dict:
data = {"public_key": your_key, "otp": otp}
resp = self._open(conn_url % (ip, port), data)
if not self._ok(resp):
if resp["code"] == 3002:
print(resp["message"])
return {"2-fa": None}
else:
print(f"failed to get vpn info: {resp}")
return {}
return resp["data"]
def report_vpn_status(self, ip, port, wg_ip, public_key):
data = {
"ip": wg_ip,
"mode": "Split",
"public_key": public_key,
"type": "100"
}
resp = self._open(keep_alive_url % (ip, port), data)
if not self._ok(resp):
print(f"failed to report vpn status: {resp}")
return {}
def disconnect_vpn(self, ip, port, wg_ip, public_key):
data = {
"ip": wg_ip,
"mode": "Split",
"public_key": public_key,
"type": "101"
}
resp = self._open(keep_alive_url % (ip, port), data)
if not self._ok(resp):
print(f"failed to disconnect vpn: {resp}")
return {}