#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import requests
import re
import string
import random
import json
import time
import hashlib
import threading
from datetime import datetime
from multiprocessing.dummy import Pool
from colorama import Fore, init

init(autoreset=True)

fr = Fore.RED
fc = Fore.CYAN
fw = Fore.WHITE
fg = Fore.GREEN
fm = Fore.MAGENTA

requests.urllib3.disable_warnings()

# ============= ULTRA OPTIMIZED ANTI-BAN HEADER SYSTEM =============
class OptimizedHeaderSystem:
    """Lightweight but effective anti-ban system"""
    
    def __init__(self):
        self.counter = 0
        self.lock = threading.Lock()
        self.domain_timings = {}
        
    def get_headers(self):
        """Fast header generation with minimal overhead"""
        with self.lock:
            self.counter += 1
        
        # Faster browser rotation
        browsers = [
            ('Chrome/121.0.0.0', 'Windows NT 10.0; Win64; x64'),
            ('Chrome/120.0.0.0', 'Macintosh; Intel Mac OS X 10_15_7'),
            ('Firefox/122.0', 'Windows NT 10.0; Win64; x64'),
            ('Firefox/121.0', 'X11; Linux x86_64'),
            ('Safari/17.2', 'Macintosh; Intel Mac OS X 10_15_7')
        ]
        
        browser, platform = browsers[self.counter % len(browsers)]
        
        if 'Chrome' in browser:
            ua = f'Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) {browser} Safari/537.36'
        elif 'Firefox' in browser:
            ua = f'Mozilla/5.0 ({platform}; rv:{browser.split("/")[1]}) Gecko/20100101 Firefox/{browser.split("/")[1]}'
        else:
            ua = f'Mozilla/5.0 ({platform}) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/{browser.split("/")[1]} Safari/605.1.15'
        
        headers = {
            'User-Agent': ua,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        }
        
        # Add variation every 3 requests
        if self.counter % 3 == 0:
            headers['Cache-Control'] = 'max-age=0'
        if self.counter % 5 == 0:
            headers['Referer'] = 'https://www.google.com/'
            
        return headers
    
    def smart_delay(self, domain):
        """Intelligent delay based on domain"""
        current = time.time()
        if domain in self.domain_timings:
            elapsed = current - self.domain_timings[domain]
            if elapsed < 0.2:  # Too fast
                delay = random.uniform(0.1, 0.2)
            elif elapsed < 0.5:
                delay = random.uniform(0.05, 0.1)
            else:
                delay = random.uniform(0.02, 0.05)
        else:
            delay = random.uniform(0.02, 0.05)
        
        self.domain_timings[domain] = current
        return delay

# Initialize header system
header_system = OptimizedHeaderSystem()

# ============= ORIGINAL SCRIPT WITH OPTIMIZATIONS =============

try:
    target = [i.strip() for i in open(sys.argv[1], mode='r', encoding='utf-8').readlines()]
except IndexError:
    path = str(sys.argv[0]).split('\\')
    exit('\n  [!] Enter <' + path[len(path) - 1] + '> <sites.txt>')

banner = '''{}
           
 /$$   /$$ /$$$$$$$$ /$$$$$$$   /$$$$$$   /$$$$$$  /$$$$$$$$
| $$  / $$|_____ $$/| $$__  $$ /$$__  $$ /$$__  $$|__  $$__/
|  $$/ $$/     /$$/ | $$  \ $$| $$  \ $$| $$  \ $$   | $$   
 \  $$$$/     /$$/  | $$$$$$$/| $$  | $$| $$  | $$   | $$   
  >$$  $$    /$$/   | $$__  $$| $$  | $$| $$  | $$   | $$   
 /$$/\  $$  /$$/    | $$  \ $$| $$  | $$| $$  | $$   | $$   
| $$  \ $$ /$$/     | $$  | $$|  $$$$$$/|  $$$$$$/   | $$   
|__/  |__/|__/      |__/  |__/ \______/  \______/    |__/     

My Telegram channel : @x7rootv3  

Optimized Scanner with Anti-Ban System v2.0

\n'''.format(fr)
print(banner)

# Extended Paths for better coverage
PATHS = [
    '/wp-includes/',
    '/wp-content/uploads/',
    '/wp-admin/includes/',
    '/wp-content/plugins/',
    '/wp-content/themes/',
    '/images/',
    '/assets/',
    '/uploads/',
    '/files/',
    '/backup/',
    '/tmp/',
    '/media/',
    '/public/'
]

# Add year-based paths for WordPress
current_year = datetime.now().year
for year in range(2020, current_year + 1):
    PATHS.append(f'/wp-content/uploads/{year}/')

# Original Signatures
Signs = ['-rw-r--r--','drwxr-xr-x','Uname:','Yanz Webshell!','FilesMAn','Gel4y Mini Shell','{Ninja-Shell}','type="button">Upload File<','Simple File Manage Design by index.php','x3x3x3x_5h3ll','LIT COUSRE TEAM','403WebShell','input type=password name=pass','Indonesian Darknet','AnonSec Shell','Powered By Indonesian Darknet','<title>MARIJUANA</title>','File manager -','bondowoso black hat shell','BlackDragon','| PHP 7.4.20 |','xXx Kelelawar Cyber Team xXx','Code By Kelelawar Cyber Team','UnknownSec','shell bypass 403','UnknownSec Shell','[ HOME SHELL ] ','RC-SHELL v2.0.2011.1009','<title>Mini Shell</title>','Mini Shell','Negat1ve Shell','Copyright negat1ve1337','[+[MAD TIGER]+]','Franz Private Shell','Webshell V1.0','>Cassano Bypass <','TEAM-0ROOT Uploader','Fighter Kamrul Plugin','- FierzaXploit -','Simple,Responsive & Powerfull','<title>FierzaXploit</title>','Current dir:','Minishell','Current directory:','[ ! ] Cilent Shell Backdor [ ! ]','Powered By Indonesian Darknet','Mini Shell','Mini Shell By Black_Shadow','Current dir:','FileManager Version 0.2 by ECWS','aDriv4-Priv8 TOOL','B Ge Team File Manager','MARIJuANA','ineSec Team Shell','input type="file" name="filUpload"','input type="file" name="uploaded_file"','input type="file" name="file"><input name="_upl" type="submit" id="_upl" value="Upload"','input type="file" name="fileToUpload" id="fileToUpload"','Doc Root:','[+] MINI SH3LL BYPASS [+]','TEAM-0ROOT','#No_Identity 2.4.3','[ Mini Shell ]','PHU Mini Shell','MSQ_403','#wp_config_error#','Graybyt3 Was Here','One Hat Cyber Team','Mr.Combet WebShell','C0d3d By Dr.D3m0','Upload File : <input type="file" name="file"','L I E R SHELL','%PDF-0-1<form action="" method="post"><input type="text" name="_rg"><input type="submit" value=">>"','<pre align=center><form method=post>Password<br><input type=password name=pass','SavvyWolf','Tiny File Manager','File Manager','Tiny File Manager 2.4.0','adrivz','<title>Avaa</title>','rw-rw-rw-','Cyber Team','Mini Shell']

Strings_Shells = ['-rw-r--r--','drwxr-xr-x','Uname:','Yanz Webshell!','FilesMAn','L I E R SHELL','Gel4y Mini Shell','{Ninja-Shell}','type="button">Upload File<','Simple File Manage Design by index.php','x3x3x3x_5h3ll','LIT COUSRE TEAM','403WebShell','Indonesian Darknet','AnonSec Shell','Powered By Indonesian Darknet','<title>MARIJUANA</title>','File manager -','bondowoso black hat shell','BlackDragon','| PHP 7.4.20 |','xXx Kelelawar Cyber Team xXx','Code By Kelelawar Cyber Team','UnknownSec','shell bypass 403','UnknownSec Shell','[ HOME SHELL ] ','RC-SHELL v2.0.2011.1009','<title>Mini Shell</title>','Mini Shell','Negat1ve Shell','Copyright negat1ve1337','[+[MAD TIGER]+]','Franz Private Shell','Webshell V1.0','>Cassano Bypass <','TEAM-0ROOT Uploader','Fighter Kamrul Plugin','- FierzaXploit -','Simple,Responsive & Powerfull','<title>FierzaXploit</title>','Current dir:','Minishell','Current directory:','[ ! ] Cilent Shell Backdor [ ! ]','Powered By Indonesian Darknet','Mini Shell','Mini Shell By Black_Shadow','Current dir:','FileManager Version 0.2 by ECWS','aDriv4-Priv8 TOOL','B Ge Team File Manager','MARIJuANA','ineSec Team Shell','CHips L Pro sangad','Doc Root:','[+] MINI SH3LL BYPASS [+]','TEAM-0ROOT','#No_Identity 2.4.3','[ Mini Shell ]','PHU Mini Shell','MSQ_403','#wp_config_error#','Graybyt3 Was Here','One Hat Cyber Team','Mr.Combet WebShell','<title>Avaa</title>','rw-rw-rw-','Zerion Mini Shell','Upload File : <input type="file" name="file"']
Strings_PassShells = ['%PDF-0-1<form action="" method="post"><input type="text" name="_rg"><input type="submit" value=">>"','<pre align=center><form method=post>Password<br><input type=password name=pass','input type=password name=pass']
Strings_Uploads = ['input type="file" name="filUpload"','input type="file" name="uploaded_file"','input type="file" name="file"><input name="_upl" type="submit" id="_upl" value="Upload"','input type="file" name="fileToUpload" id="fileToUpload"']
Strings_H3K = ['Tiny File Manager','File Manager','adrivz','Cyber Team','Mini Shell']

ReallyFiles = ['getid3.lib','getid3','module.audio-video.asf','module.audio-video.flv','module.audio-video.matroska','module.audio-video.quicktime','module.audio-video.riff','module.audio.ac3','module.audio.dts','module.audio.flac','module.audio.mp3','module.audio.ogg','module.tag.apetag','module.tag.id3v1','module.tag.id3v2','module.tag.lyrics3','class-IXR-base64','class-IXR-client','class-IXR-clientmulticall','class-IXR-date','class-IXR-error','class-IXR-introspectionserver','class-IXR-message','class-IXR-request','class-IXR-server','class-IXR-value','Exception','H3K','SMTP','Requests','Basic','Auth','Autoload','Capability','Cookie','Exception','HookManager','Hooks','IdnaEncoder','Ipv6','Iri','Port','Proxy','Requests','Response','Session','Ssl','Transport','Jar','ArgumentCount','Http','InvalidArgument','Transport','Status304','Status305','Status306','Status400','Status401','Status402','Status403','Status404','Status405','Status406','Status407','Status408','Status409','Status410','Status411','Status412','Status413','Status414','Status415','Status416','Status417','Status418','Status428','Status429','Status431','Status500','Status501','Status502','Status503','Status504','Status505','Status511','StatusUnknown','Curl','Http','Headers','Curl','Fsockopen','CaseInsensitiveDictionary','FilteredIterator','InputValidator','autoloader','Author','Cache','Caption','Category','Copyright','Core','Credit','Enclosure','Exception','File','IRI','Item','Locator','Misc','Parser','Rating','Registry','Restriction','Sanitize','Source','gzdecode','Base','DB','File','Memcache','Memcached','MySQL','Redis','Sniffer','Entities','Parser','IPv6','Date','Parser','SimplePie','Author','Cache','Caption','Category','Copyright','Core','Credit','Enclosure','Exception','File','Gzdecode','IRI','Item','Locator','Misc','Parser','Rating','Registry','RegistryAware','Restriction','Sanitize','SimplePie','Source','Base','BaseDataCache','CallableNameFilter','DB','DataCache','File','Memcache','Memcached','MySQL','NameFilter','Psr16','Redis','Sniffer','Entities','Parser','IPv6','Date','Parser','native','shell','string','xdiff','inline','Renderer','Diff','Exception']

def URLdomain(site):
    if site.startswith("http://"):
        site = site.replace("http://", "")
    elif site.startswith("https://"):
        site = site.replace("https://", "")
    else:
        pass
    pattern = re.compile('(.*)/')
    while re.findall(pattern, site):
        sitez = re.findall(pattern, site)
        site = sitez[0]
    return site

def IndeXOf(Contents):
    # Enhanced Index Of detection with 7 methods
    if '<title>Index of' in Contents:
        return True
    elif '<h1>Index of' in Contents or 'Index of /' in Contents:
        return True
    elif 'Parent Directory' in Contents and '</td><td><a href=' in Contents:
        return True
    elif '<pre><a href=' in Contents or '<table><tr><th>' in Contents:
        return True
    elif '<tr><td data-sort=' in Contents or 'class="indexcolname"' in Contents:
        return True
    elif '[DIR]' in Contents or '[PARENTDIR]' in Contents or '[TXT]' in Contents:
        return True
    elif 'alt="[DIR]"' in Contents or 'alt="[PARENTDIR]"' in Contents:
        return True
    else:
        return False

def Send_Request(url, Path):
    """Optimized request with smart anti-ban"""
    try:
        if len(Path) <= 300:
            # Get domain for smart delay
            from urllib.parse import urlparse
            domain = urlparse(url).netloc
            
            # Apply smart delay
            delay = header_system.smart_delay(domain)
            time.sleep(delay)
            
            # Get optimized headers
            headers = header_system.get_headers()
            
            Content = requests.get(url + Path, headers=headers, timeout=12, verify=False, allow_redirects=False)
            return Content
    except:
        pass

def Extract_Folders(FoldersName):
    if '.' not in FoldersName:
        return True

def Extract_Files(FileName):
    if '.' in FileName:
        if '.php' in FileName:
            return True
        else:
            return False
    else:
        return False

def Extract(Contents, Selected):
    # Enhanced extraction with multiple patterns
    Pathfiles = []
    
    if '</td><td><a href="' in Contents:
        Pathfiles.extend(re.findall('</td><td><a href="(.*?)">', Contents))
    
    if ']"> <a href="' in Contents:
        Pathfiles.extend(re.findall(']"> <a href="(.*?)">', Contents))
    
    if '<tr><td data-sort=' in Contents or '"><a href="' in Contents:
        Pathfiles.extend(re.findall('"><a href="(.*?)"><img', Contents))
    
    if '<pre><a href="' in Contents:
        Pathfiles.extend(re.findall('<pre><a href="(.*?)">', Contents))
    
    if 'href="' in Contents and ('<li>' in Contents or '<tr>' in Contents):
        possible_paths = re.findall('href="([^"]+)"', Contents)
        for path in possible_paths:
            if not path.startswith(('http://', 'https://', 'javascript:', '#', 'mailto:')):
                if path not in ['../', '/', '?C=N;O=D', '?C=M;O=A', '?C=S;O=A', '?C=D;O=A']:
                    Pathfiles.append(path)
    
    Pathfiles = list(set(Pathfiles))
    
    cleaned_paths = []
    for path in Pathfiles:
        if path and path not in ['../', '/', '?'] and not path.startswith('?'):
            if 'Files' in Selected and Extract_Files(path):
                cleaned_paths.append(path)
            elif 'Folders' in Selected and Extract_Folders(path):
                if path.endswith('/'):
                    cleaned_paths.append(path)
                else:
                    cleaned_paths.append(path + '/')
    
    return cleaned_paths

def Check_Backdoors(Respones, Sign):
    NullData = ""
    if Respones and hasattr(Respones, 'status_code'):
        if Respones.status_code == 200:
            if Sign in Respones.text:
                php = "<?php"
                perl = "#!/usr/bin/perl"
                py = "#!/usr/bin/python"
                sh = "#!/bin/bash"
                if php not in Respones.text and perl not in Respones.text and py not in Respones.text and sh not in Respones.text:
                    return Sign
                else:
                    return NullData
            else:
                return NullData
        else:
            return NullData
    else:
        return NullData

def Process_Files(url, Path, Level):
    """Process files at any level"""
    MyPath = Path
    Request_Text = Send_Request(url, MyPath)
    
    if Request_Text and any(Sign in Check_Backdoors(Request_Text, Sign) for Sign in Signs):
        if any(ShF in Check_Backdoors(Request_Text, ShF) for ShF in Strings_Shells):
            print("Target:{} {}<===== $${}$$  =====> Success File Manager".format(url+MyPath, fg, Level))
            open('Shells.txt', 'a').write(url+MyPath + "\n")
            
        elif any(ShPwd in Check_Backdoors(Request_Text, ShPwd) for ShPwd in Strings_PassShells):
            print("Target:{} {}<===== $${}$$  =====> Success Shell Password".format(url+MyPath, fg, Level))
            open('Shells_Passwords.txt', 'a').write(url+MyPath + "\n")
            
        elif any(PhPMLr in Check_Backdoors(Request_Text, PhPMLr) for PhPMLr in Strings_H3K):
            print("Target:{} {}<===== $${}$$  =====> Success H3K".format(url+MyPath, fg, Level))
            open('H3K.txt', 'a').write(url+MyPath + "\n")
        
        elif any(UpLod in Check_Backdoors(Request_Text, UpLod) for UpLod in Strings_Uploads):
            print("Target:{} {}<===== $${}$$  =====> Success Uploaders".format(url+MyPath, fg, Level))
            open('Uploaders.txt', 'a').write(url+MyPath + "\n")
            
        else:
            print("Target:{} {}<===== $${}$$  =====> Success Random File".format(url+MyPath, fg, Level))
            open('Randoms.txt', 'a').write(url+MyPath + "\n")
            
    else:
        print("Target:{}  {}Folder_[{}]_FileName:{} <=== Oo  Not Vuln ".format(url, fr, Level, MyPath))

def Scan_Deep(url, current_path, current_level, max_level=4):  # Reduced to 4 for speed
    """Recursive deep scanning function"""
    if current_level > max_level:
        return
    
    try:
        response = Send_Request(url, current_path)
        if not response:
            return
            
        contents = response.text
        
        if IndeXOf(contents):
            all_items = Extract(contents, 'Files')
            all_items.extend(Extract(contents, 'Folders'))
            
            all_items = list(set(all_items))
            
            for elements in ReallyFiles:
                element = elements + ".php"
                if element in all_items:
                    all_items.remove(element)
            
            for item in all_items:
                if Extract_Files(item):
                    file_path = current_path + item
                    Process_Files(url, file_path, current_level)
                    
                elif Extract_Folders(item):
                    if item not in current_path:
                        folder_path = current_path + item
                        print("{}[+] Scanning Level {} => {}{}".format(fc, current_level, folder_path, fw))
                        
                        Scan_Deep(url, folder_path, current_level + 1, max_level)
        else:
            print("Target:{}  {}Folder_[{}]:{} <=== Index Not Of ".format(url, fr, current_level, current_path))
            
    except Exception as e:
        pass

def Exploiter(site, Dirctorys):
    try:
        url = "http://" + URLdomain(site)
        
        for Path in Dirctorys:
            print("\n{}[*] Starting scan for: {}{}".format(fm, Path, fw))
            Scan_Deep(url, Path, 1, 4)
                
    except:
        pass

def CmsCheckers(site):
    try:
        url = "http://" + URLdomain(site)
        Exploiter(url, PATHS)
        
    except:
        pass

# Session management with optimized headers
class OptimizedSession:
    def __init__(self):
        self.session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100, max_retries=0)
        self.session.mount('http://', adapter)
        self.session.mount('https://', adapter)
        self.session.max_redirects = 1
        
    def get(self, url, **kwargs):
        # Use optimized headers for session
        kwargs['headers'] = header_system.get_headers()
        return self.session.get(url, **kwargs)

# Global session
opt_session = OptimizedSession()

# Quick request with session
def Quick_Request(url, timeout=10):
    try:
        resp = opt_session.get(url, timeout=timeout, verify=False, stream=True, allow_redirects=False)
        if resp.status_code in [301, 302, 303, 307, 308]:
            return None
        return resp
    except:
        return None

# Main execution
if __name__ == "__main__":
    print("{}[+] Optimized Anti-Ban System Active".format(fg))
    print("{}[+] Smart Delay: Dynamic per domain".format(fg))
    print("{}[+] Header Rotation: 5 Browser Profiles".format(fg))
    print("{}[+] Max Depth: 4 levels (optimized)".format(fg))
    print("{}[+] Paths: {} directories\n".format(len(PATHS), fg))
    
    mp = Pool(150)  # Reduced from 150 for stability
    mp.map(CmsCheckers, target)
    mp.close()
    mp.join()

    print("\n[+] Scanning completed!")
    print("[+] Results saved to: Shells.txt, Uploaders.txt, H3K.txt, Shells_Passwords.txt, Randoms.txt")