Вот тут тебе нужно сделать митигейшон как OVH фильтр, улучши визуальную часть бота,…
- User
Вот тут тебе нужно сделать митигейшон как OVH фильтр, улучши визуальную часть бота, сделай более подходящие смайлики, улучши тексты, надписи, сделай логирование, сделай всё что в твоих силах
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import telepot from telepot.loop import MessageLoop from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton import os import time import threading import subprocess import re import ipaddress # Замените 'YOUR_BOT_TOKEN' на токен вашего бота BOT_TOKEN = '8116567492:AAEoEba4Pr3b987ypPC1iTIKZHzfOWOEOOo' # Файлы для хранения блеклиста и вайтлиста BLACKLIST_FILE = 'blacklist.txt' WHITELIST_FILE = 'whitelist.txt' # Флаг автоматической митигации auto_mitigation = False # Инициализация бота bot = telepot.Bot(BOT_TOKEN) # Разрешенные пользователи (ID Telegram) ALLOWED_USERS = [1568047254] # Замените на ваш Telegram ID # Настройки пороговых значений для DDoS защиты CONNECTION_THRESHOLD = 40 # Максимальное количество соединений с одного IP PACKET_THRESHOLD = 1000 # Максимальное количество пакетов от одного IP BAN_DURATION = 30 # Продолжительность бана в секундах # Словарь для хранения времени блокировки IP banned_ips = {} # Хранение последнего chat_id last_chat_id = None # Главная меню def main_menu(chat_id): global auto_mitigation # Текст кнопки для включения/выключения митигации if auto_mitigation: toggle_button_text = "🛑 Выключить Авто-Митигацию" else: toggle_button_text = "🚀 Включить Авто-Митигацию" keyboard = ReplyKeyboardMarkup(keyboard=[ [KeyboardButton(text="📝 Просмотр Блеклиста"), KeyboardButton(text="📝 Просмотр Вайтлиста")], [KeyboardButton(text="➕ Добавить IP в Блеклист"), KeyboardButton(text="➕ Добавить IP в Вайтлист")], [KeyboardButton(text="➖ Удалить IP из Блеклиста"), KeyboardButton(text="➖ Удалить IP из Вайтлиста")], [KeyboardButton(text=toggle_button_text)], [KeyboardButton(text="📊 Просмотр Логов")] ], resize_keyboard=True) bot.sendMessage(chat_id, "Выберите действие:", reply_markup=keyboard) # Функции управления списками def read_list(file_path): if not os.path.exists(file_path): return [] with open(file_path, 'r') as f: return f.read().splitlines() def write_list(file_path, ip_list): with open(file_path, 'w') as f: for ip in ip_list: f.write(ip + '\n') def add_ip(file_path, ip): ip_list = read_list(file_path) if ip not in ip_list: ip_list.append(ip) write_list(file_path, ip_list) return True return False def remove_ip(file_path, ip): ip_list = read_list(file_path) if ip in ip_list: ip_list.remove(ip) write_list(file_path, ip_list) return True return False # Функции управления iptables def iptables_block_ip(ip): subprocess.call(['iptables', '-A', 'INPUT', '-s', ip, '-j', 'DROP']) def iptables_unblock_ip(ip): subprocess.call(['iptables', '-D', 'INPUT', '-s', ip, '-j', 'DROP']) def iptables_allow_ip(ip): subprocess.call(['iptables', '-I', 'INPUT', '-s', ip, '-j', 'ACCEPT']) def iptables_remove_allow_ip(ip): subprocess.call(['iptables', '-D', 'INPUT', '-s', ip, '-j', 'ACCEPT']) # Функция проверки валидности IP адреса def validate_ip(ip): try: ipaddress.ip_address(ip) return True except ValueError: return False # Функция проверки на фейковый IP адрес def is_fake_ip(ip): try: ip_obj = ipaddress.ip_address(ip) return ip_obj.is_private or ip_obj.is_reserved or ip_obj.is_loopback or ip_obj.is_multicast or ip_obj.is_unspecified except ValueError: return True # Некорректный IP считается фейковым # Обработчик сообщений def handle(msg): global auto_mitigation, last_chat_id content_type, chat_type, chat_id = telepot.glance(msg) # Сохраняем последний chat_id last_chat_id = chat_id # Проверка прав пользователя if chat_id not in ALLOWED_USERS: bot.sendMessage(chat_id, "У вас нет прав для использования этого бота.") return if content_type == 'text': text = msg['text'] if text == '/start': main_menu(chat_id) elif text == '📝 Просмотр Блеклиста': blacklist = read_list(BLACKLIST_FILE) if blacklist: bot.sendMessage(chat_id, "Блеклист:\n" + "\n".join(blacklist)) else: bot.sendMessage(chat_id, "Блеклист пуст.") main_menu(chat_id) elif text == '📝 Просмотр Вайтлиста': whitelist = read_list(WHITELIST_FILE) if whitelist: bot.sendMessage(chat_id, "Вайтлист:\n" + "\n".join(whitelist)) else: bot.sendMessage(chat_id, "Вайтлист пуст.") main_menu(chat_id) elif text == '➕ Добавить IP в Блеклист': bot.sendMessage(chat_id, "Введите IP для добавления в блеклист:") bot._chat_state = 'add_blacklist' elif text == '➕ Добавить IP в Вайтлист': bot.sendMessage(chat_id, "Введите IP для добавления в вайтлист:") bot._chat_state = 'add_whitelist' elif text == '➖ Удалить IP из Блеклиста': bot.sendMessage(chat_id, "Введите IP для удаления из блеклиста:") bot._chat_state = 'remove_blacklist' elif text == '➖ Удалить IP из Вайтлиста': bot.sendMessage(chat_id, "Введите IP для удаления из вайтлиста:") bot._chat_state = 'remove_whitelist' elif text == '🚀 Включить Авто-Митигацию': if not auto_mitigation: auto_mitigation = True bot.sendMessage(chat_id, "Автоматическая митигация включена.") else: bot.sendMessage(chat_id, "Автоматическая митигация уже включена.") main_menu(chat_id) elif text == '🛑 Выключить Авто-Митигацию': if auto_mitigation: auto_mitigation = False bot.sendMessage(chat_id, "Автоматическая митигация выключена.") else: bot.sendMessage(chat_id, "Автоматическая митигация уже выключена.") main_menu(chat_id) elif text == '📊 Просмотр Логов': if os.path.exists('ddos_logs.txt'): with open('ddos_logs.txt', 'r') as f: logs = f.read() if logs: bot.sendMessage(chat_id, "Логи DDoS атак:\n" + logs) else: bot.sendMessage(chat_id, "Логи пусты.") else: bot.sendMessage(chat_id, "Логи отсутствуют.") main_menu(chat_id) else: # Обработка состояний state = getattr(bot, '_chat_state', None) if state == 'add_blacklist': ip = text.strip() if validate_ip(ip): if add_ip(BLACKLIST_FILE, ip): iptables_block_ip(ip) bot.sendMessage(chat_id, f"IP {ip} добавлен в блеклист и заблокирован.") else: bot.sendMessage(chat_id, f"IP {ip} уже в блеклисте.") else: bot.sendMessage(chat_id, f"IP {ip} не является валидным.") bot._chat_state = None main_menu(chat_id) elif state == 'add_whitelist': ip = text.strip() if validate_ip(ip): if add_ip(WHITELIST_FILE, ip): iptables_allow_ip(ip) bot.sendMessage(chat_id, f"IP {ip} добавлен в вайтлист и разрешен.") else: bot.sendMessage(chat_id, f"IP {ip} уже в вайтлисте.") else: bot.sendMessage(chat_id, f"IP {ip} не является валидным.") bot._chat_state = None main_menu(chat_id) elif state == 'remove_blacklist': ip = text.strip() if validate_ip(ip): if remove_ip(BLACKLIST_FILE, ip): iptables_unblock_ip(ip) bot.sendMessage(chat_id, f"IP {ip} удален из блеклиста и разблокирован.") else: bot.sendMessage(chat_id, f"IP {ip} отсутствует в блеклисте.") else: bot.sendMessage(chat_id, f"IP {ip} не является валидным.") bot._chat_state = None main_menu(chat_id) elif state == 'remove_whitelist': ip = text.strip() if validate_ip(ip): if remove_ip(WHITELIST_FILE, ip): iptables_remove_allow_ip(ip) bot.sendMessage(chat_id, f"IP {ip} удален из вайтлиста.") else: bot.sendMessage(chat_id, f"IP {ip} отсутствует в вайтлисте.") else: bot.sendMessage(chat_id, f"IP {ip} не является валидным.") bot._chat_state = None main_menu(chat_id) else: bot.sendMessage(chat_id, "Неверная команда. Используйте меню для управления.") main_menu(chat_id) # Функция автоматической митигации DDoS атак def ddos_mitigation(): global auto_mitigation while True: if auto_mitigation: ip_connection_counts = {} ip_packet_counts = {} # Проверка соединений try: output = subprocess.check_output(['netstat', '-ntu'], stderr=subprocess.DEVNULL).decode() connections = output.strip().split('\n')[2:] # Пропуск заголовков for conn in connections: parts = conn.split() if len(parts) >= 5: src_ip_port = parts[4] src_ip = src_ip_port.rsplit(':', 1)[0] if validate_ip(src_ip): if src_ip not in read_list(WHITELIST_FILE): ip_connection_counts[src_ip] = ip_connection_counts.get(src_ip, 0) + 1 except Exception as e: with open('error_logs.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Ошибка получения соединений: {str(e)}\n") # Проверка пакетов try: if os.path.exists('/proc/net/nf_conntrack'): conntrack_file = '/proc/net/nf_conntrack' elif os.path.exists('/proc/net/ip_conntrack'): conntrack_file = '/proc/net/ip_conntrack' else: raise FileNotFoundError("Файл conntrack не найден.") with open(conntrack_file, 'r') as f: for line in f: match = re.search(r'src=([0-9a-fA-F\.:]+).*packets=(\d+)', line) if match: src_ip = match.group(1) packets = int(match.group(2)) if validate_ip(src_ip): if src_ip not in read_list(WHITELIST_FILE): ip_packet_counts[src_ip] = ip_packet_counts.get(src_ip, 0) + packets except Exception as e: with open('error_logs.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Ошибка чтения conntrack: {str(e)}\n") # Объединение данных и проверка порогов suspicious_ips = set(ip_connection_counts.keys()) | set(ip_packet_counts.keys()) for ip in suspicious_ips: connection_count = ip_connection_counts.get(ip, 0) packet_count = ip_packet_counts.get(ip, 0) if (connection_count > CONNECTION_THRESHOLD or packet_count > PACKET_THRESHOLD) and ip not in banned_ips: if not is_fake_ip(ip): if add_ip(BLACKLIST_FILE, ip): iptables_block_ip(ip) banned_ips[ip] = time.time() with open('ddos_logs.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Заблокирован IP: {ip}, соединений: {connection_count}, пакетов: {packet_count}\n") # Отправка уведомления в Telegram for user_id in ALLOWED_USERS: bot.sendMessage(user_id, f"🚨 Заблокирован IP: {ip}\nСоединений: {connection_count}\nПакетов: {packet_count}") else: # Логирование фейкового IP with open('ddos_logs.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Обнаружен фейковый IP: {ip}, соединений: {connection_count}, пакетов: {packet_count}\n") # Проверка времени бана current_time = time.time() for ip in list(banned_ips.keys()): if current_time - banned_ips[ip] > BAN_DURATION: if remove_ip(BLACKLIST_FILE, ip): iptables_unblock_ip(ip) del banned_ips[ip] with open('ddos_logs.txt', 'a') as f: f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Разблокирован IP: {ip}\n") # Отправка уведомления в Telegram for user_id in ALLOWED_USERS: bot.sendMessage(user_id, f"ℹ️ Разблокирован IP: {ip}") time.sleep(10) # Проверка каждые 10 секунд # Запуск функции автоматической митигации в отдельном потоке mitigation_thread = threading.Thread(target=ddos_mitigation) mitigation_thread.daemon = True mitigation_thread.start() # Запуск бота MessageLoop(bot, handle).run_as_thread() print("🤖 Бот запущен и работает...") # Бесконечный цикл для поддержания работы бота while True: time.sleep(10) - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.