-
Notifications
You must be signed in to change notification settings - Fork 72
/
dahua.py
2621 lines (2219 loc) · 97.6 KB
/
dahua.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 copy
from Crypto.PublicKey import RSA
from OpenSSL import crypto
from pathlib import Path
""" Local imports """
from utils import *
from net import Network
class DahuaFunctions(Network):
""" Dahua instance """
def __init__(
self, rhost=None, rport=None, proto=None, events=False, ssl=False,
relay_host=None, timeout=5, udp_server=True, dargs=None
):
super(DahuaFunctions, self).__init__()
self.rhost = rhost
self.rport = rport
self.proto = proto
self.events = events
self.ssl = ssl
self.relay_host = relay_host
self.timeout = timeout
self.udp_server = udp_server
self.args = dargs
self.debug = dargs.debug
self.debugCalls = dargs.calls # Some internal debugging
self.fuzzServiceDB = {} # Used when fuzzing services
self.DeviceType = '(null)'
self.networkSnifferPath = None
self.networkSnifferID = None
self.dh_sniffer_nic = None
self.attach_only = []
self.Attach = []
self.fuzz_factory = []
#
# Send command to remote console, if not attached just ignore sending
#
def run_cmd(self, msg):
query_args = {
"SID": self.instance_service('console', pull='sid'),
"method": "console.runCmd",
"params": {
"command": msg,
},
"object": self.instance_service('console', pull='object'),
}
if self.console_attach or self.args.force:
dh_data = self.p2p(query_args)
if dh_data is not None:
try:
dh_data = json.loads(dh_data)
except (json.decoder.JSONDecodeError, AttributeError) as e:
log.failure('[runCmd]: {}'.format(repr(e)))
print(dh_data)
return False
if not dh_data.get('result'):
return False
return True
#
# List and caches service(s)
#
def list_service(self, msg, fuzz=False):
cmd = msg.split()
service = None
usage = {
"": "(dump all remote services)",
"<service>": "(dump methods for <service>)",
"all": "(dump all remote services methods)",
"help": "[<service>|all] (\"system\" looks like only have builtin help)",
"[<service>|<all>]": "[save <filename>] (Save JSON to <filename>)",
}
if not len(cmd) == 1:
if cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return True
if len(cmd) == 3 and cmd[1] == 'help':
self.help_service(cmd[2])
return
if not self.RemoteServicesCache:
self.check_for_service('dump')
if not self.RemoteServicesCache:
log.failure('[listService] EZIP perhaps?')
return False
if self.RemoteServicesCache.get('result'):
if not self.args.dump:
service = log.progress('Services')
service.status("Start")
tmp = {}
cache = {}
for count in range(0, len(self.RemoteServicesCache.get('params').get('service'))):
if len(cmd) == 1:
print(self.RemoteServicesCache.get('params').get('service')[count])
elif len(cmd) == 2 or len(cmd) == 4:
query_tmp = {
"method": "",
"params": None,
}
query_tmp.update(
{'method': cmd[1] + '.listMethod' if not cmd[1] == 'all' else
self.RemoteServicesCache.get('params').get('service')[count] + '.listMethod'}
)
if not self.RemoteMethodsCache.get(
cmd[1] if not cmd[1] == 'all'
else self.RemoteServicesCache.get('params').get('service')[count]):
""" 'system.listMethod' not working with multicall """
if query_tmp.get('method') == 'system.listMethod':
dh_data = self.send_call(query_tmp)
tmp.update({query_tmp.get('method').split('.')[0]: dh_data})
dh_data.pop('result')
dh_data.pop('id')
"""SessionID bug: 'method': 'snapManager.listMethod'"""
dh_data.pop('session') if dh_data.get('session') else log.failure(
"[listService] SessionID BUG ({})".format(query_tmp.get('method').split('.')[0]))
self.RemoteMethodsCache.update({query_tmp.get('method').split('.')[0]: dh_data})
if not cmd[1] == 'all':
break
continue
else:
self.send_call(query_tmp, multicall=True)
else:
tmp.update({
cmd[1] if not cmd[1] == 'all'
else self.RemoteServicesCache.get('params').get('service')[count]:
self.RemoteMethodsCache.get(
cmd[1] if not cmd[1] == 'all'
else self.RemoteServicesCache.get('params').get('service')[count])
})
if not self.args.dump:
service.status('{} of {}'.format(
count+1, len(self.RemoteServicesCache.get('params').get('service'))))
if not cmd[1] == 'all':
break
dh_data = self.send_call(None, multicall=True, multicallsend=True)
# print('[list_service]', dh_data)
if dh_data is None:
cache = tmp
elif dh_data is not None:
for method_name in copy.deepcopy(dh_data):
service.status(method_name)
if not dh_data.get(method_name).get('result'):
log.failure("[listService] Failure to fetch: {}".format(method_name.split('.')[0]))
continue
dh_data.get(method_name).pop('result')
dh_data.get(method_name).pop('id')
"""SessionID bug: 'method': 'snapManager.listMethod'"""
if dh_data.get(method_name).get('session'):
dh_data.get(method_name).pop('session')
"""if dh_data.get(method_name).get('session') else log.failure(
"[listService] SessionID BUG ({})".format(method_name.split('.')[0]))"""
cache.update({method_name.split('.')[0]: dh_data.get(method_name)})
self.RemoteMethodsCache.update(cache)
if len(tmp):
cache.update(tmp)
if not self.args.dump:
service.success('Done')
if fuzz:
return self.RemoteMethodsCache
if len(cmd) == 4 and cmd[2] == 'save':
if len(cache):
return self.save_to_file(file_name=cmd[3], dh_data=cache)
log.failure('[listService] (save) Empty')
if not len(cmd) == 1:
if len(cache):
print(json.dumps(cache, indent=4))
else:
log.failure('[listService] (cache) Empty')
return True
else:
log.failure("[listService] {}".format(self.RemoteServicesCache))
return False
#
# Used by 'list_service()' and 'config_members()' to save result to file
#
def save_to_file(self, file_name, dh_data):
if not self.args.force:
path = Path(file_name)
if path.exists():
log.failure("[saveToFile] File {} exist (force with -f at startup)".format(file_name))
return False
try:
with open(file_name, 'w') as fd:
fd.write(json.dumps(dh_data))
log.success("[saveToFile] Saved to: {}".format(file_name))
except IOError as e:
log.failure("[saveToFile] Save {} fail: {}".format(file_name, e))
return False
return True
def help_service(self, msg):
""" In principal useless function, as the only API help seems to cover 'system' only """
cmd = msg.split()
dh_services = self.list_service(msg='service ' + cmd[0], fuzz=True)
for key in dh_services.keys():
for method in dh_services.get(key).get('params').get('method'):
query_args = {
"method": "system.methodHelp",
"params": {
"method_name": method,
},
}
dh_data = self.send_call(query_args)
query_args = {
"method": "system.methodSignature",
"params": {
"method_name": method,
},
}
dh_data2 = self.send_call(query_args)
if not dh_data and not dh_data2:
continue
log.info("Method: {:30}Params: {:20}Description: {}".format(
method,
dh_data2.get('params').get('signature', '(null)'),
dh_data.get('params').get('description', '(null)')
))
def reboot(self, delay=1):
""" 'Hard reboot' of remote device """
query_args = {
"method": "magicBox.reboot",
"params": {
"delay": delay
},
}
dh_data = self.send_call(query_args)
if dh_data.get('result'):
log.success("Trying to force reboot")
else:
log.warning("Trying to force reboot")
self.socket_event.set()
self.logout()
def logout(self):
""" Try graceful logout """
if not self.remote.connected():
log.failure('[logout] Not connected, cannot exit clean')
return False
""" Will exit the instance by check daemon thread """
if self.terminate and self.remote.connected():
self.remote.close()
if self.relay:
self.relay.close()
return False
"""keepAlive failed or terminate
Clean up before we quit, if needed (and can do so)
"""
if not self.event.is_set():
self.cleanup()
""" Stop console (and possible others) """
self.instance_service(clean=True)
query_args = {
"method": "global.logout",
"params": None,
}
dh_data = self.send_call(query_args)
if not dh_data:
log.failure("[logout] global.logout: {}".format(dh_data))
self.remote.close()
if self.relay:
self.relay.close()
return False
if dh_data.get('result'):
log.success("Logout")
self.remote.close()
if self.relay:
self.relay.close()
return True
def config_members(self, msg):
cmd = msg.split()
usage = {
"members": "(show config members)",
"all": "(dump all remote config)",
"<member>": "(dump config for <member>)",
"[<member>|<all>]": "[save <filename>] (Save JSON to <filename>)",
"": "(Use 'ceconfig' in Console to set/get)",
}
if len(cmd) == 1 or cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return False
if cmd[1] == 'members':
query_args = {
"method": "configManager.getMemberNames",
"params": {
"name": "",
},
}
else:
if cmd[1] == 'all':
cmd[1] = 'All'
query_args = {
"method": "configManager.getConfig",
"params": {
"name": cmd[1],
},
}
dh_data = self.send_call(query_args, errorcodes=True)
if not dh_data or not dh_data.get('result'):
log.failure('[config_members] Error: {}'.format(dh_data.get('error') if dh_data else False))
return False
dh_data.pop('id')
dh_data.pop('session')
dh_data.pop('result')
if len(cmd) == 4 and cmd[2] == 'save':
return self.save_to_file(file_name=cmd[3], dh_data=dh_data)
print(json.dumps(dh_data, indent=4))
return
def open_door(self, msg):
""" VTO specific functions (not complete) """
cmd = msg.split()
usage = {
"<n>": {
"open": "(open door <n>)",
"close": "(close door <n>)",
"status": "(status door <n>)",
"finger": "(<Undefined>)",
"password": "(<Undefined>)",
"lift": "(<Undefined> Not working)",
"face": "(<Undefined> Not working)",
}
}
if len(cmd) != 3 or cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return True
method_name = 'accessControl'
try:
door = int(cmd[1])
except ValueError:
log.failure("[open_door] Invalid door number {}".format(cmd[1]))
self.instance_service(method_name, stop=True)
return False
self.instance_service(method_name, params={"channel": door}, start=True)
object_id = self.instance_service(method_name, pull='object')
if not object_id:
return False
if cmd[2] == 'open':
query_args = {
"method": "accessControl.openDoor",
"params": {
"DoorIndex": door,
"ShortNumber": "9901#0",
"Type": "Remote",
"OpenDoorType": "Remote",
# "OpenDoorType": "Dahua",
# "OpenDoorType": "Local",
"UserID": "",
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
if not dh_data:
return
log.info("door: {} {}".format(door, "Success" if dh_data.get('result') else "Failure"))
elif cmd[2] == 'close':
query_args = {
"method": "accessControl.closeDoor", # {"id":21,"result":true,"session":2147483452}
"params": {
# "Type": "Remote",
# "UserID":"",
},
"object": object_id,
}
# print(query_args)
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
elif cmd[2] == 'status': # Seems always to return "Status Close"
"""{"id":8,"params":{"Info":{"status":"Close"}},"result":true,"session":2147483499}"""
query_args = {
"method": "accessControl.getDoorStatus",
"params": {
"DoorState": door,
# "ShortNumber": "9901#0",
# "Type": "Remote",
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
elif cmd[2] == 'finger':
query_args = {
"method": "accessControl.captureFingerprint", # working
"params": {
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
elif cmd[2] == 'lift':
query_args = {
"method": "accessControl.callLift", # Not working
"params": {
"Src": 1,
"DestFloor": 3,
"CallLiftCmd": "",
"CallLiftAction": "",
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
elif cmd[2] == 'password':
query_args = {
"method": "accessControl.modifyPassword", # working
"params": {
"type": "",
"user": "",
"oldPassword": "",
"newPassword": "",
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
elif cmd[2] == 'face':
query_args = {
"method": "accessControl.openDoorFace", # Not working
"params": {
"Status": "",
"MatchInfo": "",
"ImageInfo": "",
},
"object": object_id,
}
dh_data = self.send_call(query_args)
print(query_args)
print(dh_data)
self.instance_service(method_name, stop=True)
return
def telnetd_sshd(self, msg):
cmd = msg.split()
service = None
if cmd[0] == 'telnet':
service = 'Telnet'
elif cmd[0] == 'sshd':
service = 'SSHD'
usage = {
"1": "(enable)",
"0": "(disable)",
}
if len(cmd) == 1 or cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return True
if cmd[1] == '1':
enable = True
elif cmd[1] == '0':
enable = False
else:
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return False
query_args = {
"method": "configManager.getConfig",
"params": {
"name": service,
},
}
dh_data = self.send_call(query_args)
if not dh_data:
return
if dh_data.get('result'):
if dh_data['params']['table']['Enable'] == enable:
log.failure("{} already: {}".format(cmd[0], "Enabled" if enable else "Disabled"))
return
else:
log.failure("Failure: {}".format(dh_data))
return
dh_data['method'] = "configManager.setConfig"
dh_data['params']['table']['Enable'] = enable
dh_data['params']['name'] = service
dh_data['id'] = self.ID
dh_data.pop('result')
dh_data = self.send_call(dh_data, errorcodes=True)
if dh_data.get('result'):
log.success("{}: {}".format(cmd[0], "Enabled" if enable else "Disabled"))
else:
log.failure("Failure: {}".format(dh_data))
return
@staticmethod
def method_banned(msg):
banned = [
"system.listService",
"magicBox.exit",
"magicBox.restart",
"magicBox.shutdown",
"magicBox.reboot",
"magicBox.resetSystem",
"magicBox.config"
"global.login",
"global.logout",
"global.keepAlive",
"global.setCurrentTime",
"DockUser.addUser",
"DockUser.modifyPassword",
"configManager.detach",
"configManager.exportPackConfig", # Exporting config in encrypted TGZ
"configManager.secGetDefault",
"userManager.deleteGroup",
"userManager.setDefault", # will erase all users
"PhotoStation.savePhotoDesign",
"configManager.getMemberNames",
"PerformanceMonitoring.factory.instance", # generates client.notifyPerformanceInfo() callback
"PerformanceMonitoring.attach" # generates client.notifyPerformanceInfo() callback
]
try:
banned.index(msg)
dh_data = help_msg('Banned Match')
dh_data += '{}\n'.format(msg)
log.info(dh_data)
# print('Banned Match: {}'.format(msg))
return True
except ValueError as e:
print(repr(e))
return False
def fuzz_service(self, msg):
""" Under development """
cmd = msg.split()
params = None
usage = {
"check": {
"<service>": "(method for <service>)",
"all": "(all remote services methods)",
},
"factory": "(fuzz factory)"
}
if not len(cmd) >= 2 or cmd[1] == '-h':
log.info('{}'.format(help_all(msg=msg, usage=usage)))
return True
fuzz_result = {}
"""
Code = [
268894211, # Request invalid param!
268959743, # Unknown error! error code was not set in service!
268632080, # pthread error
285278247, # ? - with magicBox.resetSystem
268894208, # Request parse error!
268894212, # Server internal error!
268894209, # get component pointer failed or invalid request! (.object needed!)
]
"""
#
# TODO: Can be more than one in one call
#
dparams = [
"",
"channel", # 0 should always be availible
"pointer",
"name",
"codes",
"service",
"group",
"stream",
"uuid",
"UUID",
"object",
"interval", # PerformanceMonitoring.attach
"composite",
"path",
"DeviceID",
"points",
"Channel",
]
attach_options = [
# {"type":"FormatPatition"},
"Network", # configMember
["All"], # eventManager
0, # for channel.. etc
1,
# "DeviceID1",
"none",
# "xxxxxx",
"System_CONFIG_NETCAMERA_INFO_0", # uuid
"System_CONFIG_NETCAMERA_INFO_", # uuid
["System_CONFIG_NETCAMERA_INFO_0"], # uuid
["System_CONFIG_NETCAMERA_INFO_"], # uuid
"/mnt/sd",
"/dev/mmc0",
"/",
# ["Record FTP"],
# ["Image FTP"],
# ["FTP1"],
# ["ISCSI1"],
# ["NFS1"],
# ["SMB1"],
# ["SFTP1"],
# ["SFTP"],
# ["StorageGroup"],
# ["NAS"],
# ["Remote"],
# ["ReadWrite"],
]
try: # [Main TRY]
if len(cmd) == 3 and cmd[1] == 'check':
check = log.progress('Check')
check.status('Start')
dh_services = self.list_service(msg='service ' + cmd[2], fuzz=True)
for key in dh_services.keys():
check.status(key)
method_name = dh_services.get(key).get('params').get('method')
self.fuzzServiceDB.update({key: {
}})
try:
method_name.index(key + '.factory.instance')
self.fuzzServiceDB.get(key).update({"factory": True})
method_name.index(key + '.attach')
self.fuzzServiceDB.get(key).update({"attach": True})
except ValueError as e:
_error = str(e).split("'")[1]
try:
if _error == key + '.factory.instance':
self.fuzzServiceDB.get(key).update({"factory": False})
elif _error == key + '.attach':
self.fuzzServiceDB.get(key).update({"attach": False})
method_name.index(key + '.attach')
self.fuzzServiceDB.get(key).update({"attach": True})
except ValueError:
self.fuzzServiceDB.get(key).update({"attach": False})
pass
self.fuzz_factory = []
self.Attach = []
self.attach_only = []
for key in dh_services.keys():
if not self.fuzzServiceDB.get(key).get('factory') and not self.fuzzServiceDB.get(key).get('attach'):
if self.fuzzServiceDB.get(key):
self.fuzzServiceDB.pop(key)
continue
elif self.method_banned(key + '.factory.instance'):
if self.fuzzServiceDB.get(key):
self.fuzzServiceDB.pop(key)
continue
elif self.method_banned(key + '.attach'):
if self.fuzzServiceDB.get(key):
self.fuzzServiceDB.pop(key)
continue
if self.fuzzServiceDB.get(key).get('factory'):
self.fuzz_factory.append(key)
if self.fuzzServiceDB.get(key).get('factory') and self.fuzzServiceDB.get(key).get('attach'):
self.Attach.append(key)
if not self.fuzzServiceDB.get(key).get('factory') and self.fuzzServiceDB.get(key).get('attach'):
self.attach_only.append(key)
check.success(
'Factory: {}, Attach: {}, attach_only: {}\n'.format(
len(self.fuzz_factory), len(self.Attach), len(self.attach_only)))
dh_data = '{}'.format(help_msg('Summary'))
dh_data += '{}{}\n'.format(help_msg('Factory'), ', '.join(self.fuzz_factory))
dh_data += '{}{}\n'.format(help_msg('Attach'), ', '.join(self.Attach))
dh_data += '{}{}\n'.format(help_msg('attach_only'), ', '.join(self.attach_only))
log.success(dh_data)
return
elif len(cmd) >= 2 and cmd[1] == 'factory':
try:
if not len(self.fuzz_factory):
log.failure('Factory is Empty')
return False
except AttributeError:
log.failure('Firstly run {} check'.format(cmd[0]))
return False
fuzz_factory = []
if len(cmd) == 2:
fuzz_factory = self.fuzz_factory
elif len(cmd) == 3:
if cmd[2] in self.fuzz_factory:
fuzz_factory.append(cmd[2])
else:
log.failure('"{}" do not exist in factory'.format(cmd[2]))
return False
for method_name in fuzz_factory:
fuzz = log.progress(method_name)
if method_name in self.Attach:
object_id = self.instance_service(method_name, pull='object')
if not object_id:
fuzz.status(color('Working...', YELLOW))
self.instance_service(method_name, dattach=True, start=True, fuzz=True)
object_id = self.instance_service(method_name, pull='object')
if object_id:
fuzz.success(color(str(self.instance_service(method_name, pull='object')), GREEN))
fuzz_result.update(
{method_name: {
"available": True, "params": self.instance_service(method_name, pull='params'),
"attach_params": self.instance_service(method_name, pull='attach_params')
}})
if not object_id:
for key in dparams:
for doptions in attach_options:
params = {key: doptions}
self.instance_service(
method_name, dattach=True, params=params, attach_params=params,
start=True, fuzz=True, multicall=True, multicallsend=False)
self.instance_service(
method_name, dattach=True, attach_params=params, start=True, fuzz=True,
multicall=True, multicallsend=True)
object_id = self.instance_service(method_name, pull='object')
if object_id:
fuzz.success(color(str(self.instance_service(method_name, pull='object')), GREEN))
fuzz_result.update(
{method_name: {
"available": True, "params": self.instance_service(method_name, pull='params'),
"attach_params": self.instance_service(method_name, pull='attach_params')
}})
continue
if not object_id:
fuzz_error = self.fuzzDB.get(method_name).get('sid').get('error')
fuzz.failure(color(json.dumps(fuzz_error), RED))
fuzz_result.update(
{method_name: {
"available": False, "code": fuzz_error.get('code'),
"message": fuzz_error.get('message')}}
)
else:
object_id = self.instance_service(method_name, pull='object')
if not object_id:
fuzz.status(color('Working...', YELLOW))
self.instance_service(method_name, dattach=False, start=True, fuzz=True)
object_id = self.instance_service(method_name, pull='object')
if object_id:
fuzz.success(color(str(self.instance_service(method_name, pull='object')), GREEN))
fuzz_result.update(
{method_name: {
"available": True, "params": self.instance_service(method_name, pull='params'),
"attach_params": self.instance_service(method_name, pull='attach_params')
}})
if not object_id:
for key in dparams:
for doptions in attach_options:
params = {key: doptions}
self.instance_service(
method_name, dattach=False, params=params, start=True, fuzz=True,
multicall=True, multicallsend=False)
self.instance_service(
method_name, dattach=False, start=True, fuzz=True, multicall=True, multicallsend=True)
object_id = self.instance_service(method_name, pull='object')
if object_id:
fuzz.success(color(str(self.instance_service(method_name, pull='object')), GREEN))
fuzz_result.update(
{method_name: {
"available": True, "params": self.instance_service(method_name, pull='params'),
"attach_params": self.instance_service(method_name, pull='attach_params')
}})
continue
if not object_id:
fuzz_error = self.fuzzDB.get(method_name).get('sid').get('error')
fuzz.failure(color(json.dumps(fuzz_error), RED))
fuzz_result.update(
{method_name: {
"available": False, "code": fuzz_error.get('code'),
"message": fuzz_error.get('message')}}
)
self.instance_service(method_name="", list_all=True)
# print(json.dumps(fuzz_result,indent=4))
# print(json.dumps(self.fuzzDB,indent=4))
# self.fuzzServiceDB = {} # Reset
return
else:
log.failure('No such command "{}"'.format(msg))
except KeyboardInterrupt: # [Main TRY]
return False
return
def dev_storage(self):
query_args = {
"method": "storage.getDeviceAllInfo",
"params": None,
}
dh_data = self.send_call(query_args)
if not dh_data:
log.failure("\033[92m[\033[91mStorage: Device not found\033[92m]\033[0m")
return
if dh_data.get('result'):
device_name = dh_data.get('params').get('info')[0].get('Name')
method_name = 'devStorage'
self.instance_service(method_name, params={"name": device_name}, start=True)
object_id = self.instance_service(method_name, pull='object')
if not object_id:
return False
query_args = {
"method": "devStorage.getDeviceInfo",
"params": None,
"object": object_id,
}
dh_data = self.send_call(query_args)
if not dh_data:
if dh_data.get('result'):
dh_data = dh_data.get('params').get('device') # [storage]
log.success("\033[92m[\033[91mStorage: \033[94m{}\033[91m\033[92m]\033[0m\n".format(
dh_data.get('Name', '(null)')))
log.info("Capacity: {}, Media: {}, Bus: {}, State: {}".format(
size(dh_data.get('Capacity', '(null)')),
dh_data.get('Media', '(null)'),
dh_data.get('BUS', '(null)'),
dh_data.get('State', '(null)'),
))
log.info("Model: {}, SerialNo: {}, Firmware: {}".format(
dh_data.get(
'Module', '(null)') if self.DeviceClass == "NVR" else dh_data.get('Model', '(null)'),
dh_data.get(
'SerialNo', '(null)')if self.DeviceClass == "NVR" else dh_data.get('Sn', '(null)'),
dh_data.get('Firmware', '(null)'),
))
for part in range(0, len(dh_data.get('Partitions'))):
tmp = dh_data.get('Partitions')[part]
log.info("{}, FileSystem: {}, Size: {}, Free: {}".format(
tmp.get('Name', '(null)'),
tmp.get('FileSystem', '(null)'),
size(tmp.get('Total', 0), si=True),
size(tmp.get('Remain', 0), si=True),
))
self.instance_service(method_name, stop=True)
def get_encrypt_info(self):
query_args = {
"method": "Security.getEncryptInfo",
"params": None,
}
dh_data = self.send_call(query_args)
if not dh_data:
log.failure("\033[92m[\033[91mEncrypt Info: Fail\033[92m]\033[0m")
return
if dh_data.get('result'):
pub = dh_data.get('params').get('pub').split(",")
log.success(
"\033[92m[\033[91mEncrypt Info\033[92m]\033[0m\nAsymmetric:"
" {}, Cipher: {}, Padding: {}, RSA Exp.: {}\nRSA Modulus:\n{}".format(
dh_data.get('params').get('asymmetric'),
'; '.join(dh_data.get('params').get('cipher', ["(null)"])),
'; '.join(dh_data.get('params').get('AESPadding', ["(null)"])),
pub[1].split(":")[1],
pub[0].split(":")[1],
))
pubkey = RSA.construct((int(pub[0].split(":")[1], 16), int(pub[1].split(":")[1], 16)))
print(pubkey.exportKey().decode('ascii'))
def get_remote_info(self, msg):
cmd = msg.split()
if cmd[0] == 'device':
query_args = {
"method": "magicBox.getSoftwareVersion",
"params": None,
}
self.send_call(query_args, multicall=True)
query_args = {
"method": "magicBox.getProductDefinition",
"params": None,
}
self.send_call(query_args, multicall=True)
query_args = {
"method": "magicBox.getSystemInfo",
"params": None,