-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathiotscan.py
More file actions
4947 lines (4032 loc) · 212 KB
/
iotscan.py
File metadata and controls
4947 lines (4032 loc) · 212 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
"""
IoT Scanner with Amplification Detection and Brute Force
"""
import socket
import threading
import ipaddress
import time
import concurrent.futures
from datetime import datetime
import struct
import random
import requests
from requests.auth import HTTPBasicAuth
import ftplib
import telnetlib3
import subprocess
import sys
import base64 # используется в нескольких методах
import asyncio # для CoAP
from aiocoap import Context, Message
from pymodbus.client import ModbusTcpClient
from snap7.client import Client
import paho.mqtt.client as mqtt
import importlib.util
import shutil
import os
from Crypto.Cipher import DES
import pymssql
import vncdotool
# Многие импорты могут отсутствовать:
from aiocoap import Context, Message # CoAP
from pymodbus.client import ModbusTcpClient # Modbus
from snap7.client import Client # Siemens S7
import vncdotool # VNC
import pymssql # Базы данных
import websocket
import json
import mysql.connector
import psycopg2
import hashlib
# Отключение предупреждений о небезопасных HTTPS запросах
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Отключение предупреждений requests
import warnings
warnings.filterwarnings('ignore')
class TestResult:
def __init__(self, ip, port, service, vulnerability="Не обнаружена", credentials="Не найдены"):
self.ip = ip
self.port = port
self.service = service
self.vulnerability = vulnerability
self.credentials = credentials
class AmplificationResult:
def __init__(self, ip, port, protocol, amplification_factor, is_vulnerable):
self.ip = ip
self.port = port
self.protocol = protocol
self.amplification_factor = amplification_factor
self.is_vulnerable = is_vulnerable
class IoTScanner:
def __init__(self, max_workers=None):
self.MAX_BRUTE_TIME = 750
self.protocols = {
"23": "Telnet Router",
"2323": "Telnet Router",
"2000": "Telnet Router",
"22": "SSH Router",
"222": "SSH Router",
"2222": "SSH Router",
"7547": "TR-069",
"8443": "HTTPS Admin",
"8080": "HTTP Admin",
"80": "HTTP Camera",
"443": "HTTPS Camera",
"8088": "HTTP Camera",
"9000": "HTTP Camera",
"8000": "HTTP Camera Alt",
"8888": "HTTP DVR",
"8081": "HTTP",
"8001": "HTTP",
"8008": "HTTP",
"8009": "HTTP",
"8883": "MQTT SSL",
"5060": "SIP", # UDP основной + TCP версия
"5683": "CoAP", # UDP основной + TCP версия
"21": "FTP Router",
"34567": "Hikvision",
"554": "Hikvision",
"8554": "Hikvision",
"37777": "Dahua",
"37778": "Dahua",
"555": "Dahua",
"37775": "Dahua Alt",
"34599": "Hikvision Alt",
"1900": "SSDP",
"53": "DNS",
"11211": "memcached",
"5900": "VNC",
"5901": "VNC Alt",
}
self.amplification_protocols = {
"53": "dns",
"1900": "ssdp",
"3702": "WS-Discovery",
"11211": "memcached",
"389": "cldap",
"443": "quic",
"5683": "CoAP"
}
self.vulnerabilities = {
"default_creds": "Default credentials",
"amplification": "Amplification DDoS"
}
# 🔥 ПРОСТАЯ ЛОГИКА ДЛЯ MAX_WORKERS
if max_workers is not None:
self.Max_workers = max_workers
print(f"[SCANNER] Ручная настройка: Max_workers = {self.Max_workers}")
else:
self.Max_workers = self.get_optimal_max_workers()
print(f"[SCANNER] Автонастройка завершена. Max_workers = {self.Max_workers}")
# Остальной код без изменений
self.ranges = []
self.credentials = []
self.scanned_ips = 0
self.total_ips = 0
self.current_range = ""
self.start_time = None
self.lock = threading.Lock()
self.common_ports = self.protocols
self.amplification_only = False
self.target = None
self.scan_mode = "iot_only" # Добавить значение по умолчанию
print(f"[SCANNER] Автонастройка завершена. Max_workers = {self.Max_workers}")
self.common_ports = self.protocols
self.amplification_only = False # для совместимости
self.target = None # для совместимости
def get_optimal_max_workers(self):
"""Точная автонастройка max_workers по характеристикам системы"""
import multiprocessing
import psutil
import os
import subprocess
import platform
try:
# === ОСНОВНЫЕ ХАРАКТЕРИСТИКИ ===
cpu_cores = multiprocessing.cpu_count()
memory_gb = psutil.virtual_memory().total / (1024 ** 3)
system_type = platform.system()
# === ДЕТАЛЬНАЯ ИНФОРМАЦИЯ О CPU ===
cpu_info = self._get_detailed_cpu_info()
cpu_physical_cores = cpu_info.get('physical_cores', cpu_cores)
cpu_threads = cpu_info.get('logical_cores', cpu_cores)
cpu_freq_max = cpu_info.get('max_freq', 2.0)
cpu_arch = cpu_info.get('architecture', 'x64')
# === ДЕТАЛЬНАЯ ИНФОРМАЦИЯ О ПАМЯТИ ===
memory_info = self._get_detailed_memory_info()
memory_available_gb = memory_info.get('available_gb', memory_gb)
memory_used_percent = memory_info.get('used_percent', 0)
swap_used = memory_info.get('swap_used', False)
# === ДЕТАЛЬНАЯ ИНФОРМАЦИЯ О ДИСКЕ ===
disk_info = self._get_detailed_disk_info()
disk_type = disk_info.get('type', 'HDD')
disk_speed = disk_info.get('speed', 'slow')
free_space_gb = disk_info.get('free_space_gb', 10)
# === ДЕТАЛЬНАЯ ИНФОРМАЦИЯ О СЕТИ ===
network_info = self._get_detailed_network_info()
network_speed = network_info.get('speed', 'medium')
network_latency = network_info.get('latency', 'high')
connection_type = network_info.get('type', 'ethernet')
# === СИСТЕМНАЯ НАГРУЗКА ===
system_load = self._get_system_load()
cpu_load = system_load.get('cpu_percent', 0)
memory_pressure = system_load.get('memory_pressure', 0)
print(f"[SYSTEM] CPU: {cpu_physical_cores}P/{cpu_threads}L {cpu_freq_max:.1f}GHz {cpu_arch}")
print(f"[SYSTEM] RAM: {memory_available_gb:.1f}GB доступно ({memory_used_percent:.1f}% использовано)")
print(f"[SYSTEM] Disk: {disk_type} {disk_speed}, {free_space_gb:.1f}GB свободно")
print(f"[SYSTEM] Network: {connection_type} {network_speed}, latency: {network_latency}")
print(f"[SYSTEM] Load: CPU {cpu_load:.1f}%, Memory pressure: {memory_pressure:.1f}%")
# === БАЗОВЫЙ РАСЧЕТ ПО CPU ===
# Учитываем физические ядра, гипертрединг и частоту
cpu_base = cpu_physical_cores
# Множитель частоты (база 2.0 GHz = 1.0)
freq_multiplier = 1.0 + (cpu_freq_max - 2.0) * 0.3
# Бонус за гипертрединг (30% эффективности)
hyperthreading_bonus = (cpu_threads - cpu_physical_cores) * 0.3 if cpu_threads > cpu_physical_cores else 0
# Архитектурные бонусы
arch_bonus = 1.2 if cpu_arch in ['x86_64', 'AMD64'] else 1.0
base_workers = int(cpu_base * 8 * freq_multiplier * arch_bonus + hyperthreading_bonus * 10)
# === КОРРЕКТИРОВКА ПО ПАМЯТИ ===
# Базовый расчет: 1GB RAM = 15 workers
memory_base = memory_available_gb * 15
# Штраф за использование памяти
memory_penalty = max(0, (memory_used_percent - 70) * 0.5) if memory_used_percent > 70 else 0
# Штраф за использование swap
swap_penalty = 20 if swap_used else 0
memory_workers = memory_base - memory_penalty - swap_penalty
# === КОРРЕКТИРОВКА ПО ДИСКУ ===
disk_multipliers = {
('SSD', 'fast'): 1.3,
('SSD', 'medium'): 1.2,
('SSD', 'slow'): 1.1,
('NVMe', 'fast'): 1.5,
('NVMe', 'medium'): 1.4,
('NVMe', 'slow'): 1.3,
('HDD', 'fast'): 1.0,
('HDD', 'medium'): 0.9,
('HDD', 'slow'): 0.8
}
disk_multiplier = disk_multipliers.get((disk_type, disk_speed), 1.0)
# Штраф за малое свободное место
space_penalty = 0
if free_space_gb < 1:
space_penalty = 30
elif free_space_gb < 5:
space_penalty = 15
# === КОРРЕКТИРОВКА ПО СЕТИ ===
network_multipliers = {
('ethernet', 'fast', 'low'): 1.3,
('ethernet', 'fast', 'medium'): 1.2,
('ethernet', 'fast', 'high'): 1.1,
('ethernet', 'medium', 'low'): 1.1,
('ethernet', 'medium', 'medium'): 1.0,
('ethernet', 'medium', 'high'): 0.9,
('wifi', 'fast', 'low'): 1.1,
('wifi', 'fast', 'medium'): 1.0,
('wifi', 'fast', 'high'): 0.9,
('wifi', 'medium', 'low'): 1.0,
('wifi', 'medium', 'medium'): 0.9,
('wifi', 'medium', 'high'): 0.8,
('mobile', 'fast', 'low'): 0.9,
('mobile', 'fast', 'medium'): 0.8,
('mobile', 'fast', 'high'): 0.7,
}
network_multiplier = network_multipliers.get((connection_type, network_speed, network_latency), 1.0)
# === КОРРЕКТИРОВКА ПО НАГРУЗКЕ СИСТЕМЫ ===
load_penalty = 0
if cpu_load > 80:
load_penalty = 30
elif cpu_load > 60:
load_penalty = 15
elif cpu_load > 40:
load_penalty = 5
if memory_pressure > 80:
load_penalty += 20
elif memory_pressure > 60:
load_penalty += 10
# === ФИНАЛЬНЫЙ РАСЧЕТ ===
optimal = int(
(base_workers + memory_workers) *
disk_multiplier *
network_multiplier -
load_penalty -
space_penalty
)
# === ИНТЕЛЛЕКТУАЛЬНЫЕ ОГРАНИЧЕНИЯ ===
# Ограничения по CPU архитектуре
cpu_limits = {
'ARM': 100, # Raspberry Pi и мобильные CPU
'x86': 200, # Старые 32-битные системы
'x86_64': 800, # Современные 64-битные
'AMD64': 1000 # Серверные системы
}
optimal = min(optimal, cpu_limits.get(cpu_arch, 500))
# Ограничения по операционной системе
os_limits = {
'Windows': 800,
'Linux': 1000,
'Darwin': 600 # macOS
}
optimal = min(optimal, os_limits.get(system_type, 500))
# Ограничения по памяти (строгие)
memory_limits = [
(1, 50), # 1GB RAM - max 50 workers
(2, 100), # 2GB RAM - max 100 workers
(4, 200), # 4GB RAM - max 200 workers
(8, 400), # 8GB RAM - max 400 workers
(12, 500), # 12GB RAM - max 500 workers
(16, 600), # 16GB RAM - max 600 workers
(32, 800), # 32GB RAM - max 800 workers
(64, 1000) # 64GB+ RAM - max 1000 workers
]
for limit_gb, limit_workers in memory_limits:
if memory_available_gb <= limit_gb:
optimal = min(optimal, limit_workers)
break
# Ограничения по количеству ядер
core_limits = [
(1, 50), # 1 core - max 50 workers
(2, 100), # 2 cores - max 100 workers
(4, 300), # 4 cores - max 300 workers
(6, 400), # 6 cores - max 400 workers
(8, 500), # 8 cores - max 500 workers
(10, 600), # 10 cores - max 600 workers
(12, 700), # 12 cores - max 700 workers
(16, 800), # 16 cores - max 800 workers
(32, 1000) # 32+ cores - max 1000 workers
]
for limit_cores, limit_workers in core_limits:
if cpu_physical_cores <= limit_cores:
optimal = min(optimal, limit_workers)
break
# Гарантированный минимум и максимум
optimal = max(optimal, 10) # Минимум 10 workers
optimal = min(optimal, 50000) # Максимум 1000 workers
# Финальная проверка здравого смысла
if optimal > 300 and memory_available_gb < 4:
optimal = 150
if optimal > 500 and cpu_physical_cores < 4:
optimal = 300
print(f"[OPTIMAL] Рассчитано max_workers: {optimal}")
return optimal
except Exception as e:
print(f"[WARNING] Автонастройка не удалась: {e}, используем значение по умолчанию: 100")
return 100
def _get_detailed_cpu_info(self):
"""Детальная информация о CPU"""
import psutil
import platform
import subprocess
try:
cpu_physical = psutil.cpu_count(logical=False) or 1
cpu_logical = psutil.cpu_count(logical=True) or 1
# Частота CPU
cpu_freq = psutil.cpu_freq()
max_freq = cpu_freq.max if cpu_freq else 2.0
# Архитектура
arch = platform.machine()
# Дополнительная информация о CPU
cpu_name = "Unknown"
if platform.system() == "Windows":
try:
output = subprocess.check_output(
"wmic cpu get name",
shell=True,
text=True,
stderr=subprocess.DEVNULL
)
lines = output.strip().split('\n')
if len(lines) > 1:
cpu_name = lines[1].strip()
except:
pass
else:
try:
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('model name'):
cpu_name = line.split(':', 1)[1].strip()
break
except:
pass
return {
'physical_cores': cpu_physical,
'logical_cores': cpu_logical,
'max_freq': max_freq,
'architecture': arch,
'name': cpu_name
}
except:
return {'physical_cores': 1, 'logical_cores': 1, 'max_freq': 2.0, 'architecture': 'x64'}
def _get_detailed_memory_info(self):
"""Детальная информация о памяти"""
import psutil
try:
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
return {
'available_gb': memory.available / (1024 ** 3),
'used_percent': memory.percent,
'swap_used': swap.percent > 10,
'swap_percent': swap.percent
}
except:
return {'available_gb': 4.0, 'used_percent': 50, 'swap_used': False}
def _get_detailed_disk_info(self):
"""Детальная информация о диске"""
import psutil
import os
import subprocess
try:
# Определяем тип диска
disk_type = "HDD"
disk_speed = "medium"
if os.name == 'nt': # Windows
try:
import win32file
drive = os.path.splitdrive(os.path.abspath(__file__))[0]
drive_type = win32file.GetDriveType(drive + "\\")
if drive_type == win32file.DRIVE_FIXED:
# Проверяем SSD через PowerShell
try:
cmd = ["powershell", "-Command",
f"Get-PhysicalDisk | Where-Object {{$_.DeviceID -eq 0}} | Select-Object MediaType"]
result = subprocess.run(cmd, capture_output=True, text=True)
if "SSD" in result.stdout:
disk_type = "SSD"
disk_speed = "fast"
except:
pass
except:
pass
else: # Linux/Mac
try:
for disk in psutil.disk_partitions():
if disk.device == '/':
try:
with open('/sys/block/' + os.path.basename(disk.device) + '/queue/rotational', 'r') as f:
if f.read().strip() == '0':
disk_type = "SSD"
disk_speed = "fast"
except:
# Проверяем через hdparm
try:
result = subprocess.run(
['hdparm', '-I', '/dev/sda'],
capture_output=True, text=True
)
if "Solid State" in result.stdout:
disk_type = "SSD"
disk_speed = "fast"
except:
pass
except:
pass
# Свободное место
disk_usage = psutil.disk_usage('/')
free_space_gb = disk_usage.free / (1024 ** 3)
return {
'type': disk_type,
'speed': disk_speed,
'free_space_gb': free_space_gb
}
except:
return {'type': 'HDD', 'speed': 'medium', 'free_space_gb': 10}
def _get_detailed_network_info(self):
"""Детальная информация о сети"""
import psutil
import subprocess
import platform
try:
connection_type = "ethernet"
network_speed = "medium"
latency = "medium"
# Определяем тип подключения
if platform.system() == "Windows":
try:
result = subprocess.run(
["netsh", "wlan", "show", "interfaces"],
capture_output=True, text=True
)
if "SSID" in result.stdout and "BSSID" in result.stdout:
connection_type = "wifi"
except:
pass
else:
try:
result = subprocess.run(['ip', 'addr'], capture_output=True, text=True)
if 'wlan' in result.stdout or 'wifi' in result.stdout:
connection_type = "wifi"
except:
pass
# Оценка скорости сети через ping до известных серверов
try:
test_servers = ['8.8.8.8', '1.1.1.1', 'google.com']
min_latency = float('inf')
for server in test_servers:
param = '-n' if platform.system().lower() == 'windows' else '-c'
result = subprocess.run(
['ping', param, '2', server],
capture_output=True, text=True
)
if result.returncode == 0:
# Парсим время ping
lines = result.stdout.split('\n')
for line in lines:
if 'time=' in line:
try:
time_str = line.split('time=')[1].split(' ')[0]
latency_ms = float(time_str)
min_latency = min(min_latency, latency_ms)
except:
pass
if min_latency < 20:
latency = "low"
network_speed = "fast"
elif min_latency < 50:
latency = "medium"
network_speed = "medium"
else:
latency = "high"
network_speed = "slow"
except:
pass
return {
'type': connection_type,
'speed': network_speed,
'latency': latency
}
except:
return {'type': 'ethernet', 'speed': 'medium', 'latency': 'medium'}
def _get_system_load(self):
"""Текущая нагрузка системы"""
import psutil
try:
cpu_percent = psutil.cpu_percent(interval=0.5)
memory = psutil.virtual_memory()
# "Давление" памяти (использование + готовность к использованию)
memory_pressure = memory.percent + (memory.available / memory.total * 100) / 2
return {
'cpu_percent': cpu_percent,
'memory_pressure': memory_pressure
}
except:
return {'cpu_percent': 0, 'memory_pressure': 0}
def load_ranges(self):
"""Загрузка диапазонов из range.txt"""
try:
with open('range.txt', 'r') as f:
self.ranges = [line.strip() for line in f if line.strip()]
print(f"[+] Загружено {len(self.ranges)} диапазонов")
except FileNotFoundError:
print("[!] Файл range.txt не найден")
return False
return True
def load_credentials(self):
"""Загрузка логинов/паролей из pass.txt"""
try:
with open('pass.txt', 'r') as f:
for line in f:
line = line.strip()
if line and ':' in line:
login, password = line.split(':', 1)
self.credentials.append((login, password))
print(f"[+] Загружено {len(self.credentials)} пар логин:пароль")
except FileNotFoundError:
print("[!] Файл pass.txt не найден")
return False
return True
def set_scan_mode(self, mode):
"""Установка режима сканирования"""
valid_modes = ["combined", "iot_only", "amplification_only"]
if mode in valid_modes:
self.scan_mode = mode
print(f"[INFO] Установлен режим сканирования: {mode}")
else:
print(f"[ERROR] Неверный режим. Допустимые: {valid_modes}")
def scan_websocket_on_open_ports(self, ip, open_ports):
"""Сканирование WebSocket на открытых портах"""
websocket_results = []
# HTTP порты, которые могут иметь WebSocket
http_ports = ["80", "443", "8080", "7547", "8088", "8888", "8443", "8000", "81", "82", "83", "84", "85", "86", "88", "8008", "8081", "8082", "8090", "8181", "8444", "8843", "9001", "3000", "5000",]
for port_info in open_ports:
port = port_info['port']
# Проверяем только HTTP порты для WebSocket
if port in http_ports:
try:
# Проверяем WebSocket уязвимости
ws_vulnerabilities = self.check_websocket_vulnerabilities(ip, port)
if ws_vulnerabilities:
result = {
'ip': ip,
'port': port,
'service': 'WebSocket Service',
'vulnerabilities': ws_vulnerabilities,
'type': 'websocket'
}
websocket_results.append(result)
# Сохраняем в файл
with open('websocket_results.txt', 'a') as f:
f.write(f"{ip}:{port}:{ws_vulnerabilities}\n")
print(f"[WEBSOCKET] {ip}:{port} - найдены уязвимости: {len(ws_vulnerabilities)}")
except Exception as e:
print(f"[WEBSOCKET-ERROR] {ip}:{port} - ошибка: {e}")
continue
return websocket_results
def check_port(self, ip, port, timeout=10):
"""Проверка открытого порта"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((str(ip), int(port)))
sock.close()
return result == 0
except:
return False
def scan_single_target(self, target):
"""Исправленное сканирование одной цели с включением amplification проверок"""
results = []
# Сканирование обычных IoT сервисов
for port_str, service_name in self.common_ports.items():
port = int(port_str)
result = None
try:
# Проверка доступности порта
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
result_code = sock.connect_ex((target, port))
sock.close()
if result_code == 0: # Порт открыт
# Тестируем сервис
result = self.test_service_by_type(target, port, service_name)
if result:
# Брутфорс учетных данных
creds = self.brute_force_all_protocols(target, port, service_name)
if creds:
result.credentials = creds
result.vulnerability = self.vulnerabilities["default_creds"]
# Проверка других уязвимостей
vuln_found = self.check_actual_vulnerability(target, port, service_name)
if vuln_found and result.vulnerability == "Не обнаружена":
result.vulnerability = vuln_found
# ✅ ДОБАВЛЕНО: Проверка amplification уязвимости
amp_result = self.check_amplification_vulnerability(target, port, service_name)
if amp_result and amp_result.is_vulnerable:
result.vulnerability = f"Amplification ({amp_result.protocol} {amp_result.amplification_factor:.1f}x)"
self.save_amplification_result(amp_result)
# Сохраняем если уязвимо
if (result.credentials != "Не найдены" or
result.vulnerability != "Не обнаружена"):
self.save_result_to_file(result)
results.append(result)
except Exception as e:
continue
# ✅ ДОБАВЛЕНО: Отдельное сканирование amplification протоколов для этой цели
amp_results = self.scan_amplification_protocols(target)
if amp_results:
results.extend(self.convert_amplification_to_test_results(amp_results))
return results
def test_service_by_type(self, ip, port, service):
"""Заглушка для отсутствующего метода"""
return TestResult(ip, port, service)
def save_result_to_file(self, result):
"""Сохранение результатов"""
with open('results.txt', 'a') as f:
f.write(f"{result.ip}:{result.port}:{result.service}\n")
def run_scan(self):
"""Запуск сканирования в зависимости от выбранного режима"""
if self.scan_mode == "amplification_only":
print("[MODE] Режим: Only Amplification")
return self.scan_amplification_only()
elif self.scan_mode == "iot_only":
print("[MODE] Режим: Only IoT")
return self.scan_iot_only()
else:
print("[MODE] Режим: Combined (IoT + Amplification)")
return self.scan_combined()
def scan_combined(self):
"""КОРРЕКТНОЕ комбинированное сканирование"""
print("[INFO] Запуск КОРРЕКТНОГО комбинированного сканирования...")
all_results = []
for cidr_range in self.ranges:
try:
network = ipaddress.ip_network(cidr_range, strict=False)
print(f"[RANGE] Сканирование диапазона: {cidr_range}")
for ip in network.hosts():
# 🔥 ОДНОВРЕМЕННОЕ сканирование обоих типов
ip_str = str(ip)
# 1. Amplification сканирование (UDP)
amp_results = self.scan_amplification_for_ip(ip_str)
# 2. IoT сканирование (TCP)
iot_results = self.scan_iot_for_ip(ip_str)
# 3. WebSocket сканирование
ws_results = self.scan_websocket_services(ip_str)
# Сохраняем все результаты
if amp_results:
all_results.extend(amp_results)
print(f"[AMPLIFICATION] {ip_str}: найдено {len(amp_results)} уязвимостей")
if iot_results:
all_results.extend(iot_results)
print(f"[IOT] {ip_str}: найдено {len(iot_results)} сервисов")
if ws_results:
all_results.extend(ws_results)
print(f"[WEBSOCKET] {ip_str}: найдено {len(ws_results)} endpoints")
except Exception as e:
print(f"[ERROR] Ошибка в диапазоне {cidr_range}: {e}")
continue
return all_results
def scan_iot_only(self):
"""Сканирование только IoT протоколов"""
print("[INFO] Запуск сканирования IoT протоколов...")
results = []
for cidr_range in self.ranges:
try:
network = ipaddress.ip_network(cidr_range, strict=False)
for ip in network.hosts():
# Сканируем IoT сервисы
iot_results = self.scan_iot_for_ip(ip)
# Сканируем WebSocket сервисы
ws_results = self.scan_websocket_services(ip)
# 🔥 ДОБАВЛЯЕМ ОБА типа результатов
results.extend(iot_results)
results.extend(ws_results) # ✅ ЭТОЙ СТРОКИ НЕ ХВАТАЛО!
except Exception as e:
print(f"[ERROR] Ошибка в диапазоне {cidr_range}: {e}")
return results
def check_amplification_vulnerability(self, ip, port, protocol):
"""Проверка конкретного порта на amplification уязвимость"""
amplification_protocols = {
53: self.test_dns_amplification,
123: self.test_ntp_amplification,
1900: self.test_ssdp_amplification,
389: self.test_cldap_amplification,
11211: self.test_memcached_amplification,
161: self.test_snmp_amplification,
19: self.test_chargen_amplification,
17: self.test_qotd_amplification,
5683: self.test_coap_amplification,
443: self.test_quic_amplification,
69: self.test_tftp_amplification
}
if port in amplification_protocols:
return amplification_protocols[port](ip, port)
return None
def convert_amplification_to_test_results(self, amplification_results):
"""Конвертирует AmplificationResult в TestResult для единообразного вывода"""
test_results = []
for amp_result in amplification_results:
if amp_result.is_vulnerable:
test_result = TestResult(
ip=amp_result.ip,
port=amp_result.port,
service=f"{amp_result.protocol} Amplification",
vulnerability=f"Amplification DDoS ({amp_result.amplification_factor:.1f}x)",
credentials="Не найдены"
)
test_results.append(test_result)
return test_results
def check_udp_port(self, ip, port, timeout=10):
"""Корректная проверка UDP портов"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timeout)
query = self.create_protocol_specific_query(port)
if not query:
return False
sock.sendto(query, (str(ip), port))
try:
response, addr = sock.recvfrom(1024)
# ✅ Проверяем, что ответ валиден для протокола
return self.validate_protocol_response(port, response)
except socket.timeout:
# ✅ Для UDP таймаут - нормальная ситуация
return False
except Exception:
return False
def test_wsdiscovery_amplification(self, ip, port=3702):
"""Тестирование WS-Discovery amplification (50-150x) - ОБНОВЛЕННАЯ ВЕРСИЯ"""
try:
print(f"[WS-DISCOVERY] Тестирование {ip}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(5)
# WS-Discovery probe запрос
wsdiscovery_probe = self.create_wsdiscovery_probe()
sent_size = len(wsdiscovery_probe)
print(f"[WS-DISCOVERY] Отправка {sent_size} байт на {ip}:{port}")
start_time = time.time()
sock.sendto(wsdiscovery_probe, (str(ip), port))
try:
response, addr = sock.recvfrom(8192) # Большой буфер для WS-Discovery
received_size = len(response)
response_time = time.time() - start_time
sock.close()
# Проверяем валидность ответа
if self.validate_wsdiscovery_response(response):
amp_factor = received_size / sent_size
print(f"[WS-DISCOVERY] Успех: {sent_size} -> {received_size} байт (x{amp_factor:.2f}) за {response_time:.2f}с")
return AmplificationResult(
ip=ip, port=port, protocol="WS-Discovery",
amplification_factor=amp_factor,
is_vulnerable=amp_factor >= 20.0 # WS-Discovery обычно дает высокий коэффициент
)
else:
print(f"[WS-DISCOVERY] Невалидный ответ от {ip}:{port}")
except socket.timeout:
print(f"[WS-DISCOVERY] Таймаут для {ip}:{port}")
except Exception as e:
print(f"[WS-DISCOVERY] Ошибка получения ответа: {e}")
except Exception as e:
print(f"[WS-DISCOVERY] Критическая ошибка: {e}")
return AmplificationResult(ip=ip, port=port, protocol="WS-Discovery", amplification_factor=0, is_vulnerable=False)
def test_mdns_amplification(self, ip, port=5353):
"""Тестирование mDNS amplification (2-50x)"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(5)
# mDNS query для широкого диапазона сервисов
mdns_query = self.create_mdns_amplification_query()
sent_size = len(mdns_query)
# Отправляем на multicast адрес или напрямую
sock.sendto(mdns_query, (str(ip), port))
response, addr = sock.recvfrom(4096)
received_size = len(response)
sock.close()
# Проверяем валидность mDNS ответа
if self.validate_mdns_response(response):
amp_factor = received_size / sent_size
return AmplificationResult(
ip=ip, port=port, protocol="mDNS",
amplification_factor=amp_factor,
is_vulnerable=amp_factor >= 5.0
)
except Exception as e:
pass
return AmplificationResult(ip=ip, port=port, protocol="mDNS", amplification_factor=0, is_vulnerable=False)
def create_mdns_amplification_query(self):
"""Создает mDNS запрос для amplification тестирования"""
transaction_id = random.randint(0, 65535)
flags = 0x0000 # Standard query
questions = 5 # Множество вопросов для усиления
answers = 0
authority_rrs = 0
additional_rrs = 0
header = struct.pack('>HHHHHH', transaction_id, flags, questions,
answers, authority_rrs, additional_rrs)
# Несколько PTR запросов для разных сервисов
services = [
"_services._dns-sd._udp.local",
"_http._tcp.local",
"_printer._tcp.local",
"_ssh._tcp.local",
"_ipp._tcp.local"
]
questions_section = b''
for service in services:
# QNAME
parts = service.split('.')
for part in parts:
if part: # Пропускаем пустые части
questions_section += struct.pack('B', len(part)) + part.encode()
questions_section += b'\x00'
# QTYPE = PTR (12), QCLASS = IN (1) с unicast response
questions_section += struct.pack('>HH', 12, 0x8001)
return header + questions_section
def validate_mdns_response(self, response):
"""Валидация mDNS ответа"""
try:
if len(response) < 12: