import requests
import base64
import re
from PIL import Image
from pwn import *
from hackingscripts import util


if __name__ == "__main__":
    segment_addr = 0x800100
    segment_offset = 0x19
    data_size = 0xd8
    xor_key = 0x69

    data_addr = segment_addr + segment_offset
    firmware = ELF("./firmware.elf", checksec=False)
    for segment in firmware.segments:
        start = segment.header.p_vaddr
        end = segment.header.p_vaddr + segment.header.p_filesz

        if start <= data_addr < end:
            data = segment.data()[segment_offset:segment_offset+data_size]
            extracted_data = util.xor(data, xor_key).decode()
            break
    
    match = re.match(r"echo (.*) > data", extracted_data)
    b64_data = base64.b64decode(match[1].encode()).decode()

    match = re.match(r"wget (.*) -O - \| bash", b64_data)
    url = match[1]
    res = requests.get(url)

    match = re.search(r"wget (.*) -O - \| base64 -d > cat.png", res.text)
    url = match[1]
    res = requests.get(url)

    with open("cat.png", "wb") as f:
        f.write(base64.b64decode(res.content))

    img = Image.open("cat.png")
    img.load()
    print("[+] Flag:", img.info["Comment"])