forked from mcw0/Tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDahua-JSON-Debug-Console-v2.py
6725 lines (5613 loc) · 184 KB
/
Dahua-JSON-Debug-Console-v2.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
#!/usr/bin/env python3
"""
Author: bashis <mcw noemail eu> 2019-2021
Subject: Dahua JSON Debug Console
[Updates]
March 2021:
Misc bug fixes and tuning for performance of self.P2P()
DHIP artifact: Removed ["magic":"0x1234"]
January 2021 (Major rewrite):
1. Implemented 'multicall' - big timesaver (!) (not 100% consistent usage for now, but working good as it is)
2. 'SendCall()' wrapper around 'self.P2P()'. self.P2P() should not be used directly (unless you want raw data).
3. 'console' Multiple simultaneous connections to devices, easy switching between active Console
4. 'password manager', create/change Dahua hash and connection details for devices, saved in 'dhConsole.json'
- No fancy own encryption/decryption, we simply use the Dahua 'one way' format to save and pass on hashes.
- ./Dahua-JSON-Debug-Console-v2.py --rhost <RHOST> --proto <PROTO> --rport <RPORT> --auth <USERNAME>:<PASSWORD> --save
5. Events/Alarm, scanning config and subscribing on all found events/alarm
- Listen for incoming event traffic on UDP from instances, accepting external TCP connections for relay of event traffic (only on 127.0.0.1)
- The listening UDP socket for incoming are literally directly connected to outgoing TCP socket, for speedy reasons.
- Meaning that output is unsorted, so the JSON needs to be fixed. Check fix_json() for details.
- Listen for some events internally to give some info, using like 'reboot' to automatically restart connection
- Added sending IP to JSON event to easily see where it came from
- Simple 'eventviewer' with: --eventviewer
6. 'network wifi', WiFi scan/connect/enable/disable/reset
- TODO: Should use events for some status updates
7. 'diag/pcap', Interim debug functions (pcap/NFS/logredirect) Note: Seems only to work with NVR
8. 'rdiscover/ldiscover', remote/local discovery of devices (ldiscover support both DHIP and DVRIP)
9. Consistent way to write and handle 'Usage'
10. Continue to Console even if console.attach fails (NVR)
- Looks like to me that the thread is locked and do not accept any attach
11. The 'fuzz()' function is an first attempt to fuzzing the '<method>.factory.instance' w/ potential '<method>.attach' to map needed params
- Not really accurate for now, but can still give an hint what's required
- Handle only one params for now, should handle two or more as well.
12. 'debug' various internal debug commands
And much more...
[For testing internal events]
$ cat exit.json
{"callback": 32380128, "id": 12, "method": "client.notifyEventStream", "params": {"SID": 513, "eventList": [{"Action": "Start", "Code": "Exit", "Data": {"LocaleTime": "2000-01-01 00:18:53", "UTC": 946657133.0}, "Index": 0}]}, "session": 32218112, "ipAddr": "192.168.57.21"}
$ cat exit.json | ncat -u 127.0.0.1 43210
[!] [2000-01-01 00:18:53 (192.168.57.21) ] Exit App
$ cat shutdown.json
{"callback": 52762696, "id": 12, "method": "client.notifyEventStream", "params": {"SID": 513, "eventList": [{"Action": "Start", "Code": "ShutDown", "Data": {"LocaleTime": "2000-01-01 00:07:13", "UTC": 946656433.0}, "Index": 0}]}, "session": 52568320, "ipAddr": "192.168.57.21"}
$ cat shutdown.json | ncat -u 127.0.0.1 43210
[!] [2000-01-01 00:07:13 (192.168.57.21) ] ShutDown App
$ cat reboot.json
{"callback": 32614288, "id": 12, "method": "client.notifyEventStream", "params": {"SID": 513, "eventList": [{"Action": "Start", "Code": "Reboot", "Data": {"LocaleTime": "2021-01-02 12:53:12", "UTC": 1609563192.0}, "Index": 0}]}, "session": 32468992, "ipAddr": "192.168.57.21"}
$ cat reboot.json | ncat -u 127.0.0.1 43210
[!] [2021-01-02 12:53:12 (192.168.57.21) ] Reboot
[!] dh0: IPC-HDxxxxxx-W (192.168.57.21)
[*] Closed connection to 192.168.57.21 port 37777
[*] Scheduling reconnect to 192.168.57.21
[+] Successful instance termination of IPC-HDxxxxxx-W (192.168.57.21)
[+] Opening connection to 192.168.57.21 on port 37777: Done
[+] Dahua JSON Console: Success
[+] Login: Success
[...]
[TODO]
Clean/narrow 'Exception's better
HTTP/HTTPS proxy
[BUGS]
Plenty fixed (and for sure new introduced)
[Note]
Even if 'service methods' shows up in lists, do _not_ automatically mean that the actual code exist.
- I.e. {"code":268632064,"message":"Component error: interface not found!"}
March 2020:
1. DVRIP SessionID bug: "method": "snapManager.listMethod".
2. Renamed 'ssh' to 'sshd', 'ssh' already used in some FW.
February 2020:
1. Added option 'setDebug', Should start produce output from Debug Console in VTO/VTH
2. Added '--discover', Multicast search of devices or direct probe (--rhost 192.168.57.20) of device via UDP/37810
3. Added '--dump {config,service}' for dumping config or services on remote host w/o entering Debug Console
January 2020:
1. Ported to Python 3
2. Fixed some bugs and code adjustment
3. Added support for DVRIP (TCP/37777) [Note: Some JSON commands that working with DHIP return nothing with DVRIP]
4. encode/decode in latin-1, we might need untouched chars between 0x00 - 0xff
5. Better 'debug' with hexdump as option
"""
import sys
import json
import ndjson # pip3 install ndjson
import argparse
import copy
import _thread
import inspect
import resource
import os.path
from os import path
import select, socket, queue
from json.decoder import JSONDecodeError
from Crypto.PublicKey import RSA # pip3 install pycryptodome
from OpenSSL import crypto # pip3 install pyopenssl
from pwn import * # pip3 install pwntools (https://github.com/Gallopsled/pwntools)
global debug
# For Dahua DES/3DES
ENCRYPT = 0x00
DECRYPT = 0x01
# Colours
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
WHITE = '\033[37m'
LRED = '\033[91m'
LGREEN = '\033[92m'
LYELLOW = '\033[93m'
LBLUE = '\033[94m'
LWHITE = '\033[97m'
EventInServerPort = 43210 # UDP listener port, receiving events
EventOutServerPort = 43211 # TCP listener port, delivery of events
keepAliveTimeOut = 5
def color(text,color):
return "{}{}\033[0m".format(color,text)
#
# JSON data we will receive from events is an mess, need to sort out that before loading JSON to a list
# input: unsorted JSON
# return: sorted JSON in a list
#
def fix_json(mess):
data = []
start = 0
result = ''
for check in range(0,len(mess)):
if mess[check] == '{':
result += mess[check]
start += 1
elif start:
result += mess[check]
if mess[check] == '}':
start -= 1
if not start:
try:
if len(result):
data.append(json.loads(result))
except JSONDecodeError as e:
log.warning('fix_json: {}'.format(e))
pass
result = ''
if start:
log.warning('fix_json: not complete')
return data
#
# DVRIP have different codes in their protocols
#
def DahuaProto(proto):
proto = binascii.b2a_hex(proto.encode('latin-1')).decode('latin-1')
headers = [
'f600', # JSON
'a005', # DVRIP login Send Login Details
'a001', # DVRIP Send Request Realm
'a000', # 3DES Login
'b000', # DVRIP Recv
'b001', # DVRIP Recv
'a301', # DVRIP Discover Request
'b300', # DVRIP Discover Response
]
if proto[:4] in headers:
return True
return False
#
# print help function
#
def helpMsg(data):
return '\033[92m[\033[91m{}\033[92m]\033[0m\n'.format(data)
def helpAll(msg, Usage):
"""
Examples:
#
# Supported format
#
Usage = {
"key0":"(value 0)",
"key1":"(value 1)",
"key2":"(value 2)",
"key3":"(value 3)"
}
Usage = {
"key0":"(value 0)",
"key1":{
"subkey0":"(value 0)",
"subkey1":"(value 1)"
},
"key2":"(value 2)",
"key3":"(value 3)"
}
Usage = {
"key0":{
"subkey0":"(value 0)",
"subkey1":"(value 1)",
"subkey2":"(value 2)"
},
"key1":{
"subkey0":"(value 0)",
"subkey1":"(value 1)"
}
}
# One same line for all Usage()
log.info('{}'.format(helpAll(msg=msg,Usage=Usage)))
return True
"""
if msg.find('-h'):
msg = msg.strip('-h')
cmd = msg.split()
try:
data = '{}'.format(helpMsg('Usage'))
for key in Usage if not len(cmd) > 1 else Usage.get(cmd[1]) if isinstance(Usage.get(cmd[1]),dict) else {cmd[1]}:
if isinstance(Usage.get(key),dict):
for subkey in Usage.get(key):
data += '{} {} {} {}\n'.format(cmd[0], key, subkey, Usage.get(key).get(subkey,'(1 Not defined)'))
elif isinstance(Usage.get(key) if not len(cmd) > 1 else key,str):
data += '{} {} {}\n'.format(
cmd[0],
'{} {}'.format(cmd[1],key) if len(cmd) > 1 else key,
Usage.get(key,'(Not defined: {})'.format(key)) if len(cmd) == 1 else Usage.get(cmd[1]).get(key,'(Not defined: {})'.format(key))
)
else:
print('[else]')
print(type(key),key)
return data
except AttributeError as e:
print('error',e)
#############################################################################################################
#
# Dahua HASH / pwd Manager functions
#
#############################################################################################################
class pwdManager:
def __init__(self, rhost=None, auth=None, login=None):
self.gen1 = False
self.gen2 = False
self.login = login
self.rhost = rhost
self.auth = auth
def DVRIP(self,query_args):
proto = query_args.get('proto')
if not self.auth:
data = self.GetHost(self.rhost,hashes=True)
if args.proto == '3des':
self.login.failure(color('3DES: You need to use --auth <username>:<password>',RED))
return False
if not data:
self.login.failure(color('You need to use --auth <username>:<password> [--save]',RED))
return False
if self.auth:
USER_NAME = self.auth.split(':')[0]
PASSWORD = self.auth.split(':')[1]
if proto == '3des':
data = {
"username":self.Dahua_Gen0_hash(USER_NAME,ENCRYPT),
"password":self.Dahua_Gen0_hash(PASSWORD,ENCRYPT)
}
elif proto == 'dvrip':
if not query_args.get('random'):
self.login.failure(color('Realm [random]',RED))
return False
REALM = query_args.get('realm')
RANDOM = query_args.get('random')
if not self.auth:
data = self.GetHost(self.rhost,REALM)
if not data:
self.login.failure(color('You need to use --auth <username>:<password> [--save]',RED))
return False
USER_NAME = data.get('username')
#
# Login request
#
HASH = USER_NAME + '&&' + self.Dahua_Gen2_md5_hash(RANDOM, REALM, USER_NAME, PASSWORD if self.auth else None) + self.Dahua_DVRIP_md5_hash(RANDOM, USER_NAME, PASSWORD if self.auth else None)
data = {
"hash":HASH
}
return data
def DHIP(self, query_args):
# FakeIPaddr = '(null)' # WebGUI: mask our real IP
# FakeIPaddr = '192.168.57.1'
FakeIPaddr = '127.0.0.1'
clientType = '' # WebGUI: We do not show up in logs or online users
# clientType = 'Web3.0' # Web3.0 / Dahua3.0 / CGI
loginType = 'Direct'
authorityType = 'Default'
authorityInfo = ''
passwordType = 'Default'
if not self.auth :
data = self.GetHost(self.rhost,hashes=True)
if not data:
self.login.failure(color('You need to use --auth <username>:<password> [--save]',RED))
return False
USER_NAME = data.get('username')
else:
USER_NAME = self.auth.split(':')[0]
PASSWORD = self.auth.split(':')[1]
if query_args.get('method') == 'global.login':
params = {
"clientType":clientType,
"ipAddr":FakeIPaddr,
"loginType":loginType,
"password":"",
"userName":USER_NAME,
"Encryption":"None",
}
return params
elif query_args.get('error').get('code') == 268632079: # DHIP REALM
query_args = query_args.get('params')
RANDOM = query_args.get('random')
REALM = query_args.get('realm')
ENCRYPTION = query_args.get('encryption')
AUTHORIZATION = query_args.get('authorization') # Not known usage, unique for each device but not random
MAC = query_args.get('mac')
if not self.auth:
# We just checking RandSalt from REALM here
data = self.GetHost(self.rhost,REALM)
if not data:
self.login.failure(color('You need to use --auth <username>:<password> [--save]',RED))
return False
if not (ENCRYPTION == 'Default' or ENCRYPTION == 'OldDigest'):
self.login.failure(color('Encryption: "{}", You need to use --auth <username>:<password>'.format(ENCRYPTION),RED))
return False
if ENCRYPTION == 'Default':
HASH = self.Dahua_Gen2_md5_hash(RANDOM, REALM, USER_NAME, PASSWORD if self.auth else None)
elif ENCRYPTION == 'OldDigest':
HASH = self.gen1 if self.gen1 else self.Dahua_Gen1_hash(PASSWORD)
elif ENCRYPTION == 'Basic':
HASH = self.Basic(USER_NAME,PASSWORD)
elif ENCRYPTION == 'Plain':
HASH = PASSWORD
else:
log.fail('Unknown encryption: {}'.format(ENCRYPTION))
return False
passwordType = {
"Plain":"Plain",
"Basic":"Basic",
"OldDigest":"OldDigest",
"Default":"Default",
"2DCode":"2DCode"
}
authorityType = {
"Plain":"Plain",
"Basic":"Basic",
"OldDigest":"Default",
# "OldDigest":"OldDigest",
"Default":"Default",
"2DCode":"2DCode"
}
params = {
"userName":USER_NAME,
"password":HASH,
"clientType":clientType,
"ipAddr":FakeIPaddr,
"loginType":loginType,
"authorityInfo":authorityInfo,
"authorityType":authorityType.get(ENCRYPTION),
"passwordType":passwordType.get(ENCRYPTION),
}
return params
return
def ReadHosts(self):
try:
with open('dhConsole.json') as file:
return json.load(file)
except Exception as e:
log.failure(color('ReadHosts: {}'.format(e),RED))
return False
def WriteHosts(self,data):
try:
with open('dhConsole.json','w') as file:
json.dump(data,file)
log.success(color('Host saved successfully',GREEN))
return True
except Exception as e:
log.failure(color('WriteHosts: {}'.format(e),RED))
return False
def SaveHost(self,rhost,rport,proto,auth,realm):
data = self.ReadHosts()
if not data:
data = []
if not self.Get(rhost):
log.info('Adding new host "{}"'.format(rhost))
data.append({
"ipAddr":rhost,
"port":rport,
"proto":proto,
"username":auth.split(':')[0],
"password":{
"gen1":self.Dahua_Gen1_hash(auth.split(':')[1]),
"gen2":hashlib.md5((auth.split(':')[0] + ':' + realm + ':' + auth.split(':')[1]).encode('latin-1')).hexdigest().upper(),
"RandSalt":realm.split()[2]
},
"events":True,
})
else:
log.info('Updating host "{}"'.format(rhost))
for host in range(0,len(data)):
if rhost == data[host].get('ipAddr'):
break
data[host].update({
"ipAddr":rhost,
"port":rport,
"proto":proto,
"username":auth.split(':')[0],
"password":{
"gen1":self.Dahua_Gen1_hash(auth.split(':')[1]),
"gen2":hashlib.md5((auth.split(':')[0] + ':' + realm + ':' + auth.split(':')[1]).encode('latin-1')).hexdigest().upper(),
"RandSalt":realm.split()[2]
},
"events":True,
})
if not self.WriteHosts(data):
return False
return True
def GetHost(self,ipAddr=False,realm=False,hashes=False):
data = self.Get(ipAddr)
if not data:
log.failure('Host "{}" do not exist'.format(ipAddr))
return False
if realm:
RandSalt = realm.split()[2]
if not data.get('password').get('RandSalt') == RandSalt:
log.failure(color('RandSalt differs, current hash does not work anymore!',LRED))
return False
if hashes:
self.gen1 = data.get('password').get('gen1')
self.gen2 = data.get('password').get('gen2')
if not self.gen1 or not self.gen2:
log.failure('No available hashes!')
return False
return data
def Get(self,ipAddr=False):
data = self.ReadHosts()
if not data:
return False
if not ipAddr:
return data
if ipAddr:
for host in range(0,len(data)):
if ipAddr == data[host].get('ipAddr'):
tmp = True
break
else:
tmp = False
return data[host] if tmp else False
#
# The DES/3DES code in the bottom of this script.
#
def Dahua_Gen0_hash(self,data, mode):
# "secret" key for Dahua Technology
key = b'poiuytrewq' # 3DES
if len(data) > 8: # Max 8 bytes!
log.failure("'{}' is more than 8 bytes, this will most probaly fail".format(data))
data = data[0:8]
data_len = len(data)
key_len = len(key)
#
# padding key with 0x00 if needed
#
if key_len <= 8:
if not (key_len % 8) == 0:
key += p8(0x0) * (8 - (key_len % 8)) # DES (8 bytes)
elif key_len <= 16:
if not (key_len % 16) == 0:
key += p8(0x0) * (16 - (key_len % 16)) # 3DES DES-EDE2 (16 bytes)
elif key_len <= 24:
if not (key_len % 24) == 0:
key += p8(0x0) * (24 - (key_len % 24)) # 3DES DES-EDE3 (24 bytes)
#
# padding data with 0x00 if needed
#
if not (data_len % 8) == 0:
data += p8(0x0).decode('latin-1') * (8 - (data_len % 8))
if key_len == 8:
k = des(key)
else:
k = triple_des(key)
if mode == ENCRYPT:
data = k.encrypt(data.encode('latin-1'))
self.deshash = data
else:
data = k.decrypt(data)
data = data.decode('latin-1').strip('\x00') # Strip all 0x00 padding
return data
#
# From: https://github.com/haicen/DahuaHashCreator/blob/master/DahuaHash.py
#
#
def compressor(self,in_var, out):
i=0
j=0
while i<len(in_var):
# python 2.x (thanks to @davidak501)
# out[j] = (ord(in_var[i]) + ord(in_var[i+1])) % 62;
# python 3.x
out[j] = (in_var[i] + in_var[i+1]) % 62;
if (out[j] < 10):
out[j] += 48
elif (out[j] < 36):
out[j] += 55;
else:
out[j] += 61
i=i+2
j=j+1
def Dahua_Gen1_hash(self,passw):
# if len(passw)>6:
# debug("Warning: password is more than 6 characters. Hash may be incorrect")
m = hashlib.md5()
m.update(passw.encode("latin-1"))
s=m.digest()
crypt=[]
for b in s:
crypt.append(b)
out2=['']*8
self.compressor(crypt,out2)
data=''.join([chr(a) for a in out2])
return data
#
# END
#
def Basic(self,username, password):
return b64e(username.encode('latin-1') + b':' + password.encode('latin-1'))
#
# Dahua DVRIP random MD5 password hash
#
def Dahua_DVRIP_md5_hash(self,Dahua_random, username, password):
RANDOM_HASH = hashlib.md5((username + ':' + Dahua_random + ':' + self.gen1 if self.gen1 else self.Dahua_Gen1_hash(password)).encode('latin-1')).hexdigest().upper()
return RANDOM_HASH
#
# Dahua random MD5 password hash
#
def Dahua_Gen2_md5_hash(self,Dahua_random, Dahua_realm, username, password):
PWDDB_HASH = self.gen2 if self.gen2 else hashlib.md5((username + ':' + Dahua_realm + ':' + password).encode('latin-1')).hexdigest().upper()
PASS = (username + ':' + Dahua_random + ':' + PWDDB_HASH).encode('latin-1')
RANDOM_HASH = hashlib.md5(PASS).hexdigest().upper()
return RANDOM_HASH
#############################################################################################################
#
# Simple Event Viewer
#
#############################################################################################################
class SimpleEventViewer:
def __init__(self):
log.success("[Simple Event Viewer]")
self.EventConnect()
def EventConnect(self):
try:
self.remote = remote('127.0.0.1', EventOutServerPort, ssl=False, timeout=5)
except (SystemExit) as e:
log.warning("[Simple Event Viewer]: {}".format(e))
if self.remote.connected():
self.remote.close()
return False
self.EventReceive()
return False
def EventReceive(self):
try:
while True:
data = ''
while True:
tmp = len(data)
data += self.remote.recv(numb=8192,timeout=1).decode('latin-1')
if tmp == len(data):
break
if len(data):
self.EventViewer(data)
except (Exception, KeyboardInterrupt, SystemExit) as e:
log.warning("[Simple Event Viewer]: {}".format(e))
if self.remote.connected():
self.remote.close()
return False
def EventViewer(self,data):
# fix the JSON mess
data = fix_json(data)
if not len(data):
log.warning('[Simple Event Viewer]: callback data invalid!\n{}'.format(callback))
return False
for events in data:
log.info('[Event From]: {}\n{}'.format(color(events.get('ipAddr'),GREEN), events))
#############################################################################################################
#
# main init and loop for console I/O
#
# If multiple Consoles is attached to one device, all attached Consoles will receive same output from device
#
#############################################################################################################
class DebugConsole:
def __init__(self):
self.udp_server = False
self.tcp_server = False
self.events = args.events
if args.dump or args.test:
return self.Dump()
self.MainConsole()
#
# Will terminate and restart instances in case of some failure
#
def TerminateDaemons(self,threadName):
time.sleep(1)
if not self.udp_server:
return False
status = log.progress(color("Terminate Daemons thread",YELLOW))
status.success(color("Started",GREEN))
daemon = False
while True:
time.sleep(10)
for session in self.dhConsole:
instance = self.dhConsole.get(session).get('instance')
if instance.terminate and not instance.remote.connected():
ipAddr = self.dhConsole.get(session).get('ipAddr')
daemon = True
break
try:
if daemon:
self.dhConsole.pop(session)
if self.dh == instance:
for session in self.dhConsole:
self.dh = self.dhConsole.get(session).get('instance')
break
del instance
daemon = False
_thread.start_new_thread(self.RestartConnection,("RestartConnection",ipAddr,))
if not len(self.dhConsole):
log.error('Terminate Daemons: No other active sessions')
return False
except (Exception, PwnlibException) as e:
status.failure('{}'.format(e))
return False
#
# Will handle all incoming event traffic on UDP, accepting connections from TCP to relay event traffic
# - The receiving UDP socket is literally connected to sending TCP socket
# - Will also send to internal event handler, to catch some events
# - Since it's unsorted JSON from multiple instanses, the JSON needs to be fixed with 'fix_json()'
#
# Good info
# https://steelkiwi.com/blog/working-tcp-sockets/
def EventInOutServer(self,threadName):
status = log.progress(color("UDP/TCP EventInOutServer listener thread",YELLOW))
try:
self.tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.tcp_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.tcp_server.setblocking(0)
self.tcp_server.bind(('127.0.0.1', EventOutServerPort))
self.tcp_server.listen(10)
self.udp_server = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
self.udp_server.bind(('127.0.0.1', EventInServerPort))
except OSError as e:
self.udp_server = False
self.tcp_server = False
status.failure(color("{}".format(e),RED))
return False
inputs = [self.tcp_server,self.udp_server]
outputs = []
message_queues = {}
try:
status.success(color("Started",GREEN))
while True:
readable, writable, exceptional = select.select(
inputs, outputs, inputs)
for s in readable:
if s is self.tcp_server:
connection, client_address = s.accept()
# log.info('Connection: {}'.format(client_address))
connection.setblocking(0)
inputs.append(connection)
message_queues[connection] = queue.Queue()
else:
if s is not self.udp_server:
data = s.recv(1024)
if s not in outputs:
outputs.append(s)
if not data:
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
del message_queues[s]
else:
data, address = self.udp_server.recvfrom(8192)
# log.info('Incoming data from: {}'.format(address))
if len(data) == 8192:
log.warning('EventInOutServer: LEN == 8192')
print(data)
if data:
self.InternalEventManager(data.decode('latin-1'))
for tmp in message_queues:
message_queues[tmp].put(data)
if tmp not in outputs:
outputs.append(tmp)
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
except queue.Empty:
outputs.remove(s)
else:
s.send(next_msg)
for s in exceptional:
if s in inputs:
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queues[s]
except (Exception) as e:
status.failure('{}'.format(e))
return False
#
# JSON fixing part, then feed 'LocalEventHandler()'
#
def InternalEventManager(self,data):
try:
events = fix_json(data)
for event in events:
self.LocalEventHandler(event)
except (Exception) as e:
log.failure('InternalEventManager: {}'.format(e))
#
# Local event handler
#
def LocalEventHandler(self,data):
try:
ipAddr = data.get('ipAddr')
eventList = data.get('params').get('eventList')
for events in eventList:
if events.get('Action') == 'Start':
#
# Reboot event, remote device is already rebooting and we cannot make clean exit, so just close instance and reschedule connection
#
if events.get('Code') == 'Reboot':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),LYELLOW),
color(ipAddr,GREEN),
color('Reboot',RED),
))
tmp = False
for session in self.dhConsole:
if self.dhConsole.get(session).get('ipAddr') == ipAddr:
log.warning("{}: {} ({})".format(
session,
self.dhConsole.get(session).get('device'),
self.dhConsole.get(session).get('ipAddr'),
))
tmp = self.dhConsole.get(session).get('instance')
tmp.terminate = True
tmp.logout()
break
if tmp:
if tmp == self.dh:
del self.dh
self.dhConsole.pop(session)
if len(self.dhConsole):
for session in self.dhConsole:
self.dh = self.dhConsole.get(session).get('instance')
break
else:
del tmp
self.dhConsole.pop(session)
_thread.start_new_thread(self.RestartConnection,("RestartConnection",ipAddr,))
elif events.get('Code') == 'Exit':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('Exit App',RED),
))
elif events.get('Code') == 'ShutDown':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('ShutDown App',RED),
))
# VTO
elif events.get('Code') == 'AlarmLocal':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('AlarmLocal [Start]',RED),
))
# VTO
elif events.get('Code') == 'ProfileAlarmTransmit':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('ProfileAlarmTransmit [Start]\nAlarmType: {}, DevSrcType: {}, SenseMethod: {}, UserID: {}'.format(
events.get('Data').get('AlarmType'),
events.get('Data').get('DevSrcType'),
events.get('Data').get('SenseMethod'),
events.get('Data').get('UserID'),
),RED),
))
elif events.get('Action') == 'Stop':
# VTO
if events.get('Code') == 'AlarmLocal':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('AlarmLocal [Stop]',GREEN),
))
# VTO
elif events.get('Code') == 'ProfileAlarmTransmit':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),
color('ProfileAlarmTransmit [Stop]\nAlarmType: {}, DevSrcType: {}, SenseMethod: {}, UserID: {}'.format(
events.get('Data').get('AlarmType'),
events.get('Data').get('DevSrcType'),
events.get('Data').get('SenseMethod'),
events.get('Data').get('UserID'),
),GREEN),
))
elif events.get('Action') == 'Pulse':
if events.get('Code') == 'SafetyAbnormal':
log.warning('[{} ({}) ] {}'.format(
color(events.get('Data').get('AbnormalTime') if events.get('Data').get('AbnormalTime') else events.get('Data').get('LocaleTime'),YELLOW),
color(ipAddr,GREEN),