#!/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
import string
from bs4 import BeautifulSoup
from hackingscripts import util, rev_shell
from hackingscripts.fileserver import HttpFileServer

import socket
from PIL import Image

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

HOST = "44c5decd-6619-4ce0-859a-882ed74f1736.rdocker.vuln.land"
IP_ADDRESS = util.get_address()

def get_image_bytes():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, 80))
    sock.sendall(b"\n")

    data = b""

    while True:
        b = sock.recv(1024)
        if not b:
            break

        data += b

    body_offset = data.index(b"\n\n")  # malformed here
    header, body = data[:body_offset], data[body_offset+2:]

    return header, body

if __name__ == "__main__":

    header, body = get_image_bytes()

    flag = ""
    while body:
        offset_index = body.index(b"\r\n")
        chunk_size = int(body[0:offset_index], 16)
        offset = offset_index + 2
        chunk = body[offset:offset+chunk_size]
        body = body[offset+chunk_size+2:]

        if chunk_size > 0x900:
            flag += chr(chunk_size & 0xFF)
    
    print("[+] Flag:", flag)
