-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathnet.py
2270 lines (1914 loc) · 85.7 KB
/
net.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import ndjson
import copy
import inspect
import _thread
from utils import *
from pwdmanager import PwdManager
from relay import init_relay, DahuaHttp
def dahua_proto(proto):
""" DVRIP have different codes in their protocols """
headers = [
b'\xa0\x00', # 3DES Login
b'\xa0\x01', # DVRIP Send Request Realm
b'\xa0\x05', # DVRIP login Send Login Details
b'\xb0\x00', # DVRIP Receive
b'\xb0\x01', # DVRIP Receive
b'\xa3\x01', # DVRIP Discover Request
b'\xb3\x00', # DVRIP Discover Response
b'\xf6\x00', # DVRIP JSON
]
if proto[:2] in headers:
return True
return False
class Network(object):
def __init__(self):
super(Network, self).__init__()
self.args = None
""" If we don't have own udp server running in main app, will be False and we do not send anything """
self.tcp_server = None
self.console_attach = None
self.DeviceClass = None
self.DeviceType = None
self.AuthCode = None
self.ErrorCode = None
# Internal sharing
self.ID = 0 # Our Request / Response ID that must be in all requests and initiated by us
self.SessionID = 0 # Session ID will be returned after successful login
self.header = None
self.instance_serviceDB = {} # Store of Object, ProcID, SID, etc.. for 'service'
self.multicall_query_args = [] # Used with system.multicall method
self.multicall_query = [] # Used with system.multicall method
self.multicall_return_check = None # Used with system.multicall method
self.fuzzDB = {} # Used when fuzzing some calls
self.RestoreEventHandler = {} # Cache of temporary enabled events
self.params_tmp = {} # Used in instance_create()
self.attachParamsTMP = [] # Used in instance_create()
self.RemoteServicesCache = {} # Cache of remote services, used to check if certain service exist or not
self.RemoteMethodsCache = {} # Cache of used remote methods
self.RemoteConfigCache = {} # Cache of remote config
self.rhost = None
self.rport = None
self.proto = None
self.events = None
self.ssl = None
self.relay_host = None
self.timeout = None
self.udp_server = None
self.proto = None
self.relay = None
self.remote = None
self.debug = None
self.debugCalls = None # Some internal debugging
self.event = threading.Event()
self.socket_event = threading.Event()
self.lock = threading.Lock()
self.recv_stream_status = threading.Event()
self.terminate = False
#############################################################################################################
#
# Custom pwntools functions
#
#############################################################################################################
def custom_can_recv(self, timeout=0.020):
"""
wrapper for pwntools 'can_recv()'
SSLSocket and paramiko recv() do not support any flags
"""
time.sleep(timeout)
try:
""" pwntools """
if self.remote.can_recv():
return True
return False
except TypeError:
""" paramiko ssh """
if self.remote.sock.recv_ready():
return True
return False
except ValueError:
""" SSL """
# TODO: Not found any way for SSL
return True
except AttributeError:
""" OSError """
print('AttributeError')
return False
def custom_connect_remote(self, rhost, rport, timeout=10):
""" Custom SSH connect_remote(), still we using pwntools 'transport()' """
# channel = self.relay.transport.Channel(timeout=timeout)
channel = self.relay.transport.open_channel('direct-tcpip', (rhost, rport), ('127.0.0.1', 0), timeout=timeout)
print(self.relay.transport.is_active())
return channel
def custom_exec_command(self, cmd, script='', timeout=10, env_export=None):
""" Custom SSH exec_command(), still using pwntools 'transport()' """
env_export = ';'.join('export {}={}'.format(var, env_export.get(var)) for var in env_export)
cmd = ''.join([env_export, cmd, script])
stdout = b''
stderr = b''
sftp = None
relay = None
"""
Generally not many embedded devices who has sftp support,
meaning it will most likely not support exec_command() and/or python either.
Just to avoid potential 'psh' hanging in embedded devices
"""
try:
sftp = self.relay.transport.open_session(timeout=timeout)
sftp.settimeout(timeout=timeout)
sftp.invoke_subsystem('sftp')
except Exception as e:
print('[custom_exec_command] (sftp)', repr(e))
return {"stdout": [], "stderr": ['embedded devices not supported']}
finally:
if sftp:
sftp.close()
try:
relay = self.relay.transport.open_session(timeout=timeout)
relay.settimeout(timeout=timeout)
relay.exec_command(cmd)
while True:
stdout = b''.join([stdout, relay.recv(4096)])
if relay.exit_status_ready():
break
""" Catch potential stderr from remote """
stderr = b''.join([stderr, relay.recv_stderr(4096)])
except Exception as e:
print('[custom_exec_command] (relay)', repr(e))
return {"stdout": [], "stderr": ['exec request failed on channel {}'.format(relay.get_id())]}
finally:
if relay:
relay.close()
stdout = stdout.decode('utf-8').split('\n')
stderr = stderr.decode('utf-8').split('\n')
""" return output in list, remove potential empty entries """
return {
"stdout": [x for x in stdout if x],
"stderr": [x for x in stderr if x]
}
def dh_discover(self, msg):
""" Device DHIP/DVRIP discover function """
cmd = msg.split()
dh_data = None
host = None
sock = None
remote_recvfrom = None
remote_ip = None
remote_port = None
usage = {
"dhip": "[host]",
"dvrip": "[host]"
}
if len(cmd) < 2 or len(cmd) > 3 or cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return True
discover = cmd[1]
if discover == 'dhip':
if len(cmd) == 2:
dip = '239.255.255.251'
else:
dip = check_host(cmd[2])
if not dip:
log.failure("Invalid RHOST")
return False
dport = 37810
query_args = {
"method": "DHDiscover.search",
# "method": "deviceDiscovery.refresh",
# "method": "deviceDiscovery.ipScan",
# "method": "DHDiscover.setConfig",
# "method": "Security.getEncryptInfo",
# "method": "DevInit.account",
# "method": "PasswdFind.getDescript",
# "method": "PasswdFind.resetPassword",
# "method": "PasswdFind.checkAuthCode",
# "method": "DevInit.leAction",
# "method": "userManager.getCaps",
# "method": "DevInit.access",
# "method": "Security.modifyPwdOutSession",
"params": {
"mac": "",
"uni": 1
},
}
header = \
p64(0x2000000044484950, endian='big') + p64(0x0) + p32(len(json.dumps(query_args))) + \
p32(0x0) + p32(len(json.dumps(query_args))) + p32(0x0)
packet = header + json.dumps(query_args).encode('latin-1')
elif discover == 'dvrip':
if len(cmd) == 2:
dip = '255.255.255.255'
else:
dip = check_host(cmd[2])
if not dip:
log.failure("Invalid RHOST")
return False
dport = 5050
packet = p32(0xa3010001, endian='big') + (p32(0x0) * 3) + p32(0x02000000, endian='big') + (p32(0x0) * 3)
else:
log.failure('{}'.format(help_all(msg=cmd[0], usage=usage)))
return False
if self.relay_host:
script = r"""
import os, sys, socket, base64
socket.setdefaulttimeout(4)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(base64.b64decode(os.getenv('PACKET')), (os.getenv('dip'),int(os.getenv('dport'))))
while True:
try:
dh_data, addr = sock.recvfrom(8196)
print({"host": addr[0],
"dh_data": base64.b64encode(dh_data)
})
except Exception as e:
# sys.stderr.write(repr(e))
break
sock.close()
"""
env_export = {
'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/sbin',
'PACKET': b64e(packet),
'dip': dip,
'dport': str(dport)
}
if not self.relay:
dh_data = init_relay(relay=self.relay_host, rhost=self.rhost, rport=self.rport, discover=discover)
if not dh_data:
return False
self.relay = dh_data.get('dh_relay')
remote_recvfrom = self.custom_exec_command(
cmd=';python -c ', script=sh_string(script), env_export=env_export)
else:
socket.setdefaulttimeout(3)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self._debug("SEND", packet)
sock.sendto(packet, (dip, dport))
while True:
if self.relay:
for host in remote_recvfrom.get('stdout'):
x = ast.literal_eval(host)
dh_data = b64d(x.get('dh_data'))
remote_ip = x.get('host')
remote_port = dport
break
if len(remote_recvfrom.get('stdout')):
remote_recvfrom.get('stdout').remove(host)
else:
if len(remote_recvfrom.get('stderr')):
for stderr in remote_recvfrom.get('stderr'):
log.warning('[stderr] {}'.format(stderr))
return True
else:
try:
dh_data, addr = sock.recvfrom(4096)
remote_ip = addr[0]
remote_port = addr[1]
except (Exception, KeyboardInterrupt, SystemExit):
sock.close()
return True
log.success("dh_discover response from: {}:{}".format(remote_ip, remote_port))
self._debug("RECV", dh_data)
dh_data = dh_data[32:].decode('latin-1')
if discover == 'dhip':
dh_data = json.loads(dh_data.strip('\x00'))
print(json.dumps(dh_data, indent=4))
elif discover == 'dvrip':
bin_info = {
"Version": {
"Version": "{}.{}.{}.{}".format(
u16(dh_data[0:2]), u16(dh_data[2:4]), u16(dh_data[4:6]), u16(dh_data[6:8]))
},
"Network": {
"Hostname": dh_data[8:24].strip('\x00'),
"IPAddress": unbinary_ip(dh_data[24:28]),
"SubnetMask": unbinary_ip(dh_data[28:32]),
"DefaultGateway": unbinary_ip(dh_data[32:36]),
"DnsServers": unbinary_ip(dh_data[36:40]),
},
"AlarmServer": {
"Address": unbinary_ip(dh_data[40:44]),
"Port": u16(dh_data[44:46]),
"Unknown46-47": u8(dh_data[46:47]),
"Unknown47-48": u8(dh_data[47:48]),
},
"Email": {
"Address": unbinary_ip(dh_data[48:52]),
"Port": u16(dh_data[52:54]),
"Unknown54-55": u8(dh_data[54:55]),
"Unknown55-56": u8(dh_data[55:56]),
},
"Unknown": {
"Unknown56-50": unbinary_ip(dh_data[56:60]),
"Unknown60-62": u16(dh_data[60:62]),
"Unknown82-86": unbinary_ip(dh_data[82:86]),
"Unknown86-88": u16(dh_data[86:88]),
},
"Web": {
"Port": u16(dh_data[62:64]),
},
"HTTPS": {
"Port": u16(dh_data[64:66]),
},
"DVRIP": {
"TCPPort": u16(dh_data[66:68]),
"MaxConnections": u16(dh_data[68:70]),
"SSLPort": u16(dh_data[70:72]),
"UDPPort": u16(dh_data[72:74]),
"Unknown74-75": u8(dh_data[74:75]),
"Unknown75-76": u8(dh_data[75:76]),
"MCASTAddress": unbinary_ip(dh_data[76:80]),
"MCASTPort": u16(dh_data[80:82]),
},
}
log.info("Binary:\n{}".format(json.dumps(bin_info, indent=4)))
log.info("Ascii:\n{}".format(dh_data[88:].strip('\x00')))
def dh_connect(self, username=None, password=None, logon=None, force=False):
""" Initiate connection to device and handle possible calls from cmd line """
console = None
log.info(
color('logon type "{}" with proto "{}" at {}:{}'.format(logon, self.proto, self.rhost, self.rport), LGREEN)
)
if self.relay_host:
dh_data = init_relay(relay=self.relay_host, rhost=self.rhost, rport=self.rport)
if not dh_data:
return False
self.relay = dh_data.get('dh_relay')
self.remote = dh_data.get('dh_remote')
elif self.proto == 'http' or self.proto == 'https':
self.remote = DahuaHttp(self.rhost, self.rport, proto=self.proto, timeout=self.timeout)
else:
try:
self.remote = remote(self.rhost, self.rport, ssl=self.ssl, timeout=self.timeout)
except PwnlibException:
return False
if self.args.test:
self.header = self.proto_header()
return True
if not self.args.dump:
console = log.progress(color('Dahua Debug Console', YELLOW))
console.status(color('Trying', YELLOW))
if self.proto == 'dvrip' or self.proto == '3des':
if not self.dahua_dvrip_login(username=username, password=password, logon=logon):
if not self.args.dump:
if self.args.save:
console.success('Save host')
else:
console.failure(color("Failed", RED))
return False
else:
return False
elif self.proto == 'dhip' or self.proto == 'http' or self.proto == 'https':
if not self.dahua_dhip_login(username=username, password=password, logon=logon, force=force):
if not self.args.dump:
if self.args.save:
console.success('Save host')
else:
console.failure(color('Failed', RED))
return False
else:
return False
# Old devices fail and close connection
if logon != 'old_3des':
query_args = {
"method": "userManager.getActiveUserInfoAll",
"params": {
},
}
dh_data = self.send_call(query_args)
users = '{}'.format(help_msg('Active Users'))
if dh_data.get('params').get('users') is not None:
for user in dh_data.get('params').get('users'):
users += '{}@{} since {} with "{}" (Id: {}) \n'.format(
user.get('Name'),
user.get('ClientAddress'),
user.get('LoginTime'),
user.get('ClientType'),
user.get('Id'))
else:
users += 'None'
log.info(users)
query_args = {
"method": "magicBox.getDeviceType",
"params": None,
}
self.send_call(query_args, multicall=True)
""" Classes: NVR, IPC, VTO, VTH, DVR... etc. """
query_args = {
"method": "magicBox.getDeviceClass",
"params": None,
}
self.send_call(query_args, multicall=True)
query_args = {
"method": "global.getCurrentTime",
"params": None,
}
dh_data = self.send_call(query_args, multicall=True, multicallsend=True)
self.DeviceClass = \
dh_data.get('magicBox.getDeviceClass').get('params').get('type') \
if dh_data and dh_data.get('magicBox.getDeviceClass').get('result') else '(null)'
self.DeviceType = \
dh_data.get('magicBox.getDeviceType').get('params').get('type')\
if dh_data and dh_data.get('magicBox.getDeviceType').get('result') else '(null)'
if dh_data and dh_data.get('global.getCurrentTime').get('params'):
remote_time = dh_data.get('global.getCurrentTime').get('params').get('time')
elif dh_data and dh_data.get('global.getCurrentTime').get('result'):
remote_time = dh_data.get('global.getCurrentTime').get('result')
else:
remote_time = '(null)'
log.info("Remote Model: {}, Class: {}, Time: {}".format(
self.DeviceType,
self.DeviceClass,
remote_time
))
if self.args.dump:
return True
if not self.instance_service('console', dattach=True, start=True):
console.failure(color("Attach Console failed, using local only", LRED))
self.console_attach = False
else:
self.console_attach = True
console.success(color('Success', GREEN))
if self.events:
self.event_manager(msg='events 1')
if self.proto in ['http', 'https']:
_thread.start_new_thread(self.subscribe_notify, ())
return True
def _sleep_check_socket(self, delay):
""" This function will act as the delay for keepAlive of the connection
At same time it will check and process any late incoming packets every second,
which will end up in clientNotifyData()
"""
keep_alive = 0
dsleep = 1
dh_data = None
while True:
if delay <= keep_alive:
break
else:
keep_alive += dsleep
if self.terminate:
break
# If received dh_data and not another process locked p2p(), should be callback, break
if self.custom_can_recv() and not self.lock.locked():
try:
dh_data = self.p2p(packet=None, recv=True)
if not dh_data:
continue
""" Will always return list """
dh_data = fix_json(dh_data)
for NUM in range(0, len(dh_data)):
self._check_for_keepalive(dh_data[NUM])
except EOFError as e:
log.failure('[_sleep_check_socket] {}'.format(repr(e)))
self.remote.close()
return False
except (AttributeError, ValueError, TypeError) as e:
log.failure('[_sleep_check_socket] ({}) {}'.format(repr(e), dh_data))
pass
time.sleep(dsleep)
continue
def _p2p_keepalive(self, delay):
""" Main keepAlive thread """
keep_alive = log.progress(color('keepAlive thread', YELLOW))
keep_alive.success(color('Started', GREEN))
self.keep_alive_timeout_times = 5
self.keep_alive_timeout = 0
while True:
self._sleep_check_socket(delay)
if self.terminate:
return False
if not self.remote.connected() or self.keep_alive_timeout == self.keep_alive_timeout_times:
log.warning('self termination ({})'.format(self.rhost))
self.terminate = True
self.remote.close()
# TEST
# del self.remote
if self.relay:
self.relay.close()
# TEST
# del self.relay
return False
query_args = {
"method": "global.keepAlive",
"params": {
"timeout": delay,
"active": True
},
}
try:
dh_data = self.p2p(query_args, timeout=10)
# print('[keepAlive] sending/receiving', dh_data)
except requests.exceptions.RequestException:
self.keep_alive_timeout = self.keep_alive_timeout_times
self.event.set()
self.remote.close()
# TEST
# del self.remote
if self.relay:
self.relay.close()
# TEST
# del self.relay
continue
except EOFError as e:
log.failure('[keepAlive] {}'.format(repr(e)))
self.remote.close()
if self.relay:
self.relay.close()
continue
if dh_data is None:
log.failure('[keepAlive timeout] ({})'.format(self.rhost))
self.keep_alive_timeout += 1
self.event.set()
continue
""" Will always return list """
dh_data = fix_json(dh_data)
for NUM in range(0, len(dh_data)):
self._check_for_keepalive(dh_data[NUM])
def _check_for_keepalive(self, dh_data):
try:
# keepAlive answer
if dh_data.get('result') and dh_data.get('params').get('timeout'):
if self.event.is_set():
log.success('[keepAlive back] ({})'.format(self.rhost))
self.keep_alive_timeout = 0
self.event.clear()
elif not dh_data.get('result') and dh_data.get('error').get('code') == 287637505:
# Invalid session in request data!
log.failure('[keepAlive timeout] ({})'.format(self.rhost))
self.keep_alive_timeout = self.keep_alive_timeout_times
self.event.set()
else:
"""
Not keepAlive answer, send it away to clientNotify
check for 'client.' callback 'method' or other stuff
"""
if dh_data:
self.client_notify(json.dumps(dh_data))
except AttributeError:
if dh_data:
self.client_notify(json.dumps(dh_data))
pass
#
# Any late dh_data processed from the '_p2p_keepalive()' thread coming from remote device will end up here,
# sort out with "client.notify....." callback
#
def client_notify(self, dh_data):
#
# Some stuff prints sometimes 'garbage', like 'dvrip -l'
#
dh_data = ndjson.loads(dh_data, strict=False)
for NUM in range(0, len(dh_data)):
dh_data = dh_data[NUM]
if dh_data.get('method') == 'client.notifyConsoleResult':
return self.console_result(msg=dh_data, callback=True)
elif dh_data.get('method') == 'client.notifyConsoleAsyncResult':
return self.console_result(msg=dh_data, callback=True)
elif dh_data.get('method') == 'client.notifyDeviceInfo':
return self.device_discovery(msg=dh_data, callback=True)
elif dh_data.get('method') == 'client.notifyEventStream':
if self.udp_server:
dh_data['host'] = self.rhost
#
# wifi also need events
#
# print('[2] netApp')
# self.net_app(dh_data,callback=True)
#
# Send off to main event handler
#
notify_event = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
notify_event.sendto(json.dumps(dh_data).encode('latin-1'), ("127.0.0.1", EventInServerPort))
notify_event.close()
else:
try:
if dh_data.get('method'):
log.failure(color("[clientNotify] Unhandled callback: {}".format(dh_data.get('method')), RED))
print(json.dumps(dh_data, indent=4))
except AttributeError:
log.failure('[clientNotify] Unknown dh_data: {}'.format(dh_data))
pass
return True
def send_call(self, query_args=None, multicall=False, multicallsend=False, errorcodes=False, login=False):
""" Primary function for sending/receiving data """
if query_args is None:
query_args = ''
""" Single call """
if not multicall and not len(self.multicall_query_args):
""" Just to make 'params' consistent both if it is 'None' or '{}' """
if len(query_args) and query_args.get('params') is not None:
if not len(query_args.get('params')):
query_args.update({"params": None})
try:
dh_data = self.p2p(query_args, login=login)
except (KeyboardInterrupt, EOFError):
return None
if not dh_data:
return None
"""
Replicating how Dahua sending dh_data, so we pass on received dh_data with 'transfer'
packet + split('\n')
[JSON][0]
[DATA][1]
"""
try:
dh_data = json.loads(dh_data)
except (AttributeError, JSONDecodeError) as e:
if not dh_data.find('\n'):
log.failure("[sendCall] (json) ({}) {}".format(repr(e), dh_data))
pass
tmp = dh_data.split('\n')
dh_data = json.loads(tmp[0])
dh_data.update({"transfer": b64e(tmp[1])})
pass
if not dh_data.get('result') and dh_data.get('error'):
if self.debugCalls:
log.failure(color("query: {}".format(query_args), GREEN))
log.failure(color(
"response: {}".format(dh_data), LRED))
if errorcodes:
return dh_data
else:
return False
return dh_data
""" Multi call """
if not len(self.multicall_query_args):
self.multicall_query_args = []
self.multicall_return_check = []
"""
Normally we will return JSON dh_data with key as the 'method' name when 'params' is None
Others we will use 'params' name, as the 'method' name can be the same for different calls
"""
# TODO: For now we need to specify known calls, should be bit smarter to handle all kind of methods
# (maybe by using ID)
#
# Just to make 'params' consistent both if it is 'None' or '{}'
if len(query_args) and query_args.get('params') is not None:
if not len(query_args.get('params')):
query_args.update({"params": None})
if isinstance(query_args, dict):
query_args.update({
'id': self.ID,
'session': self.SessionID
})
self.update_id()
if len(query_args):
if query_args.get('params') is None:
method = query_args.get('method')
elif query_args.get('method') == 'configManager.getConfig' and query_args.get('params').get('name'):
method = query_args.get('params').get('name')
elif query_args.get('method') == 'configManager.setConfig' and query_args.get('params').get('name'):
method = query_args.get('params').get('name')
elif query_args.get('method') == 'configManager.getDefault' and query_args.get('params').get('name'):
method = query_args.get('params').get('name')
elif query_args.get('method').split('.')[0] == 'netApp':
method = query_args.get('method')
# TODO: Very beta test
elif query_args.get('id'):
method = query_args.get('id')
else:
log.failure("[sendCall] (multicall): {}".format(query_args.get('method')))
return False
self.multicall_query_args.append(query_args)
self.multicall_return_check.append({"id": query_args.get('id'), "method": method})
# TODO: Not good idea to have one additional outside of P2P, but is needed (for now)
# self.ID += 1
if multicall and multicallsend and len(self.multicall_query_args):
self.multicall_query = {
"method": "system.multicall",
"params": self.multicall_query_args,
}
try:
dh_data = self.p2p(self.multicall_query)
except (KeyboardInterrupt, EOFError):
self.multicall_query_args = []
self.multicall_return_check = []
return None
if not dh_data or not len(dh_data):
print('[system.multicall] data:', dh_data)
if self.debugCalls:
log.failure(color("[sendCall #1] No dh_data back with query: (system.multicall)", LRED))
# Lets listen again, keepAlive might got it and sent back to recv()
try:
dh_data = self.p2p(packet=None, recv=True)
except (KeyboardInterrupt, EOFError):
if self.debugCalls:
log.failure(color("[sendCall #2] No dh_data back with query: (system.multicall)", LRED))
self.multicall_query_args = []
self.multicall_return_check = []
return None
if not dh_data:
return None
try:
dh_data = json.loads(dh_data)
except (AttributeError, JSONDecodeError) as e:
log.failure("[sendCall] (json) ({}) {}".format(repr(e), dh_data))
try:
dh_data += self.p2p(packet=None, recv=True)
except (KeyboardInterrupt, EOFError):
self.multicall_query_args = []
self.multicall_return_check = []
return None
if not dh_data:
return None
if not dh_data.get('result'):
if self.debugCalls:
log.failure(color("query: {}".format(self.multicall_query_args), GREEN))
log.failure(color(
"response: {}".format(dh_data), LRED))
return None
dh_data = dh_data.get('params')
tmp = {}
for key in range(0, len(dh_data)):
""" Looks like to be FIFO, bailout just in case to catch any ID mismatch """
if not self.multicall_return_check[key].get('id') == dh_data[key].get('id'):
log.error("Function SendCall() ID mismatch :\nreq: {}\nres: {}".format(
self.multicall_return_check[key], dh_data[key]))
tmp[self.multicall_return_check[key].get('method')] = dh_data[key]
self.multicall_query_args = []
self.multicall_return_check = None
return tmp
def instance_service(
self, method_name='', dattach=False, params=None, attach_params=None,
stop=False, start=False, pull=None, clean=False, list_all=False, fuzz=False,
attach_only=False, multicall=False, multicallsend=False):
"""
Main function to create remote instance and attach (if needed)
Storing all details in 'self.instance_serviceDB', simplifies to create/check/pull/close remote instance
"""
if clean:
for service in copy.deepcopy(self.instance_serviceDB):
if not service == 'console':
log.warning(
color('BUG: instance_service "{}" should have already been stopped (stop now)'.format(service),
LRED))
if self.debugCalls:
log.info('[instance_service] sending stop to: {}'.format(service))
self.instance_service(service, stop=True)
return True
elif list_all:
for service in self.instance_serviceDB:
dh_data = '{}'.format(help_msg(service))
for key in self.instance_serviceDB.get(service):
dh_data += '[{}] = {}\n'.format(key, self.instance_serviceDB.get(service).get(key))
log.info(dh_data)
return True
elif pull:
if method_name not in self.instance_serviceDB:
if self.debugCalls:
log.failure('[instanceService] (pull) method_name: {} do not exist'.format(method_name))
return False
if self.debugCalls:
log.success('[instanceService] (pull) method_name: {} do exist'.format(method_name))
return self.instance_serviceDB.get(method_name).get(pull)
elif start:
if not self.check_for_service(method_name):
if self.debugCalls:
log.failure('[instanceService] (service) method_name: {} do not exist'.format(method_name))
return False
if method_name in self.instance_serviceDB:
if self.debugCalls:
log.failure('[instanceService] (create) method_name: {} do exist'.format(method_name))
return False
object_id, _proc_id, _sid, dparams, attach_params = self.instance_create(
method=method_name,
dattach=True if attach_params else dattach,
params=params,
attach_params=attach_params,
fuzz=fuzz,
attach_only=attach_only,
multicall=multicall,
multicallsend=multicallsend,
)
if multicall and not multicallsend:
return
""" More for when fuzzing, we want the Response and not only True/False """
if fuzz and _sid or fuzz and object_id:
self.fuzzDB.update({
method_name: {
"method_name": method_name,
"attach": True if attach_params else dattach,
"params": dparams,
"attach_params": attach_params,
"object": object_id, # False if failure
"proc": _proc_id, # method_name
"sid": _sid # Response dh_data w/ error code
}
})
if not object_id:
if self.debugCalls:
log.failure('[instanceService] (create) Object: {} do not exist'.format(method_name))
return False
self.instance_serviceDB.update({
method_name: {
"method_name": method_name,
"attach": True if attach_params else dattach,
"params": dparams,
"attach_params": attach_params,
"object": object_id,
"proc": _proc_id,
"sid": _sid
}
})
if self.debugCalls:
log.success('[instanceService] (update) {}'.format(method_name))
self.instance_service(list_all=True)
return True
elif stop:
if method_name not in self.instance_serviceDB:
if self.debugCalls:
log.failure('[instanceService] (destroy) method_name: {} do not exist'.format(method_name))
return False
result, method, dh_data = self.instance_destroy(
method=method_name,
_proc_id=self.instance_serviceDB.get(method_name).get('proc'),
object_id=self.instance_serviceDB.get(method_name).get('object'),
detach=self.instance_serviceDB.get(method_name).get('attach'),
detach_params=self.instance_serviceDB.get(method_name).get('attach_params')
)
if method_name in self.instance_serviceDB:
self.instance_serviceDB.pop(method_name)
if self.debugCalls:
log.success('[destroy] pop: {}'.format(method_name))
self.instance_service(list_all=True)
if not result:
if self.debugCalls:
log.failure('[instanceService] (destroy,instance_destroy) {} {} {}'.format(result, method, dh_data))
return False
return True
def instance_create(
self, method, dattach=True, params=None, attach_params=None, fuzz=False, attach_only=False,
multicall=False, multicallsend=False):
""" Create factory.instance """
object_id = None
_proc_id = None
dparams = None
answer = None