-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.py
More file actions
executable file
·198 lines (166 loc) · 6.02 KB
/
proxy.py
File metadata and controls
executable file
·198 lines (166 loc) · 6.02 KB
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
#!/usr/bin/python3
"""Minimalistic HTTP proxy for the DCS WebGUI that decrypts and logs requests.
Additionally, it loads and updates a JSON file with all new request
types that the proxy encounters."""
import asyncio
import base64
import hashlib
import json
import os
import aes
class WebGuiProxy:
# set of URIs that the WebGUI issues periodically
PERIODIC_URIS: set[str] = {
"getMissionInfo",
"getMissionList",
"getPauseState",
"getPlayers",
"getServerUptime",
"getSimulatorMode",
"updateChat",
"updateLog",
}
def __init__(
self,
connect_port: int = 8088,
listen_port: int = 8089,
verbose: bool = False,
# WebGUI/js/app.js: r'\bwebKey:"DigitalCombatSimulator.com"\b'
webgui_key: bytes = b"DigitalCombatSimulator.com",
):
self._connect_port: int = connect_port
self._listen_port: int = listen_port
self._verbose: bool = verbose
self._aes = aes.AES(hashlib.sha256(webgui_key).digest())
def __enter__(self):
try:
with open("webgui_uris.json", "rt") as fh:
self._webgui_uris = json.load(fh)
except FileNotFoundError:
self._webgui_uris = {}
return self
def __exit__(self, exc_type, exc_value, traceback):
with open("webgui_uris.json", "wt") as fh:
json.dump(dict(sorted(self._webgui_uris.items())), fh, indent="\t")
async def _http_recv(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
):
# read and parse HTTP request line and headers
# https://en.wikipedia.org/wiki/HTTP#HTTP/1.1_request_messages
header = await reader.readuntil(b"\r\n\r\n")
header = header.decode("ascii").removesuffix("\r\n\r\n").split("\r\n")
start = header[0]
# split headers into dictionary
fields: dict[str, str] = dict(line.split(": ", 1) for line in header[1:])
if "Content-Length" in fields:
body = await reader.readexactly(int(fields["Content-Length"]))
else:
body = b""
return start, fields, body
async def _http_send(
self,
writer: asyncio.StreamWriter,
start: str,
fields: dict[str, str],
body: bytes,
):
# assemble header
header = bytearray(start.encode("ascii"))
header += b"\r\n"
for key, value in fields.items():
header += f"{key}: {value}\r\n".encode("ascii")
header += b"\r\n"
# send header and body
writer.write(header + body)
await writer.drain()
async def _http_proxy(
self, cl_rd: asyncio.StreamReader, cl_wr: asyncio.StreamWriter
):
# connect to WebGUI server while we process the client request
task_connect = asyncio.create_task(
asyncio.open_connection("127.0.0.1", self._connect_port)
)
# receive client request
request, headers, body_req = await self._http_recv(cl_rd, cl_wr)
# wait for connection to WebGUI server
srv_rd, srv_wr = await task_connect
# forwards client request to WebGUI server (with modified headers)
headers["Connection"] = "close"
try:
del headers["Host"]
except KeyError:
pass
await self._http_send(srv_wr, request, headers, body_req)
# receive server response
status, headers, body_resp = await self._http_recv(srv_rd, srv_wr)
# print(status, headers, body_resp)
# forward WebGUI response to client (with modified headers)
headers["Connection"] = "close"
await self._http_send(cl_wr, status, headers, body_resp)
# close all sockets
cl_wr.close()
srv_wr.close()
await asyncio.gather(cl_wr.wait_closed(), srv_wr.wait_closed())
# ignore other requests
if not request.startswith("POST /encryptedRequest HTTP/1."):
return
# decrypt
json_req = json.loads(body_req.decode("ascii"))
req_ct = base64.b64decode(json_req["ct"])
req_iv = base64.b64decode(json_req["iv"])
req_pt = self._aes.decrypt_cbc(req_ct, req_iv)
req = json.loads(req_pt.decode())
uri = req["uri"]
json_resp = json.loads(body_resp.decode("ascii"))
resp_ct = base64.b64decode(json_resp["ct"])
resp_iv = base64.b64decode(json_resp["iv"])
resp_pt = self._aes.decrypt_cbc(resp_ct, resp_iv)
resp = json.loads(resp_pt.decode())
example = {"request": req, "response": resp}
if self._verbose or uri not in self.PERIODIC_URIS:
print({f"{uri}": {"examples": [example]}})
# add example to dictionary of commands
if uri not in self._webgui_uris:
self._webgui_uris[uri] = {"examples": [example]}
async def serve(self):
server = await asyncio.start_server(
self._http_proxy,
"127.0.0.1",
self._listen_port,
reuse_port=True if os.name == "posix" else False,
)
async with server:
try:
await server.serve_forever()
except (asyncio.CancelledError, KeyboardInterrupt):
pass
if __name__ == "__main__":
import argparse
# parse CLI arguments
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--verbose",
action="store_const",
const=True,
default=False,
help="Also print periodic WebGUI requests (will flood output)",
)
parser.add_argument(
"webgui_port",
nargs="?",
type=int,
default=8088,
help="WebGUI port that HTTP proxy connects to",
)
parser.add_argument(
"listen_port",
nargs="?",
type=int,
default=8089,
help="Listen port of HTTP proxy",
)
args = parser.parse_args()
with WebGuiProxy(args.webgui_port, args.listen_port, args.verbose) as proxy:
asyncio.run(proxy.serve())