from frida_tools import tracer
import json
import requests
import frida, sys

#python frida-trace.py  --no-pause

BURP_HOST = 'localhost'
BURP_PORT = 8888

device = frida.get_device_manager().enumerate_devices()[-1]
print(device)
session = device.attach("com.emeint.android.myservices")



def on_message(self, message, data, ui):
    handled = False
    if message['type'] == 'input':
        handled = True
    elif message['type'] == 'send':
        stanza = message['payload']
        if stanza['from'] == '/request':
            req_data = stanza['payload']
            print(req_data)
            # orig_json_data = json.loads(req_data)
            # orig_request_url = orig_json_data.pop(u'orig_request_url')
            orig_request_url = 'execute'
            req = requests.request('REQUEST',
                                  'http://%s:%d/' % (BURP_HOST, BURP_PORT),
                                  headers={
                                      'content-type': 'text/plain',
                                      'ORIG_REQUEST_URI': orig_request_url
                                  },
                                  data=req_data)
            return_content = req.content.decode('utf-8')
            # req = requests.request('REQUEST', 'http://%s:%d/' % (BURP_HOST, BURP_PORT),
            #                        headers={'content-type':'text/plain', 'ORIG_REQUEST_URI': orig_request_url},
            #                        data=json.dumps(orig_json_data))
            self._script.post({'type':'input', 'payload': return_content})
            handled = True
        elif stanza['from'] == '/response':
            req_data = stanza['payload'].encode('utf-8')
            req = requests.request('RESPONSE', 'http://%s:%d/' % (BURP_HOST, BURP_PORT),
                                   headers={'content-type': 'text/plain'},
                                   data=req_data)
            self._script.post({'type': 'output', 'payload': req.content.decode('utf-8')})
            handled = True
    if not handled:
        self.__process_message(message, data, ui)



script = session.create_script("""
Interceptor.attach(Module.findExportByName(null, "open"), {


    onEnter: function onEnter(log, args, state) {
        log("read(" + "fd=" + args[0]+ ", buf=" + args[1]+ ", count=" + args[2] + ")");
        state.buf = args[1]
    },
 
    onLeave: function onLeave(log, retval, state) {
        send({from: '/http', payload: Memory.readUtf8String(state.buf)})
        var op = recv('input', function(value) { // callback function
            log("Forwarding mitm'ed content: " + value.payload)
            Memory.writeUtf8String(state.buf, value.payload)
        });
        op.wait();
    }
})


""")




script.on('message', on_message)
script.load()
sys.stdin.read()