-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGenIPv6OverflowExploit.py
More file actions
140 lines (115 loc) · 6.29 KB
/
GenIPv6OverflowExploit.py
File metadata and controls
140 lines (115 loc) · 6.29 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
import http.server
import socketserver
import json
import threading
import time
import requests
import subprocess
import random
import string
from datetime import datetime
# Уникальный идентификатор эксплойта и создание файла-доказательства
def generate_exploit_id() -> str:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
return f"exploit_{timestamp}_{random_string}.txt"
exploit_proof_file = generate_exploit_id()
# Класс, представляющий структуру IPv6-пакета
class IPv6Packet:
def __init__(self, header_len: int, extensions: list):
self.header_len = header_len
self.extensions = extensions
def calculate_total_length(self) -> int:
# Подсчет общей длины пакета с учетом длины заголовка и всех расширений
return self.header_len + sum(self.extensions)
# Функция обработки пакета и симуляция переполнения буфера
def simulate_packet_processing(packet: IPv6Packet) -> int:
total_length = packet.calculate_total_length()
buffer_size = 64 # Размер выделяемого буфера
buffer = bytearray(buffer_size)
try:
# Попытка записи данных в буфер
for idx in range(total_length):
buffer[idx] = 0xFF
return len(buffer)
except IndexError:
# Обнаружено переполнение буфера
stylish_print(f"[!] ОБНАРУЖЕНО ПЕРЕПОЛНЕНИЕ БУФЕРА!", "red")
stylish_print(f"[*] Файл-доказательство: {exploit_proof_file}", "yellow")
stylish_print("[+] Начата генерация файла...", "green")
# Запись файла-доказательства
with open(exploit_proof_file, 'w') as proof:
proof.write("Файл создан при эксплуатации уязвимости IPv6.")
# Запуск файла в Notepad для демонстрации воздействия
subprocess.Popen(['notepad.exe', exploit_proof_file])
return -1 # Возвращаем -1 как индикатор успешной эксплуатации
# Для вывода информации
def stylish_print(message: str, color: str = "white"):
color_codes = {
"red": "\033[91m",
"green": "\033[92m",
"yellow": "\033[93m",
"white": "\033[0m"
}
print(f"{color_codes.get(color, color_codes['white'])}{message}{color_codes['white']}")
# Класс-обработчик HTTP-запросов для сервера
class CustomHTTPServer(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_len = int(self.headers['Content-Length'])
post_body = self.rfile.read(content_len)
packet_info = json.loads(post_body.decode('utf-8'))
# Создание объекта IPv6-пакета и его обработка
ipv6_packet = IPv6Packet(packet_info['header_length'], packet_info['extension_headers'])
process_result = simulate_packet_processing(ipv6_packet)
# Формирование HTTP-ответа на основе результата обработки пакета
response_payload = {
"status": "success" if process_result != -1 else "exploit_detected",
"buffer_size": process_result,
"proof_file": exploit_proof_file if process_result == -1 else None
}
# Отправка ответа клиенту
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(response_payload).encode('utf-8'))
# Функция запуска HTTP-сервера
def run_server():
with socketserver.TCPServer(("", 8000), CustomHTTPServer) as httpd:
stylish_print("[+] HTTP-сервер запущен на http://localhost:8000", "green")
httpd.serve_forever()
# Функция для тестирования сервера с нормальными и вредоносными пакетами
def test_packets():
time.sleep(1) # Ожидание запуска сервера
server_address = "http://localhost:8000"
# Отправка нормального пакета IPv6
normal_packet = {
"header_length": 40,
"extension_headers": [8, 16]
}
normal_response = requests.post(server_address, json=normal_packet)
stylish_print("Нормальный пакет:", "green")
print(normal_response.json())
# Отправка вредоносного пакета IPv6
exploit_packet = {
"header_length": 40,
"extension_headers": [8, 2**32 - 47] # Большое значение для запуска переполнения
}
try:
exploit_response = requests.post(server_address, json=exploit_packet)
stylish_print("Вредоносный пакет:", "yellow")
print(exploit_response.json())
# Проверка наличия файла-доказательства
if exploit_response.json().get("proof_file"):
stylish_print(f"Создан файл-доказательство: {exploit_response.json()['proof_file']}", "red")
except requests.exceptions.ConnectionError:
stylish_print("Сервер успешно подвергнут эксплуатации при обработке вредоносного пакета.", "red")
if __name__ == "__main__":
# Запуск HTTP-сервера в отдельном потоке
server_thread = threading.Thread(target=run_server)
server_thread.start()
# Запуск тестирования в отдельном потоке
test_thread = threading.Thread(target=test_packets)
test_thread.start()
# Ожидание завершения обоих потоков
server_thread.join()
test_thread.join()