-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonvif_enum.py
More file actions
3598 lines (3154 loc) · 153 KB
/
Copy pathonvif_enum.py
File metadata and controls
3598 lines (3154 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
"""
ONVIF Device Enumerator
Comprehensive enumeration of ONVIF-compatible IP cameras/NVRs.
For authorized security testing and network administration.
Packaged by Jon 'GainSec' Gaines as a standalone research utility.
"""
import argparse
import sys
import json
import re
from dataclasses import dataclass, field
from typing import Optional, Dict, List, Any
import socket
from datetime import datetime
from urllib.parse import urlparse, urlunparse
try:
from onvif import ONVIFCamera, ONVIFError
from zeep.transports import Transport
from requests import Session
except ImportError:
print("[!] Missing dependency: pip install onvif-zeep")
sys.exit(1)
# Set default socket timeout to prevent hangs on unresolvable hostnames
socket.setdefaulttimeout(10)
@dataclass
class ONVIFTarget:
ip: str
port: int = 80
username: str = "admin"
password: str = "admin"
wsdl_dir: Optional[str] = None
@dataclass
class EnumerationResults:
"""Store all enumeration results."""
target: str = ""
device_info: Dict = field(default_factory=dict)
capabilities: Dict = field(default_factory=dict)
services: List = field(default_factory=list)
scopes: List = field(default_factory=list)
network: Dict = field(default_factory=dict)
profiles: List = field(default_factory=list)
video_sources: List = field(default_factory=list)
audio_sources: List = field(default_factory=list)
video_encoders: List = field(default_factory=list)
audio_encoders: List = field(default_factory=list)
osds: List = field(default_factory=list)
ptz: Dict = field(default_factory=dict)
imaging: Dict = field(default_factory=dict)
events: Dict = field(default_factory=dict)
analytics: Dict = field(default_factory=dict)
recording: Dict = field(default_factory=dict)
search: Dict = field(default_factory=dict)
replay: Dict = field(default_factory=dict)
users: List = field(default_factory=list)
certificates: List = field(default_factory=list)
ip_filter: Dict = field(default_factory=dict)
relay_outputs: List = field(default_factory=list)
digital_inputs: List = field(default_factory=list)
system: Dict = field(default_factory=dict)
security: Dict = field(default_factory=dict)
def to_dict(self) -> dict:
return {k: v for k, v in self.__dict__.items() if v}
class ONVIFEnumerator:
"""Comprehensive ONVIF device enumeration."""
def __init__(self, target: ONVIFTarget):
self.target = target
self.camera = None
self.results = EnumerationResults(target=f"{target.ip}:{target.port}")
# Service caches
self._device_service = None
self._media_service = None
self._media2_service = None
self._ptz_service = None
self._imaging_service = None
self._events_service = None
self._analytics_service = None
self._recording_service = None
self._search_service = None
self._replay_service = None
# Extended services
self._doorcontrol_service = None
self._accesscontrol_service = None
self._thermal_service = None
self._deviceio_service = None
self._credential_service = None
self._accessrules_service = None
self._schedule_service = None
self._receiver_service = None
self._provisioning_service = None
def _fix_service_url(self, url: str) -> str:
"""Force service URL to use target IP."""
if not url:
return url
parsed = urlparse(url)
if not parsed.hostname:
return url
# Always force target IP
port = parsed.port if parsed.port else self.target.port
new_netloc = f"{self.target.ip}:{port}"
return urlunparse((parsed.scheme, new_netloc, parsed.path,
parsed.params, parsed.query, parsed.fragment))
def _patch_service_urls(self):
"""Patch all service URLs in camera.xaddrs to use target IP."""
if not hasattr(self.camera, 'xaddrs') or not self.camera.xaddrs:
return
patched = 0
for service_ns, url in list(self.camera.xaddrs.items()):
fixed_url = self._fix_service_url(url)
if fixed_url != url:
self.camera.xaddrs[service_ns] = fixed_url
patched += 1
if patched > 0:
print(f" [+] Patched {patched} service URL(s) to use {self.target.ip}")
def _patch_service_binding(self, service):
"""Patch a service's binding address to use target IP."""
if not service:
return service
try:
# Patch ONVIFService.xaddr
if hasattr(service, 'xaddr'):
service.xaddr = self._fix_service_url(service.xaddr)
# Patch zeep service proxy binding options
if hasattr(service, '_binding_options') and 'address' in service._binding_options:
service._binding_options['address'] = self._fix_service_url(service._binding_options['address'])
# Patch ws_client (zeep client wrapper in python-onvif)
if hasattr(service, 'ws_client'):
ws = service.ws_client
if hasattr(ws, '_binding_options') and 'address' in ws._binding_options:
ws._binding_options['address'] = self._fix_service_url(ws._binding_options['address'])
# Patch zeep client's service binding operations
if hasattr(ws, '_client') and hasattr(ws._client, 'wsdl'):
wsdl = ws._client.wsdl
if hasattr(wsdl, 'bindings'):
for binding in wsdl.bindings.values():
if hasattr(binding, '_operations'):
for op in binding._operations.values():
if hasattr(op, 'location'):
op.location = self._fix_service_url(op.location)
except Exception:
pass
return service
def connect(self) -> bool:
"""Establish connection to ONVIF device."""
print(f"\n[*] Connecting to {self.target.ip}:{self.target.port}")
try:
# Create session with timeout
session = Session()
session.timeout = 10 # 10 second timeout
# Create transport with timeout
transport = Transport(session=session, timeout=10, operation_timeout=15)
# Build kwargs - only include wsdl_dir if specified
kwargs = {
'host': self.target.ip,
'port': self.target.port,
'user': self.target.username,
'passwd': self.target.password,
'transport': transport,
}
if self.target.wsdl_dir:
kwargs['wsdl_dir'] = self.target.wsdl_dir
self.camera = ONVIFCamera(**kwargs)
self._device_service = self.camera.devicemgmt
# Fix service URLs if they contain unresolvable hostnames
self._patch_service_urls()
print("[+] Connected successfully")
return True
except ONVIFError as e:
print(f"[-] ONVIF Error: {e}")
return False
except socket.timeout:
print(f"[-] Connection timed out")
return False
except Exception as e:
print(f"[-] Connection failed: {e}")
return False
# =========================================================================
# DEVICE SERVICE OPERATIONS
# =========================================================================
def get_device_info(self) -> dict:
"""Retrieve device information."""
print("\n[*] Device Information")
print("-" * 50)
try:
info = self._device_service.GetDeviceInformation()
device_info = {
"Manufacturer": getattr(info, 'Manufacturer', 'N/A'),
"Model": getattr(info, 'Model', 'N/A'),
"Firmware": getattr(info, 'FirmwareVersion', 'N/A'),
"Serial": getattr(info, 'SerialNumber', 'N/A'),
"Hardware": getattr(info, 'HardwareId', 'N/A'),
}
for key, value in device_info.items():
print(f" {key}: {value}")
self.results.device_info = device_info
return device_info
except Exception as e:
print(f"[-] Failed to get device info: {e}")
return {}
def get_wsdl_url(self) -> str:
"""Get WSDL URL from device."""
print("\n[*] WSDL URL")
print("-" * 50)
try:
wsdl = self._device_service.GetWsdlUrl()
wsdl_url = getattr(wsdl, 'WsdlUrl', str(wsdl)) if hasattr(wsdl, 'WsdlUrl') else str(wsdl)
print(f" [+] WSDL: {wsdl_url}")
self.results.system['wsdl_url'] = wsdl_url
return wsdl_url
except Exception as e:
print(f"[-] Failed to get WSDL URL: {e}")
return ""
def get_capabilities(self) -> dict:
"""Enumerate device capabilities."""
print("\n[*] Device Capabilities")
print("-" * 50)
try:
caps = self._device_service.GetCapabilities({'Category': 'All'})
capabilities = {}
cap_types = [
('Analytics', ['XAddr', 'RuleSupport', 'AnalyticsModuleSupport']),
('Device', ['XAddr']),
('Events', ['XAddr', 'WSSubscriptionPolicySupport', 'WSPullPointSupport']),
('Imaging', ['XAddr']),
('Media', ['XAddr']),
('PTZ', ['XAddr']),
]
for cap_name, attrs in cap_types:
if hasattr(caps, cap_name) and getattr(caps, cap_name):
cap_obj = getattr(caps, cap_name)
capabilities[cap_name] = {attr: getattr(cap_obj, attr, None) for attr in attrs}
xaddr = getattr(cap_obj, 'XAddr', 'N/A')
print(f" [+] {cap_name}: {xaddr}")
# Extension capabilities
if hasattr(caps, 'Extension') and caps.Extension:
ext = caps.Extension
ext_caps = ['Recording', 'Search', 'Replay', 'DeviceIO', 'Extensions']
for ext_cap in ext_caps:
if hasattr(ext, ext_cap) and getattr(ext, ext_cap):
ext_obj = getattr(ext, ext_cap)
xaddr = getattr(ext_obj, 'XAddr', None)
if xaddr:
capabilities[ext_cap] = {'XAddr': xaddr}
print(f" [+] {ext_cap}: {xaddr}")
self.results.capabilities = capabilities
return capabilities
except Exception as e:
print(f"[-] Failed to get capabilities: {e}")
return {}
def get_services(self) -> list:
"""Get available ONVIF services."""
print("\n[*] Available Services")
print("-" * 50)
try:
services = self._device_service.GetServices({'IncludeCapability': True})
service_list = []
for svc in services:
namespace = getattr(svc, 'Namespace', 'Unknown')
xaddr = getattr(svc, 'XAddr', 'Unknown')
version = getattr(svc, 'Version', None)
ver_str = ""
if version:
major = getattr(version, 'Major', 0)
minor = getattr(version, 'Minor', 0)
ver_str = f" (v{major}.{minor})"
svc_name = namespace.split('/')[-1] if namespace else 'Unknown'
service_list.append({
'name': svc_name,
'namespace': namespace,
'xaddr': xaddr,
'version': ver_str.strip()
})
print(f" [+] {svc_name}{ver_str}: {xaddr}")
self.results.services = service_list
return service_list
except Exception as e:
print(f"[-] Failed to get services: {e}")
return []
def get_service_capabilities(self) -> dict:
"""Get detailed service capabilities."""
print("\n[*] Service Capabilities")
print("-" * 50)
try:
caps = self._device_service.GetServiceCapabilities()
svc_caps = {}
# Network capabilities
if hasattr(caps, 'Network') and caps.Network:
net = caps.Network
svc_caps['Network'] = {
'IPFilter': getattr(net, 'IPFilter', False),
'ZeroConfiguration': getattr(net, 'ZeroConfiguration', False),
'IPVersion6': getattr(net, 'IPVersion6', False),
'DynDNS': getattr(net, 'DynDNS', False),
'Dot11Configuration': getattr(net, 'Dot11Configuration', False),
'HostnameFromDHCP': getattr(net, 'HostnameFromDHCP', False),
'NTP': getattr(net, 'NTP', None),
'DHCPv6': getattr(net, 'DHCPv6', False),
}
print(f" [+] Network: IPFilter={svc_caps['Network']['IPFilter']}, "
f"ZeroConfig={svc_caps['Network']['ZeroConfiguration']}, "
f"IPv6={svc_caps['Network']['IPVersion6']}")
# Security capabilities
if hasattr(caps, 'Security') and caps.Security:
sec = caps.Security
svc_caps['Security'] = {
'TLS1.0': getattr(sec, 'TLS1_0', False),
'TLS1.1': getattr(sec, 'TLS1_1', False),
'TLS1.2': getattr(sec, 'TLS1_2', False),
'OnboardKeyGeneration': getattr(sec, 'OnboardKeyGeneration', False),
'AccessPolicyConfig': getattr(sec, 'AccessPolicyConfig', False),
'DefaultAccessPolicy': getattr(sec, 'DefaultAccessPolicy', False),
'Dot1X': getattr(sec, 'Dot1X', False),
'RemoteUserHandling': getattr(sec, 'RemoteUserHandling', False),
'X509Token': getattr(sec, 'X_509Token', False),
'SAMLToken': getattr(sec, 'SAMLToken', False),
'KerberosToken': getattr(sec, 'KerberosToken', False),
'UsernameToken': getattr(sec, 'UsernameToken', False),
'HttpDigest': getattr(sec, 'HttpDigest', False),
'RELToken': getattr(sec, 'RELToken', False),
'MaxUsers': getattr(sec, 'MaxUsers', None),
'MaxUserNameLength': getattr(sec, 'MaxUserNameLength', None),
'MaxPasswordLength': getattr(sec, 'MaxPasswordLength', None),
}
print(f" [+] Security: TLS1.2={svc_caps['Security']['TLS1.2']}, "
f"UsernameToken={svc_caps['Security']['UsernameToken']}, "
f"MaxUsers={svc_caps['Security']['MaxUsers']}")
# System capabilities
if hasattr(caps, 'System') and caps.System:
sys_cap = caps.System
svc_caps['System'] = {
'DiscoveryResolve': getattr(sys_cap, 'DiscoveryResolve', False),
'DiscoveryBye': getattr(sys_cap, 'DiscoveryBye', False),
'RemoteDiscovery': getattr(sys_cap, 'RemoteDiscovery', False),
'SystemBackup': getattr(sys_cap, 'SystemBackup', False),
'SystemLogging': getattr(sys_cap, 'SystemLogging', False),
'FirmwareUpgrade': getattr(sys_cap, 'FirmwareUpgrade', False),
'HttpFirmwareUpgrade': getattr(sys_cap, 'HttpFirmwareUpgrade', False),
'HttpSystemBackup': getattr(sys_cap, 'HttpSystemBackup', False),
'HttpSystemLogging': getattr(sys_cap, 'HttpSystemLogging', False),
'HttpSupportInformation': getattr(sys_cap, 'HttpSupportInformation', False),
}
print(f" [+] System: Backup={svc_caps['System']['SystemBackup']}, "
f"Logging={svc_caps['System']['SystemLogging']}, "
f"FirmwareUpgrade={svc_caps['System']['FirmwareUpgrade']}")
self.results.system['service_capabilities'] = svc_caps
return svc_caps
except Exception as e:
print(f"[-] Failed to get service capabilities: {e}")
return {}
def get_scopes(self) -> list:
"""Get device scopes (location, name, etc.)."""
print("\n[*] Device Scopes")
print("-" * 50)
try:
scopes = self._device_service.GetScopes()
scope_list = []
for scope in scopes:
scope_def = getattr(scope, 'ScopeDef', 'N/A')
scope_item = getattr(scope, 'ScopeItem', 'N/A')
scope_list.append({'def': scope_def, 'item': scope_item})
# Parse common scope patterns
patterns = [
('onvif.org/name/', 'Name'),
('onvif.org/location/', 'Location'),
('onvif.org/hardware/', 'Hardware'),
('onvif.org/type/', 'Type'),
('onvif.org/Profile/', 'Profile'),
]
printed = False
for pattern, label in patterns:
if pattern in scope_item:
value = scope_item.split(pattern)[-1]
print(f" [+] {label}: {value}")
printed = True
break
if not printed:
print(f" [+] {scope_item}")
self.results.scopes = scope_list
return scope_list
except Exception as e:
print(f"[-] Failed to get scopes: {e}")
return []
def get_discovery_mode(self) -> dict:
"""Get discovery mode settings."""
print("\n[*] Discovery Mode")
print("-" * 50)
discovery = {}
try:
mode = self._device_service.GetDiscoveryMode()
discovery['mode'] = str(mode)
print(f" [+] Discovery Mode: {mode}")
except Exception as e:
print(f"[-] Failed to get discovery mode: {e}")
try:
remote_mode = self._device_service.GetRemoteDiscoveryMode()
discovery['remote_mode'] = str(remote_mode)
print(f" [+] Remote Discovery Mode: {remote_mode}")
except Exception as e:
pass # Not all devices support this
try:
dp_addrs = self._device_service.GetDPAddresses()
if dp_addrs:
discovery['dp_addresses'] = [str(addr) for addr in dp_addrs]
print(f" [+] DP Addresses: {discovery['dp_addresses']}")
except Exception:
pass
self.results.system['discovery'] = discovery
return discovery
def get_endpoint_reference(self) -> str:
"""Get endpoint reference."""
try:
epr = self._device_service.GetEndpointReference()
if epr:
ref = getattr(epr, 'Address', str(epr))
self.results.system['endpoint_reference'] = ref
return ref
except Exception:
pass
return ""
def get_network_interfaces(self) -> list:
"""Enumerate network interfaces."""
print("\n[*] Network Interfaces")
print("-" * 50)
try:
interfaces = self._device_service.GetNetworkInterfaces()
iface_list = []
for iface in interfaces:
token = getattr(iface, 'token', 'N/A')
enabled = getattr(iface, 'Enabled', False)
info = {'token': token, 'enabled': enabled}
if hasattr(iface, 'Info') and iface.Info:
info['name'] = getattr(iface.Info, 'Name', 'N/A')
info['mac'] = getattr(iface.Info, 'HwAddress', 'N/A')
info['mtu'] = getattr(iface.Info, 'MTU', 'N/A')
print(f" [+] {info['name']} ({info['mac']}) - Enabled: {enabled}, MTU: {info['mtu']}")
# IPv4 config
if hasattr(iface, 'IPv4') and iface.IPv4:
info['ipv4'] = {'enabled': getattr(iface.IPv4, 'Enabled', False)}
if hasattr(iface.IPv4, 'Config') and iface.IPv4.Config:
cfg = iface.IPv4.Config
info['ipv4']['dhcp'] = getattr(cfg, 'DHCP', False)
if hasattr(cfg, 'Manual') and cfg.Manual:
for addr in cfg.Manual:
ip = getattr(addr, 'Address', 'N/A')
prefix = getattr(addr, 'PrefixLength', 'N/A')
info['ipv4']['address'] = f"{ip}/{prefix}"
print(f" IPv4: {ip}/{prefix} (DHCP: {info['ipv4']['dhcp']})")
if hasattr(cfg, 'FromDHCP') and cfg.FromDHCP:
dhcp_addr = cfg.FromDHCP
ip = getattr(dhcp_addr, 'Address', 'N/A')
prefix = getattr(dhcp_addr, 'PrefixLength', 'N/A')
print(f" IPv4 (DHCP): {ip}/{prefix}")
# IPv6 config
if hasattr(iface, 'IPv6') and iface.IPv6:
info['ipv6'] = {'enabled': getattr(iface.IPv6, 'Enabled', False)}
if hasattr(iface.IPv6, 'Config') and iface.IPv6.Config:
cfg = iface.IPv6.Config
info['ipv6']['dhcp'] = getattr(cfg, 'DHCP', None)
if hasattr(cfg, 'Manual') and cfg.Manual:
for addr in cfg.Manual:
ip = getattr(addr, 'Address', 'N/A')
prefix = getattr(addr, 'PrefixLength', 'N/A')
info['ipv6']['address'] = f"{ip}/{prefix}"
print(f" IPv6: {ip}/{prefix}")
# Link config
if hasattr(iface, 'Link') and iface.Link:
link = iface.Link
if hasattr(link, 'AdminSettings') and link.AdminSettings:
info['link_speed'] = getattr(link.AdminSettings, 'Speed', 'N/A')
info['duplex'] = getattr(link.AdminSettings, 'Duplex', 'N/A')
info['auto_neg'] = getattr(link.AdminSettings, 'AutoNegotiation', False)
iface_list.append(info)
self.results.network['interfaces'] = iface_list
return iface_list
except Exception as e:
print(f"[-] Failed to get network interfaces: {e}")
return []
def get_network_protocols(self) -> list:
"""Get enabled network protocols."""
print("\n[*] Network Protocols")
print("-" * 50)
try:
protocols = self._device_service.GetNetworkProtocols()
proto_list = []
for proto in protocols:
name = getattr(proto, 'Name', 'Unknown')
enabled = getattr(proto, 'Enabled', False)
ports = []
if hasattr(proto, 'Port') and proto.Port:
ports = [p for p in proto.Port]
proto_list.append({
'name': name,
'enabled': enabled,
'ports': ports
})
port_str = ', '.join(map(str, ports)) if ports else 'N/A'
status = "Enabled" if enabled else "Disabled"
print(f" [+] {name}: {status} (Ports: {port_str})")
self.results.network['protocols'] = proto_list
return proto_list
except Exception as e:
print(f"[-] Failed to get network protocols: {e}")
return []
def get_network_default_gateway(self) -> dict:
"""Get default gateway configuration."""
try:
gw = self._device_service.GetNetworkDefaultGateway()
gateway = {}
if hasattr(gw, 'IPv4Address') and gw.IPv4Address:
gateway['ipv4'] = [str(a) for a in gw.IPv4Address]
if hasattr(gw, 'IPv6Address') and gw.IPv6Address:
gateway['ipv6'] = [str(a) for a in gw.IPv6Address]
if gateway:
self.results.network['gateway'] = gateway
print(f" [+] Gateway: {gateway}")
return gateway
except Exception:
return {}
def get_dns(self) -> dict:
"""Get DNS configuration."""
print("\n[*] DNS Configuration")
print("-" * 50)
dns_info = {}
try:
dns = self._device_service.GetDNS()
dns_info['from_dhcp'] = getattr(dns, 'FromDHCP', False)
dns_info['search_domain'] = []
dns_info['servers'] = []
if hasattr(dns, 'SearchDomain') and dns.SearchDomain:
dns_info['search_domain'] = list(dns.SearchDomain)
print(f" [+] Search Domain: {dns_info['search_domain']}")
if hasattr(dns, 'DNSManual') and dns.DNSManual:
for d in dns.DNSManual:
if hasattr(d, 'IPv4Address') and d.IPv4Address:
dns_info['servers'].append(d.IPv4Address)
print(f" [+] DNS Server: {d.IPv4Address}")
if hasattr(d, 'IPv6Address') and d.IPv6Address:
dns_info['servers'].append(d.IPv6Address)
print(f" [+] DNS Server (v6): {d.IPv6Address}")
if hasattr(dns, 'DNSFromDHCP') and dns.DNSFromDHCP:
for d in dns.DNSFromDHCP:
if hasattr(d, 'IPv4Address') and d.IPv4Address:
print(f" [+] DNS Server (DHCP): {d.IPv4Address}")
self.results.network['dns'] = dns_info
except Exception as e:
print(f"[-] Failed to get DNS: {e}")
return dns_info
def get_ntp(self) -> dict:
"""Get NTP configuration."""
print("\n[*] NTP Configuration")
print("-" * 50)
ntp_info = {}
try:
ntp = self._device_service.GetNTP()
ntp_info['from_dhcp'] = getattr(ntp, 'FromDHCP', False)
ntp_info['servers'] = []
print(f" [+] NTP From DHCP: {ntp_info['from_dhcp']}")
if hasattr(ntp, 'NTPManual') and ntp.NTPManual:
for server in ntp.NTPManual:
srv_type = getattr(server, 'Type', 'Unknown')
if srv_type == 'IPv4':
addr = getattr(server, 'IPv4Address', 'N/A')
elif srv_type == 'IPv6':
addr = getattr(server, 'IPv6Address', 'N/A')
else:
addr = getattr(server, 'DNSname', 'N/A')
ntp_info['servers'].append({'type': srv_type, 'address': addr})
print(f" [+] NTP Server: {addr} ({srv_type})")
if hasattr(ntp, 'NTPFromDHCP') and ntp.NTPFromDHCP:
for server in ntp.NTPFromDHCP:
addr = getattr(server, 'IPv4Address', None) or getattr(server, 'DNSname', 'N/A')
print(f" [+] NTP Server (DHCP): {addr}")
self.results.network['ntp'] = ntp_info
except Exception as e:
print(f"[-] Failed to get NTP: {e}")
return ntp_info
def get_dynamic_dns(self) -> dict:
"""Get Dynamic DNS configuration."""
try:
ddns = self._device_service.GetDynamicDNS()
ddns_info = {
'type': getattr(ddns, 'Type', 'N/A'),
'name': getattr(ddns, 'Name', 'N/A'),
'ttl': getattr(ddns, 'TTL', 'N/A'),
}
if ddns_info['type'] != 'NoUpdate':
print(f" [+] Dynamic DNS: {ddns_info['type']} - {ddns_info['name']}")
self.results.network['dynamic_dns'] = ddns_info
return ddns_info
except Exception:
return {}
def get_zero_configuration(self) -> dict:
"""Get zero configuration (link-local) settings."""
try:
zc = self._device_service.GetZeroConfiguration()
zc_info = {
'interface_token': getattr(zc, 'InterfaceToken', 'N/A'),
'enabled': getattr(zc, 'Enabled', False),
}
if hasattr(zc, 'Addresses') and zc.Addresses:
zc_info['addresses'] = list(zc.Addresses)
print(f" [+] Zero Config: Enabled={zc_info['enabled']}")
self.results.network['zero_config'] = zc_info
return zc_info
except Exception:
return {}
def get_hostname(self) -> dict:
"""Get hostname configuration."""
hostname_info = {}
try:
hostname = self._device_service.GetHostname()
hostname_info = {
'name': getattr(hostname, 'Name', 'N/A'),
'from_dhcp': getattr(hostname, 'FromDHCP', False),
}
print(f" [+] Hostname: {hostname_info['name']} (DHCP: {hostname_info['from_dhcp']})")
self.results.system['hostname'] = hostname_info
except Exception as e:
print(f"[-] Failed to get hostname: {e}")
return hostname_info
def get_system_date_time(self) -> dict:
"""Get system date/time configuration."""
print("\n[*] System Date/Time")
print("-" * 50)
dt_info = {}
try:
dt = self._device_service.GetSystemDateAndTime()
dt_info['type'] = getattr(dt, 'DateTimeType', 'N/A')
dt_info['daylight_savings'] = getattr(dt, 'DaylightSavings', False)
if hasattr(dt, 'TimeZone') and dt.TimeZone:
dt_info['timezone'] = getattr(dt.TimeZone, 'TZ', 'N/A')
print(f" [+] Timezone: {dt_info['timezone']}")
if hasattr(dt, 'UTCDateTime') and dt.UTCDateTime:
utc = dt.UTCDateTime
date_str = f"{utc.Date.Year}-{utc.Date.Month:02d}-{utc.Date.Day:02d}"
time_str = f"{utc.Time.Hour:02d}:{utc.Time.Minute:02d}:{utc.Time.Second:02d}"
dt_info['utc'] = f"{date_str} {time_str}"
print(f" [+] UTC Time: {date_str} {time_str}")
if hasattr(dt, 'LocalDateTime') and dt.LocalDateTime:
local = dt.LocalDateTime
date_str = f"{local.Date.Year}-{local.Date.Month:02d}-{local.Date.Day:02d}"
time_str = f"{local.Time.Hour:02d}:{local.Time.Minute:02d}:{local.Time.Second:02d}"
dt_info['local'] = f"{date_str} {time_str}"
print(f" [+] Local Time: {date_str} {time_str}")
print(f" [+] Time Source: {dt_info['type']}")
self.results.system['datetime'] = dt_info
except Exception as e:
print(f"[-] Failed to get system time: {e}")
return dt_info
def get_system_log(self) -> dict:
"""Get system log (if supported)."""
print("\n[*] System Log")
print("-" * 50)
log_info = {}
try:
# Try to get system log via HTTP
log = self._device_service.GetSystemLog({'LogType': 'System'})
if hasattr(log, 'String') and log.String:
log_info['system'] = log.String[:2000] # Truncate for display
print(f" [+] System Log ({len(log.String)} chars):")
# Show last 10 lines
lines = log.String.strip().split('\n')
for line in lines[-10:]:
print(f" {line[:100]}")
if len(lines) > 10:
print(f" ... ({len(lines) - 10} more lines)")
except Exception as e:
print(f"[-] System log not available: {e}")
try:
log = self._device_service.GetSystemLog({'LogType': 'Access'})
if hasattr(log, 'String') and log.String:
log_info['access'] = log.String[:2000]
print(f" [+] Access Log ({len(log.String)} chars)")
except Exception:
pass
self.results.system['logs'] = log_info
return log_info
def get_system_support_information(self) -> str:
"""Get system support information."""
try:
info = self._device_service.GetSystemSupportInformation()
if hasattr(info, 'String') and info.String:
self.results.system['support_info'] = info.String[:5000]
return info.String
except Exception:
pass
return ""
def get_geo_location(self) -> dict:
"""Get device geo location if available."""
try:
loc = self._device_service.GetGeoLocation()
if loc:
geo = {}
for item in loc:
if hasattr(item, 'Longitude'):
geo['longitude'] = item.Longitude
if hasattr(item, 'Latitude'):
geo['latitude'] = item.Latitude
if hasattr(item, 'Elevation'):
geo['elevation'] = item.Elevation
if geo:
print(f" [+] Geo Location: {geo}")
self.results.system['geo_location'] = geo
return geo
except Exception:
pass
return {}
def get_system_backup(self) -> dict:
"""Get system configuration backup."""
print("\n[*] System Backup")
print("-" * 50)
backup_info = {}
try:
backup = self._device_service.GetSystemBackup()
if backup:
backup_info['files'] = []
for item in backup:
file_info = {}
if hasattr(item, 'Name'):
file_info['name'] = item.Name
print(f" [+] Backup file: {item.Name}")
if hasattr(item, 'Data'):
data = item.Data
if hasattr(data, 'Include'):
file_info['include_href'] = data.Include.href if hasattr(data.Include, 'href') else str(data.Include)
print(f" Include: {file_info['include_href']}")
elif isinstance(data, bytes):
file_info['data_size'] = len(data)
file_info['data_preview'] = data[:500].decode('utf-8', errors='replace')
print(f" Data size: {len(data)} bytes")
print(f" Preview: {file_info['data_preview'][:200]}...")
elif isinstance(data, str):
file_info['data_size'] = len(data)
file_info['data'] = data
print(f" Data size: {len(data)} chars")
print(f" Content: {data[:500]}")
else:
file_info['data_type'] = str(type(data))
file_info['data_str'] = str(data)[:1000]
print(f" Data type: {type(data)}")
print(f" Data: {str(data)[:500]}")
backup_info['files'].append(file_info)
self.results.system['backup'] = backup_info
else:
print(" [-] No backup data returned")
except Exception as e:
print(f" [-] Backup error: {e}")
return backup_info
def restore_system(self, backup_file: str = None) -> bool:
"""Restore system from backup (DANGEROUS - requires confirmation)."""
print("\n[*] System Restore")
print("-" * 50)
print(" [!] WARNING: This operation can modify device configuration!")
if not backup_file:
print(" [-] No backup file provided")
print(" [*] Usage: Pass backup data to restore_system(backup_data)")
return False
try:
# Read backup file if path provided
if isinstance(backup_file, str) and len(backup_file) < 500:
import os
if os.path.exists(backup_file):
with open(backup_file, 'rb') as f:
backup_data = f.read()
print(f" [*] Loaded backup from: {backup_file}")
else:
backup_data = backup_file.encode() if isinstance(backup_file, str) else backup_file
else:
backup_data = backup_file
# Create backup file structure for ONVIF
backup_files = [{
'Name': 'backup.xml',
'Data': backup_data
}]
result = self._device_service.RestoreSystem({'BackupFiles': backup_files})
print(f" [+] Restore result: {result}")
return True
except Exception as e:
print(f" [-] Restore error: {e}")
return False
def get_firmware_upgrade_info(self) -> dict:
"""Check if firmware upgrade is supported and get upload URI."""
print("\n[*] Firmware Upgrade Check")
print("-" * 50)
try:
result = self._device_service.StartFirmwareUpgrade()
upgrade_info = {
'supported': True,
'upload_uri': getattr(result, 'UploadUri', None),
'upload_delay': str(getattr(result, 'UploadDelay', None)),
'expected_down_time': str(getattr(result, 'ExpectedDownTime', None)),
}
print(f" [+] Firmware upgrade SUPPORTED!")
print(f" [+] Upload URI: {upgrade_info['upload_uri']}")
print(f" [+] Upload Delay: {upgrade_info['upload_delay']}")
print(f" [+] Expected Downtime: {upgrade_info['expected_down_time']}")
print(f" [!] WARNING: Device may be waiting for firmware upload now!")
return upgrade_info
except Exception as e:
err_str = str(e).lower()
if 'not implemented' in err_str or 'not supported' in err_str:
print(f" [-] Firmware upgrade NOT supported")
elif 'action not supported' in err_str:
print(f" [-] Firmware upgrade NOT supported (ActionNotSupported)")
else:
print(f" [-] Firmware upgrade error: {e}")
return {'supported': False, 'error': str(e)}
def get_users(self) -> list:
"""Enumerate users (requires admin access)."""
print("\n[*] Users")
print("-" * 50)
try:
users = self._device_service.GetUsers()
user_list = []
for user in users:
username = getattr(user, 'Username', 'N/A')
level = getattr(user, 'UserLevel', 'N/A')
user_list.append({'username': username, 'level': str(level)})
print(f" [+] {username} ({level})")
self.results.users = user_list
return user_list
except Exception as e:
print(f"[-] Failed to enumerate users: {e}")
return []
def get_certificates(self) -> list:
"""Get device certificates."""
print("\n[*] Certificates")
print("-" * 50)
cert_list = []
try:
certs = self._device_service.GetCertificates()
for cert in certs:
cert_id = getattr(cert, 'CertificateID', 'N/A')
cert_info = {
'id': cert_id,
}
if hasattr(cert, 'Certificate') and cert.Certificate:
# Certificate is typically base64 encoded
cert_info['has_certificate'] = True
cert_info['certificate_length'] = len(cert.Certificate)
cert_list.append(cert_info)
print(f" [+] Certificate ID: {cert_id}")
self.results.certificates = cert_list
except Exception as e:
print(f"[-] Failed to get certificates: {e}")
# Get certificate status
try:
status = self._device_service.GetCertificatesStatus()
for s in status:
cert_id = getattr(s, 'CertificateID', 'N/A')
enabled = getattr(s, 'Status', False)
print(f" [+] Certificate {cert_id} Status: {'Enabled' if enabled else 'Disabled'}")
except Exception:
pass
return cert_list
def get_access_policy(self) -> dict:
"""Get access policy configuration."""
try:
policy = self._device_service.GetAccessPolicy()
policy_info = {}
if hasattr(policy, 'User') and policy.User:
policy_info['users'] = []
for user in policy.User:
username = getattr(user, 'Username', 'N/A')
level = getattr(user, 'UserLevel', 'N/A')
policy_info['users'].append({'username': username, 'level': str(level)})
self.results.system['access_policy'] = policy_info
return policy_info
except Exception:
return {}
def get_ip_address_filter(self) -> dict:
"""Get IP address filter configuration."""
print("\n[*] IP Address Filter")
print("-" * 50)
filter_info = {}
try:
ip_filter = self._device_service.GetIPAddressFilter()
filter_info['type'] = getattr(ip_filter, 'Type', 'N/A')
filter_info['addresses'] = []
print(f" [+] Filter Type: {filter_info['type']}")
if hasattr(ip_filter, 'IPv4Address') and ip_filter.IPv4Address:
for addr in ip_filter.IPv4Address:
ip = getattr(addr, 'Address', 'N/A')
prefix = getattr(addr, 'PrefixLength', 32)
filter_info['addresses'].append(f"{ip}/{prefix}")
print(f" [+] IPv4 Filter: {ip}/{prefix}")
if hasattr(ip_filter, 'IPv6Address') and ip_filter.IPv6Address:
for addr in ip_filter.IPv6Address:
ip = getattr(addr, 'Address', 'N/A')