У меня есть 4 кода. Первый код прими к сведению. Остальные три (со 2 по 4) объедини в один:
1 код:
# real_time_ddos_detection.py

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import pyshark
import threading
import time
from collections import defaultdict, deque

# -----------------------------
# 1. Define Fuzzy Logic System
# -----------------------------

# Define the universe variables with ranges
tv = ctrl.Antecedent(np.arange(0, 1001, 1), 'Traffic Volume') # Mbps
pr = ctrl.Antecedent(np.arange(0, 100001, 1), 'Packet Rate') # Packets per second
usip = ctrl.Antecedent(np.arange(0, 10001, 1), 'Unique Source IPs') # Count
ca = ctrl.Antecedent(np.arange(0, 100001, 1), 'Connection Attempts') # Connections per second
er = ctrl.Antecedent(np.arange(0, 101, 1), 'Error Rate') # Percentage

risk = ctrl.Consequent(np.arange(0, 101, 1), 'DDoS Risk') # Percentage

# Membership functions for Traffic Volume
tv['low'] = fuzz.trimf(tv.universe, [0, 0, 250])
tv['medium'] = fuzz.trimf(tv.universe, [100, 500, 900])
tv['high'] = fuzz.trimf(tv.universe, [750, 1000, 1000])

# Membership functions for Packet Rate
pr['low'] = fuzz.trimf(pr.universe, [0, 0, 25000])
pr['medium'] = fuzz.trimf(pr.universe, [10000, 50000, 90000])
pr['high'] = fuzz.trimf(pr.universe, [75000, 100000, 100000])

# Membership functions for Unique Source IPs
usip['few'] = fuzz.trimf(usip.universe, [0, 0, 2500])
usip['moderate'] = fuzz.trimf(usip.universe, [1000, 5000, 9000])
usip['many'] = fuzz.trimf(usip.universe, [7500, 10000, 10000])

# Membership functions for Connection Attempts
ca['low'] = fuzz.trimf(ca.universe, [0, 0, 25000])
ca['medium'] = fuzz.trimf(ca.universe, [10000, 50000, 90000])
ca['high'] = fuzz.trimf(ca.universe, [75000, 100000, 100000])

# Membership functions for Error Rate
er['low'] = fuzz.trimf(er.universe, [0, 0, 25])
er['medium'] = fuzz.trimf(er.universe, [10, 50, 90])
er['high'] = fuzz.trimf(er.universe, [75, 100, 100])

# Membership functions for DDoS Risk
risk['low'] = fuzz.trimf(risk.universe, [0, 0, 25])
risk['medium'] = fuzz.trimf(risk.universe, [10, 50, 90])
risk['high'] = fuzz.trimf(risk.universe, [75, 100, 100])

# Define fuzzy rules
rule1 = ctrl.Rule(tv['high'] & pr['high'], risk['high'])
rule2 = ctrl.Rule(usip['many'] & ca['high'], risk['high'])
rule3 = ctrl.Rule(er['high'], risk['high'])
rule4 = ctrl.Rule(tv['medium'] & pr['medium'], risk['medium'])
rule5 = ctrl.Rule(usip['moderate'] & ca['medium'], risk['medium'])
rule6 = ctrl.Rule(er['medium'], risk['medium'])
rule7 = ctrl.Rule(tv['low'] & pr['low'], risk['low'])
rule8 = ctrl.Rule(usip['few'] & ca['low'], risk['low'])
rule9 = ctrl.Rule(er['low'], risk['low'])
rule10 = ctrl.Rule(tv['high'] & usip['few'], risk['medium'])
rule11 = ctrl.Rule(pr['high'] & ca['low'], risk['medium'])
rule12 = ctrl.Rule(tv['medium'] & er['high'], risk['high'])

# Create control system and simulation
ddos_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6,
rule7, rule8, rule9, rule10, rule11, rule12])

# ----------------------------------------
# 2. Define Real-Time Packet Processing
# ----------------------------------------

# Network interface to capture packets from
INTERFACE = 'VMware Network Adapter VMnet8' # Replace 'eth0' with your network interface name

# Create a live capture object
capture = pyshark.LiveCapture(interface=INTERFACE)

def process_packets():
"""
Captures and processes packets in real-time,
computes network parameters, and evaluates DDoS risk.
"""
# Parameters over a time window
WINDOW_SIZE = 10 # seconds
PACKET_LIMIT = None # Set to None for continuous capture

# Initialize variables
packet_count = 0
start_time = time.time()
packet_sizes = deque()
source_ips = defaultdict(int)
connection_attempts = 0
error_packets = 0

print(f"Starting packet capture on interface '{INTERFACE}'...")

# Start live capture
for packet in capture.sniff_continuously(packet_count=PACKET_LIMIT):
current_time = time.time()
elapsed_time = current_time - start_time

# Update packet count and sizes
packet_count += 1
try:
packet_size = int(packet.length)
packet_sizes.append(packet_size)
except AttributeError:
# Packet length not available
continue

# Extract source IP
try:
src_ip = packet.ip.src
source_ips[src_ip] += 1
except AttributeError:
# Non-IP packet
continue

# Check for TCP SYN packets (new connection attempts)
if 'TCP' in packet:
try:
if packet.tcp.flags_syn == 'True' and packet.tcp.flags_ack == 'False':
connection_attempts += 1
except AttributeError:
pass # Handle packets where flags might not be present

# Check for error packets (e.g., TCP resets)
try:
if packet.tcp.flags_reset == 'True':
error_packets += 1
except AttributeError:
pass

# If the time window has passed, compute parameters
if elapsed_time >= WINDOW_SIZE:
# Compute parameters
total_traffic = sum(packet_sizes) * 8 / (elapsed_time * 1e6) # Mbps
packet_rate = packet_count / elapsed_time
unique_source_ips = len(source_ips)
connection_attempt_rate = connection_attempts / elapsed_time
error_rate = (error_packets / packet_count) * 100 if packet_count > 0 else 0

# Prepare the inputs for the fuzzy logic system
ddos_simulation = ctrl.ControlSystemSimulation(ddos_ctrl)
ddos_simulation.input['Traffic Volume'] = min(total_traffic, 1000)
ddos_simulation.input['Packet Rate'] = min(packet_rate, 100000)
ddos_simulation.input['Unique Source IPs'] = min(unique_source_ips, 10000)
ddos_simulation.input['Connection Attempts'] = min(connection_attempt_rate, 100000)
ddos_simulation.input['Error Rate'] = min(error_rate, 100)

# Compute the DDoS risk
ddos_simulation.compute()
risk_level = ddos_simulation.output['DDoS Risk']

# Print the results
print(f"\nTime Window Ending at: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(current_time))}")
print(f"Traffic Volume: {total_traffic:.2f} Mbps")
print(f"Packet Rate: {packet_rate:.2f} packets/sec")
print(f"Unique Source IPs: {unique_source_ips}")
print(f"Connection Attempts: {connection_attempt_rate:.2f} per sec")
print(f"Error Rate: {error_rate:.2f}%")
print(f"DDoS Risk Level: {risk_level:.2f}%")

# Alert if risk is high
if risk_level > 75:
print("ALERT: High DDoS risk detected!")

# Reset parameters for the next window
start_time = current_time
packet_count = 0
packet_sizes.clear()
source_ips.clear()
connection_attempts = 0
error_packets = 0

# ----------------------------------------
# 3. Main Execution
# ----------------------------------------

if name == "main":
try:
# Start the packet processing in a separate thread
thread = threading.Thread(target=process_packets)
thread.start()
except KeyboardInterrupt:
print("\nStopping packet capture.")
capture.close()

2 код:
import pyshark
import time
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Определяем входные и выходные переменные для нечеткой логики
packet_rate = ctrl.Antecedent(np.arange(0, 2001, 1), 'packet_rate') # Диапазон до 2000 пакетов/с
packet_size = ctrl.Antecedent(np.arange(0, 2001, 1), 'packet_size') # Диапазон до 2000 байт
src_ip_variation = ctrl.Antecedent(np.arange(0, 1001, 1), 'src_ip_variation') # Диапазон до 1000
protocol_type = ctrl.Antecedent(np.arange(0, 3, 1), 'protocol_type') # 0 - TCP, 1 - UDP, 2 - ICMP
dst_port = ctrl.Antecedent(np.arange(0, 65536, 1), 'dst_port') # Диапазон портов
packet_flags = ctrl.Antecedent(np.arange(0, 6, 1), 'packet_flags') # 0 - Нет флагов, 1 - SYN, 2 - ACK, 3 - SYN/ACK, 4 - RST, 5 - FIN

ddos_probability = ctrl.Consequent(np.arange(0, 101, 1), 'ddos_probability')

# Определяем нечеткие множества для входных переменных
packet_rate['low'] = fuzz.trimf(packet_rate.universe, [0, 0, 500])
packet_rate['medium'] = fuzz.trimf(packet_rate.universe, [400, 800, 1200])
packet_rate['high'] = fuzz.trimf(packet_rate.universe, [1000, 2000, 2000])

packet_size['small'] = fuzz.trimf(packet_size.universe, [0, 0, 700])
packet_size['medium'] = fuzz.trimf(packet_size.universe, [600, 1000, 1400])
packet_size['large'] = fuzz.trimf(packet_size.universe, [1300, 2000, 2000])

src_ip_variation['low'] = fuzz.trimf(src_ip_variation.universe, [0, 0, 200])
src_ip_variation['medium'] = fuzz.trimf(src_ip_variation.universe, [150, 400, 650])
src_ip_variation['high'] = fuzz.trimf(src_ip_variation.universe, [600, 1000, 1000])

protocol_type['tcp'] = fuzz.trimf(protocol_type.universe, [0, 0, 0])
protocol_type['udp'] = fuzz.trimf(protocol_type.universe, [1, 1, 1])
protocol_type['icmp'] = fuzz.trimf(protocol_type.universe, [2, 2, 2])

dst_port['common'] = fuzz.trapmf(dst_port.universe, [0, 0, 1024, 1024])
dst_port['uncommon'] = fuzz.trapmf(dst_port.universe, [1023, 65535, 65535, 65535])

packet_flags['none'] = fuzz.trimf(packet_flags.universe, [0, 0, 0])
packet_flags['syn'] = fuzz.trimf(packet_flags.universe, [1, 1, 1])
packet_flags['ack'] = fuzz.trimf(packet_flags.universe, [2, 2, 2])
packet_flags['syn_ack'] = fuzz.trimf(packet_flags.universe, [3, 3, 3])
packet_flags['rst'] = fuzz.trimf(packet_flags.universe, [4, 4, 4])
packet_flags['fin'] = fuzz.trimf(packet_flags.universe, [5, 5, 5])

# Определяем нечеткие множества для выходной переменной
ddos_probability['low'] = fuzz.trimf(ddos_probability.universe, [0, 0, 40])
ddos_probability['medium'] = fuzz.trimf(ddos_probability.universe, [30, 50, 70])
ddos_probability['high'] = fuzz.trimf(ddos_probability.universe, [60, 100, 100])

# Правила нечеткой логики
rule1 = ctrl.Rule(packet_rate['low'] & src_ip_variation['low'], ddos_probability['low'])
rule2 = ctrl.Rule(packet_rate['medium'] & src_ip_variation['medium'], ddos_probability['medium'])
rule3 = ctrl.Rule(packet_rate['high'] | src_ip_variation['high'], ddos_probability['high'])
rule4 = ctrl.Rule(packet_size['large'] & packet_rate['high'], ddos_probability['high'])
rule5 = ctrl.Rule(packet_size['small'] & packet_rate['high'], ddos_probability['medium'])
rule6 = ctrl.Rule(packet_size['small'] & src_ip_variation['high'], ddos_probability['high'])
rule7 = ctrl.Rule(packet_rate['medium'] & src_ip_variation['high'], ddos_probability['high'])
rule8 = ctrl.Rule(packet_rate['high'] & src_ip_variation['medium'], ddos_probability['high'])
rule9 = ctrl.Rule(protocol_type['icmp'], ddos_probability['high'])
rule10 = ctrl.Rule(protocol_type['udp'] & packet_rate['high'], ddos_probability['high'])
rule11 = ctrl.Rule(dst_port['uncommon'] & packet_rate['high'], ddos_probability['medium'])
rule12 = ctrl.Rule(packet_flags['syn'] & packet_rate['high'], ddos_probability['high'])
rule13 = ctrl.Rule(packet_flags['rst'] & packet_rate['high'], ddos_probability['medium'])
rule14 = ctrl.Rule(packet_flags['fin'] & packet_rate['high'], ddos_probability['medium'])

# Создаем контрольную систему
ddos_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8,
rule9, rule10, rule11, rule12, rule13, rule14])

# Функция для анализа трафика
def analyze_traffic(packet_counts, packet_sizes, src_ips, protocol_counts, dst_ports, packet_flags_list):
# Получаем параметры трафика за последние 10 секунд
current_packet_rate = packet_counts / 10 # Средняя скорость пакетов в секунду
if packet_sizes:
current_packet_size = sum(packet_sizes) / len(packet_sizes)
else:
current_packet_size = 0
current_src_ip_variation = len(src_ips)

# Определяем наиболее часто встречающийся протокол
if protocol_counts:
max_protocol = max(protocol_counts, key=protocol_counts.get)
if max_protocol == 'TCP':
current_protocol_type = 0
elif max_protocol == 'UDP':
current_protocol_type = 1
elif max_protocol == 'ICMP':
current_protocol_type = 2
else:
current_protocol_type = 0 # По умолчанию TCP

# Находим наиболее частый порт назначения
if dst_ports:
current_dst_port = max(set(dst_ports), key=dst_ports.count)
else:
current_dst_port = 80 # По умолчанию 80

# Находим наиболее часто встречающийся флаг пакета
if packet_flags_list:
current_packet_flag = max(set(packet_flags_list), key=packet_flags_list.count)
else:
current_packet_flag = 0 # Нет флагов

# Создаем новый объект ControlSystemSimulation
ddos_detect = ctrl.ControlSystemSimulation(ddos_ctrl)

# Вводим значения в нечеткую систему
try:
# Ограничиваем значения в пределах универсальных множеств
ddos_detect.input['packet_rate'] = min(max(current_packet_rate, packet_rate.universe[0]), packet_rate.universe[-1])
ddos_detect.input['packet_size'] = min(max(current_packet_size, packet_size.universe[0]), packet_size.universe[-1])
ddos_detect.input['src_ip_variation'] = min(max(current_src_ip_variation, src_ip_variation.universe[0]), src_ip_variation.universe[-1])
ddos_detect.input['protocol_type'] = current_protocol_type
ddos_detect.input['dst_port'] = min(max(current_dst_port, dst_port.universe[0]), dst_port.universe[-1])
ddos_detect.input['packet_flags'] = current_packet_flag

# Вычисляем
ddos_detect.compute()
except Exception as e:
print(f"Ошибка при вычислении нечеткой системы: {e}")
return

# Получаем вероятность DDoS-атаки
probability = ddos_detect.output.get('ddos_probability', None)
if probability is None:
print("Не удалось получить значение ddos_probability")
else:
print(f"Вероятность DDoS-атаки: {probability:.2f}%")
print(f"Параметры: Средняя скорость пакетов: {current_packet_rate:.2f} п/с, "
f"Средний размер пакета: {current_packet_size:.2f} байт, "
f"Уникальные IP-адреса источников: {current_src_ip_variation}, "
f"Протокол: {max_protocol}, "
f"Порт назначения: {current_dst_port}, "
f"Флаг пакета: {current_packet_flag}\n")

# Основной цикл программы
def main():
while True:
# Глобальные переменные для хранения трафика
packet_counts = 0
packet_sizes = []
src_ips = set()
protocol_counts = {'TCP': 0, 'UDP': 0, 'ICMP': 0}
dst_ports = []
packet_flags_list = []

# Захватываем пакеты в течение 10 секунд
print("Начинаем захват пакетов на 10 секунд...")
capture = pyshark.LiveCapture(interface='VMware Network Adapter VMnet8') # Замените 'your_interface' на ваш интерфейс

# Захватываем пакеты с таймаутом
start_time = time.time()
try:
for packet in capture.sniff_continuously():
current_time = time.time()
if current_time - start_time > 10:
break # Останавливаем захват через 10 секунд

packet_counts += 1
try:
size = int(packet.length)
packet_sizes.append(size)
except AttributeError:
pass

try:
src_ip = packet.ip.src
src_ips.add(src_ip)
except AttributeError:
pass

try:
# Учитываем тип протокола
if hasattr(packet, 'tcp'):
protocol_counts['TCP'] += 1
# Учитываем флаги TCP
flags = int(packet.tcp.flags, 16)
if flags & 0x02: # SYN
packet_flags_list.append(1)
elif flags & 0x10: # ACK
packet_flags_list.append(2)
elif flags & 0x12: # SYN/ACK
packet_flags_list.append(3)
elif flags & 0x04: # RST
packet_flags_list.append(4)
elif flags & 0x01: # FIN
packet_flags_list.append(5)
else:
packet_flags_list.append(0)
# Учитываем порт назначения
dst_ports.append(int(packet.tcp.dstport))
elif hasattr(packet, 'udp'):
protocol_counts['UDP'] += 1
dst_ports.append(int(packet.udp.dstport))
elif hasattr(packet, 'icmp'):
protocol_counts['ICMP'] += 1
except AttributeError:
pass
except KeyboardInterrupt:
print("Захват пакетов прерван пользователем.")
break

print("Захват пакетов завершен. Анализируем трафик...")
# Анализируем собранный трафик
analyze_traffic(packet_counts, packet_sizes, src_ips, protocol_counts, dst_ports, packet_flags_list)
print("Анализ завершен. Повторяем цикл.\n")

# Здесь можно добавить задержку перед следующим циклом, если необходимо
# Например, time.sleep(1)

if name == "main":
try:
main()
except KeyboardInterrupt:
print("Программа остановлена пользователем.")

3 код:

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import pyshark
import time

# Определение входных и выходных переменных
conn_rate_range = np.arange(0, 1001, 1) # скорость входящих соединений (conn/sec)
incomplete_percent_range = np.arange(0, 101, 1) # процент незавершенных соединений (%)
traffic_volume_range = np.arange(0, 1000001, 1) # объем входящего трафика (bytes/sec)
ddos_risk_range = np.arange(0, 101, 1) # риск DDoS-атаки (%)

conn_rate = ctrl.Antecedent(conn_rate_range, 'conn_rate')
incomplete_percent = ctrl.Antecedent(incomplete_percent_range, 'incomplete_percent')
traffic_volume = ctrl.Antecedent(traffic_volume_range, 'traffic_volume')
ddos_risk = ctrl.Consequent(ddos_risk_range, 'ddos_risk')

# Функции принадлежности
conn_rate['low'] = fuzz.trimf(conn_rate.universe, [0, 0, 300])
conn_rate['medium'] = fuzz.trimf(conn_rate.universe, [200, 500, 800])
conn_rate['high'] = fuzz.trimf(conn_rate.universe, [600, 1000, 1000])

incomplete_percent['low'] = fuzz.trimf(incomplete_percent.universe, [0, 0, 20])
incomplete_percent['medium'] = fuzz.trimf(incomplete_percent.universe, [10, 50, 90])
incomplete_percent['high'] = fuzz.trimf(incomplete_percent.universe, [80, 100, 100])

traffic_volume['low'] = fuzz.trimf(traffic_volume.universe, [0, 0, 200000])
traffic_volume['medium'] = fuzz.trimf(traffic_volume.universe, [100000, 500000, 900000])
traffic_volume['high'] = fuzz.trimf(traffic_volume.universe, [800000, 1000000, 1000000])

ddos_risk['low'] = fuzz.trimf(ddos_risk.universe, [0, 0, 30])
ddos_risk['medium'] = fuzz.trimf(ddos_risk.universe, [20, 50, 80])
ddos_risk['high'] = fuzz.trimf(ddos_risk.universe, [70, 100, 100])

# Правила
rule1 = ctrl.Rule(incomplete_percent['high'], ddos_risk['high'])
rule2 = ctrl.Rule(incomplete_percent['medium'] & conn_rate['high'], ddos_risk['high'])
rule3 = ctrl.Rule(incomplete_percent['medium'] & conn_rate['medium'], ddos_risk['medium'])
rule4 = ctrl.Rule(incomplete_percent['low'] & conn_rate['low'], ddos_risk['low'])
rule5 = ctrl.Rule(traffic_volume['high'] & incomplete_percent['medium'], ddos_risk['medium'])
rule6 = ctrl.Rule(traffic_volume['high'] & incomplete_percent['high'], ddos_risk['high'])
rule7 = ctrl.Rule(conn_rate['high'] & incomplete_percent['low'], ddos_risk['medium'])
rule8 = ctrl.Rule(traffic_volume['low'] & incomplete_percent['low'] & conn_rate['low'], ddos_risk['low'])

ddos_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8])

def evaluate_ddos_risk(conn_rate_value, incomplete_percent_value, traffic_volume_value):
ddos_simulation = ctrl.ControlSystemSimulation(ddos_ctrl)

conn_rate_value = max(0, min(conn_rate_value, 1000))
incomplete_percent_value = max(0, min(incomplete_percent_value, 100))
traffic_volume_value = max(0, min(traffic_volume_value, 1000000))

ddos_simulation.input['conn_rate'] = conn_rate_value
ddos_simulation.input['incomplete_percent'] = incomplete_percent_value
ddos_simulation.input['traffic_volume'] = traffic_volume_value

ddos_simulation.compute()

risk = ddos_simulation.output['ddos_risk']
return risk

def process_traffic():
interface = 'VMware Network Adapter VMnet8' # Замените на ваш интерфейс
capture = pyshark.LiveCapture(interface=interface, bpf_filter='tcp')
duration = 10 # Окно в 10 секунд

print("Начало захвата трафика. Нажмите Ctrl+C для остановки.")

try:
while True:
start_time = time.time()
end_time = start_time + duration

new_connections = 0
incomplete_connections = 0
total_connections = 0
total_incoming_traffic = 0

connections = {}

packets = capture.sniff_continuously()
for packet in packets:
current_time = time.time()
if current_time > end_time:
break

try:
if not hasattr(packet, 'tcp') or not hasattr(packet, 'ip'):
continue

ip_src = packet.ip.src
ip_dst = packet.ip.dst
src_port = packet.tcp.srcport
dst_port = packet.tcp.dstport
flags = int(packet.tcp.flags, 16)
size = int(packet.length)

total_incoming_traffic += size

conn_id = (ip_src, src_port, ip_dst, dst_port)

syn_flag = (flags & 0x02) != 0
ack_flag = (flags & 0x10) != 0
rst_flag = (flags & 0x04) != 0
fin_flag = (flags & 0x01) != 0

if syn_flag and not ack_flag:
new_connections += 1
connections[conn_id] = {'status': 'SYN_SENT', 'timestamp': current_time}
elif ack_flag:
if conn_id in connections and connections[conn_id]['status'] == 'SYN_SENT':
connections[conn_id]['status'] = 'ESTABLISHED'
elif fin_flag or rst_flag:
if conn_id in connections:
del connections[conn_id]
except Exception as e:
print(f"Ошибка обработки пакета: {e}")
continue

incomplete_connections = len([c for c in connections.values() if c['status'] != 'ESTABLISHED'])
total_connections = max(new_connections, 1)

incomplete_percent_value = (incomplete_connections / total_connections) * 100
conn_rate_value = new_connections / duration
traffic_volume_value = total_incoming_traffic / duration

ddos_risk_value = evaluate_ddos_risk(conn_rate_value, incomplete_percent_value, traffic_volume_value)

print(f"\n===== Окно с {time.strftime('%H:%M:%S', time.localtime(start_time))} до {time.strftime('%H:%M:%S', time.localtime(end_time))} =====")
print(f"Скорость входящих соединений: {conn_rate_value:.2f} conn/sec")
print(f"Процент незавершенных соединений: {incomplete_percent_value:.2f}%")
print(f"Объем входящего трафика: {traffic_volume_value:.2f} bytes/sec")
print(f"Оценка риска DDoS-атаки: {ddos_risk_value:.2f}%")

# Удаляем старые соединения
connections = {k: v for k, v in connections.items() if current_time - v['timestamp'] < 60}
except KeyboardInterrupt:
print("\nЗахват трафика остановлен.")

if name == 'main':
process_traffic()

4 код:
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
import pyshark
import time
import logging

# Настройка логирования
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Диапазоны значений для переменных
CONN_RATE_RANGE = np.arange(0, 1001, 1) # скорость входящих соединений (conn/sec)
INCOMPLETE_PERCENT_RANGE = np.arange(0, 101, 1) # процент незавершенных соединений (%)
TRAFFIC_VOLUME_RANGE = np.arange(0, 1000001, 1) # объем входящего трафика (bytes/sec)
DDOS_RISK_RANGE = np.arange(0, 101, 1) # риск DDoS-атаки (%)

# Определение входных и выходных переменных
conn_rate = ctrl.Antecedent(CONN_RATE_RANGE, 'conn_rate')
incomplete_percent = ctrl.Antecedent(INCOMPLETE_PERCENT_RANGE, 'incomplete_percent')
traffic_volume = ctrl.Antecedent(TRAFFIC_VOLUME_RANGE, 'traffic_volume')
ddos_risk = ctrl.Consequent(DDOS_RISK_RANGE, 'ddos_risk')

# Функции принадлежности
conn_rate.automf(3, names=['low', 'medium', 'high'])
incomplete_percent.automf(3, names=['low', 'medium', 'high'])
traffic_volume.automf(3, names=['low', 'medium', 'high'])
ddos_risk.automf(3, names=['low', 'medium', 'high'])

# Правила
rules = [
ctrl.Rule(incomplete_percent['high'], ddos_risk['high']),
ctrl.Rule(incomplete_percent['medium'] & conn_rate['high'], ddos_risk['high']),
ctrl.Rule(incomplete_percent['medium'] & conn_rate['medium'], ddos_risk['medium']),
ctrl.Rule(incomplete_percent['low'] & conn_rate['low'], ddos_risk['low']),
ctrl.Rule(traffic_volume['high'] & incomplete_percent['medium'], ddos_risk['medium']),
ctrl.Rule(traffic_volume['high'] & incomplete_percent['high'], ddos_risk['high']),
ctrl.Rule(conn_rate['high'] & incomplete_percent['low'], ddos_risk['medium']),
ctrl.Rule(traffic_volume['low'] & incomplete_percent['low'] & conn_rate['low'], ddos_risk['low'])
]

ddos_ctrl = ctrl.ControlSystem(rules)

# Функция для вычисления риска DDoS-атаки
def evaluate_ddos_risk(conn_rate_value, incomplete_percent_value, traffic_volume_value):
ddos_simulation = ctrl.ControlSystemSimulation(ddos_ctrl)

# Ограничение входных значений
conn_rate_value = np.clip(conn_rate_value, 0, 1000)
incomplete_percent_value = np.clip(incomplete_percent_value, 0, 100)
traffic_volume_value = np.clip(traffic_volume_value, 0, 1000000)

# Передача значений
ddos_simulation.input['conn_rate'] = conn_rate_value
ddos_simulation.input['incomplete_percent'] = incomplete_percent_value
ddos_simulation.input['traffic_volume'] = traffic_volume_value

ddos_simulation.compute()

return ddos_simulation.output['ddos_risk']

# Функция анализа пакетов
def analyze_packet(packet, connections, current_time):
try:
if not hasattr(packet, 'tcp') or not hasattr(packet, 'ip'):
return 0, 0

ip_src = packet.ip.src
ip_dst = packet.ip.dst
src_port = packet.tcp.srcport
dst_port = packet.tcp.dstport
flags = int(packet.tcp.flags, 16)
size = int(packet.length)

conn_id = (ip_src, src_port, ip_dst, dst_port)

syn_flag = (flags & 0x02) != 0
ack_flag = (flags & 0x10) != 0
rst_flag = (flags & 0x04) != 0
fin_flag = (flags & 0x01) != 0

if syn_flag and not ack_flag:
connections[conn_id] = {'status': 'SYN_SENT', 'timestamp': current_time}
return 1, size # Новое соединение
elif ack_flag:
if conn_id in connections and connections[conn_id]['status'] == 'SYN_SENT':
connections[conn_id]['status'] = 'ESTABLISHED'
elif fin_flag or rst_flag:
if conn_id in connections:
del connections[conn_id]

return 0, size

except Exception as e:
logging.error(f"Ошибка обработки пакета: {e}")
return 0, 0

# Функция захвата и анализа трафика
def process_traffic(interface='VMware Network Adapter VMnet8', duration=10):
capture = pyshark.LiveCapture(interface=interface, bpf_filter='tcp')

logging.info("Начало захвата трафика. Нажмите Ctrl+C для остановки.")

try:
while True:
start_time = time.time()
end_time = start_time + duration

# Переменные для текущего окна
new_connections = 0
total_incoming_traffic = 0
connections = {}

# Захват трафика в течение текущего окна времени
for packet in capture.sniff_continuously():
current_time = time.time()
if current_time > end_time:
break

new_conn, size = analyze_packet(packet, connections, current_time)
new_connections += new_conn
total_incoming_traffic += size

# Рассчитываем показатели
incomplete_connections = len([c for c in connections.values() if c['status'] != 'ESTABLISHED'])
total_connections = max(new_connections, 1)

incomplete_percent_value = (incomplete_connections / total_connections) * 100
conn_rate_value = new_connections / duration
traffic_volume_value = total_incoming_traffic / duration

ddos_risk_value = evaluate_ddos_risk(conn_rate_value, incomplete_percent_value, traffic_volume_value)

logging.info(f"\n===== Окно с {time.strftime('%H:%M:%S', time.localtime(start_time))} до {time.strftime('%H:%M:%S', time.localtime(end_time))} =====")
logging.info(f"Скорость входящих соединений: {conn_rate_value:.2f} conn/sec")
logging.info(f"Процент незавершенных соединений: {incomplete_percent_value:.2f}%")
logging.info(f"Объем входящего трафика: {traffic_volume_value:.2f} bytes/sec")
logging.info(f"Оценка риска DDoS-атаки: {ddos_risk_value:.2f}%")

except KeyboardInterrupt:
logging.info("Захват трафика остановлен.")

if name == 'main':
process_traffic()