-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.py
375 lines (299 loc) · 11.1 KB
/
main.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""
DH-P2P + PTCP Implementation
"""
import argparse
import datetime
import random
import select
import socket
import subprocess
import sys
from urllib.parse import quote
from helpers import (
MAIN_PORT,
MAIN_SERVER,
UDP,
PTCPPayload,
get_auth,
get_dec,
get_enc,
get_key,
get_nonce,
)
def main(serial, dtype=0, username=None, password=None, debug=False):
socketserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketserver.bind(("0.0.0.0", 554))
socketserver.listen(5)
print("Listening on port 554")
if debug:
subprocess.Popen(
[
"ffplay",
"-rtsp_transport",
"tcp",
"-i",
f"rtsp://{username}:{quote(password)}@127.0.0.1/cam/realmonitor?channel=6&subtype=0",
]
)
main_remote = UDP(MAIN_SERVER, MAIN_PORT, debug)
res = main_remote.request("/probe/p2psrv")
res = main_remote.request(f"/online/p2psrv/{serial}")
p2psrv_server, p2psrv_port = res["data"]["body"]["US"].split(":")
p2psrv_port = int(p2psrv_port)
p2psrv_remote = UDP(p2psrv_server, p2psrv_port, debug)
res = p2psrv_remote.request(f"/probe/device/{serial}")
p2psrv_remote.close()
res = main_remote.request("/online/relay")
relay_server, relay_port = res["data"]["body"]["Address"].split(":")
relay_port = int(relay_port)
device_remote = UDP(MAIN_SERVER, MAIN_PORT, debug)
laddr = f"127.0.0.1:{device_remote.lport}"
ipaddr = f"<IpEncrpt>true</IpEncrpt><LocalAddr>{laddr}</LocalAddr>"
auth = ""
aid = random.randbytes(8)
if dtype > 0:
key = get_key(username, password)
nonce = get_nonce()
laddr = get_enc(key, nonce, laddr)
ipaddr = f"<IpEncrptV2>true</IpEncrptV2><LocalAddr>{laddr}</LocalAddr>"
auth = "" if dtype == 0 else get_auth(username, key, nonce, laddr)
res = device_remote.request(
f"/device/{serial}/p2p-channel",
f"<body>{auth}<Identify>{' '.join(f'{b:x}' for b in aid)}</Identify>{ipaddr}<version>5.0.0</version></body>",
should_read=False,
)
main_remote.rhost = relay_server
main_remote.rport = relay_port
res = main_remote.request("/relay/agent")
token = res["data"]["body"]["Token"]
agent_server, agent_port = res["data"]["body"]["Agent"].split(":")
agent_port = int(agent_port)
main_remote.rhost = agent_server
main_remote.rport = agent_port
res = main_remote.request(
f"/relay/start/{token}",
"<body><Client>:0</Client></body>",
)
res = device_remote.read(return_error=True)
if res["code"] < 200:
res = device_remote.read(return_error=True)
if res["code"] >= 400:
print("Error:", res["status"])
if dtype == 0 and res["code"] == 403:
print("Device requires authentication when creating P2P channel.")
print("Try again with:")
print(
f"main.py --type 1 --username <username> --password <password> {serial}"
)
sys.exit(1)
device_laddr = res["data"]["body"]["LocalAddr"]
if dtype > 0:
nonce = res["data"]["body"]["Nonce"]
device_laddr = get_dec(key, nonce, device_laddr)
device_server, device_port = res["data"]["body"]["PubAddr"].split(":")
device_port = int(device_port)
device_remote.rhost = device_server
device_remote.rport = device_port
main_remote.rhost = MAIN_SERVER
main_remote.rport = MAIN_PORT
if dtype > 0:
auth = get_auth(username, key, nonce)
res = main_remote.request(
f"/device/{serial}/relay-channel",
f"<body>{auth}<agentAddr>{agent_server}:{agent_port}</agentAddr></body>",
should_read=False,
)
main_remote.rhost = agent_server
main_remote.rport = agent_port
# TODO check timeout
res = main_remote.read()
main_remote.request_ptcp(b"\x00\x03\x01\x00")
res = main_remote.read_ptcp()
main_remote.request_ptcp(b"\x17\x00\x00\x00" + b"\x00\x00\x00\x00\x00\x00\x00\x00")
res = main_remote.read_ptcp()
while len(res.body) == 0:
res = main_remote.read_ptcp()
sign = res.body[12:]
main_remote.request_ptcp()
device_remote.rhost = device_server
device_remote.rport = device_port
aid = bytes(0xFF - b for b in aid)
cookie = random.randbytes(4)
trasn_id = random.randbytes(12)
eaddr = device_port.to_bytes(2) + socket.inet_aton(device_server)
eaddr = bytes(0xFF - b for b in eaddr)
data = (
b"\xff\xfe\xff\xe7"
+ cookie
+ trasn_id
+ b"\x7f\xd5\xff\xf7"
+ aid
+ b"\xff\xfb\xff\xf7\xff\xfe"
+ eaddr
)
print(f":{device_remote.lport} >>> {device_remote.rhost}:{device_remote.rport}")
print("".join(f"\\x{b:02X}" for b in data))
device_remote.send(data)
try:
data = device_remote.recv(timeout=5)
except socket.timeout:
print("Timeout occurred while waiting for a response from the device.")
print("If the issue persists, you may need to use relay mode with this device.")
print("Note: Relay mode is currently not implemented for Python.")
sys.exit(1)
print("Data <<<")
print("".join(f"\\x{b:02X}" for b in data))
rtrans_id = data[8:20]
ip, port = device_laddr.split(":")
port = int(port)
eaddr = port.to_bytes(2) + socket.inet_aton(ip)
data = (
b"\xfe\xfe\xff\xe7"
+ cookie
+ rtrans_id
+ b"\x7f\xd6\xff\xf7"
+ aid
+ b"\xff\xfb\xff\xf7\xff\xfe"
+ eaddr
)
print("Request >>>")
print("".join(f"\\x{b:02X}" for b in data))
device_remote.send(data)
if dtype > 0:
data = device_remote.recv()
print("Data <<<")
print("".join(f"\\x{b:02X}" for b in data))
data = (
b"\xfe\xfe\xff\xf3"
+ cookie
+ rtrans_id
+ b"\x7f\xd6\xff\xf7"
+ aid
+ b"\xff\xfb\xff\xf7\xff\xfe"
+ b"\xa8\x13\x3f\x57\xfe\x37"
)
for _ in range(5):
print("Request >>>")
print("".join(f"\\x{b:02X}" for b in data))
device_remote.send(data)
for _ in range(5):
data = device_remote.recv()
print("Data <<<")
print("".join(f"\\x{b:02X}" for b in data))
device_remote.request_ptcp(b"\x00\x03\x01\x00")
res = device_remote.read_ptcp()
assert res.body == b"\x00\x03\x01\x00"
device_remote.request_ptcp(
b"\x19\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + sign
)
res = device_remote.read_ptcp()
if len(res.body) == 0:
res = device_remote.read_ptcp()
assert res.body[0] == 0x1A
device_remote.request_ptcp(
b"\x1b\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00"
)
res = device_remote.read_ptcp()
assert len(res.body) == 0
print("Ready to connect")
print("Test with: rtsp://127.0.0.1/cam/realmonitor?channel=1&subtype=0")
while True:
ready, _, _ = select.select([socketserver], [], [], 0.1)
if not ready:
ptcp_ready, _, _ = select.select([device_remote], [], [], 0)
if not ptcp_ready:
continue
# only simplex, duplex is not supported
res = device_remote.read_ptcp()
if len(res.body) == 0:
continue
assert res.body[0] == 0x13
device_remote.request_ptcp()
continue
socketclient, address = socketserver.accept()
print(f"Connection from {address}")
realm_id = random.randint(0x00000000, 0xFFFFFFFF)
device_remote.request_ptcp(
b"\x11\x00\x00\x00"
+ realm_id.to_bytes(4, "big")
+ b"\x00\x00\x00\x00"
# port 554
+ b"\x00\x00\x02\x2A"
+ b"\x7f\x00\x00\x01",
)
res = device_remote.read_ptcp()
if len(res.body) == 0:
res = device_remote.read_ptcp()
assert res.body[0] == 0x12
try:
while True:
ptcp_ready, _, _ = select.select([device_remote], [], [], 0.1)
# if ptcp_ready:
while ptcp_ready:
res = device_remote.read_ptcp()
if len(res.body) == 0:
continue
device_remote.request_ptcp()
if res.body[0] != 0x10:
continue
body = PTCPPayload.parse(res.body)
if debug:
print()
print(body)
print(f"[{datetime.datetime.now().isoformat()}]")
print("Data <<<")
print(body.payload)
print()
socketclient.send(body.payload)
ptcp_ready, _, _ = select.select([device_remote], [], [], 0.1)
client_ready, _, _ = select.select([socketclient], [], [], 0)
if not client_ready:
continue
data = socketclient.recv(4096)
if not data:
print("Connection closed?")
break
if debug:
print()
print(f"[{datetime.datetime.now().isoformat()}]")
print("Data >>>")
print(data)
print()
device_remote.request_ptcp(bytes(PTCPPayload(realm_id, data)))
# handle connection reset by peer
except ConnectionResetError:
print("Connection reset by peer")
except BrokenPipeError:
print("Broken pipe")
finally:
print("Cleaning up connection")
device_remote.request_ptcp(
b"\x12\x00\x00\x00"
+ realm_id.to_bytes(4, "big")
+ b"\x00\x00\x00\x00"
+ b"DISC"
)
res = device_remote.read_ptcp()
while len(res.body) == 0 or res.body[0] == 0x10:
if len(res.body) > 0:
device_remote.request_ptcp()
res = device_remote.read_ptcp()
assert res.body[0] == 0x12
device_remote.request_ptcp()
socketclient.close()
print("Connection closed")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("serial", help="Serial number of the camera")
parser.add_argument("-d", "--debug", action="store_true", help="Enable debug mode")
parser.add_argument("-t", "--type", type=int, help="Type of the camera", default=0)
parser.add_argument("-u", "--username", help="Username of the camera")
parser.add_argument("-p", "--password", help="Password of the camera")
args = parser.parse_args()
if args.username is None or args.password is None:
if args.type > 0:
parser.error("Username and password are required for type > 0")
elif args.debug:
parser.error("Username and password are required in debug mode")
if args.serial:
main(args.serial, args.type, args.username, args.password, args.debug)