Ejemplo n.º 1
0
def attach(packageName):
    online_session = None
    online_script = None
    rdev = None
    remoteDriver = run_env.getRemoteDriver()  #ip:port
    try:
        if remoteDriver:
            rdev = frida.get_device_manager().add_remote_device(remoteDriver)
        elif platform.system().find("Windows") != -1:
            warn("推荐使用linux或mac操作系统获得更好的兼容性.")
            rdev = frida.get_remote_device()
        else:
            rdev = frida.get_usb_device(1000)
        online_session = rdev.attach(packageName)
        if online_session == None:
            warn("attaching fail to " + packageName)
        online_script = online_session.create_script(run_env.rpc_jscode)
        online_script.on('message', on_message)
        online_script.load()
        checkRadarDex(packageName, online_script)
        createHookingEnverment(packageName,
                               online_script.exports.mainactivity())
    except Exception:
        warn(traceback.format_exc())
    return online_session, online_script
Ejemplo n.º 2
0
    def attach_application(self, pid, frida_script, device):

        self.frida_script = frida_script

        if pid.isnumeric():
            self.pid = int(pid)
        else:
            self.pid = pid

        if device == 'remote':
            self.device = frida.get_remote_device()
        elif device == 'usb':
            self.device = frida.get_usb_device()
        else:
            self.device = frida.get_local_device()

        self.session = self.device.attach(self.pid)

        with codecs.open(self.frida_script, 'r', 'utf-8') as f:
            source = f.read()

        self.script = self.session.create_script(source)
        self.script.load()

        return
Ejemplo n.º 3
0
    def attach(self):
        if self.project.pid != None:
            target_process = self.project.pid
        elif self.project.process_name != None:
            target_process = self.project.process_name
        else:
            log.warn("No process specified with 'process_name' or 'pid'!")
            return False

        if self.project.remote_frida:
            self.frida_session = frida.get_remote_device().attach(
                target_process)
        else:
            self.frida_session = frida.attach(target_process)
        self.loadScript()
        pid = self.frida_script.exports.getpid()
        log.info("Attached to pid %d!" % pid)
        self.project.pid = pid

        # Query the loaded modules from the target
        self.getModuleMap()

        # ... and create the module filter list
        self.createModuleFilterList()
        return True
Ejemplo n.º 4
0
def get_zuiyou_sign():
    # 调用frida脚本
    process = frida.get_remote_device().attach("cn.xiaochuankeji.tieba")
    script = process.create_script(jsCode)
    # print('[*] Running zuiyou')
    script.load()
    return script.exports
Ejemplo n.º 5
0
def connect_device():
    try:
        device = frida.get_usb_device()
    except:
        device = frida.get_remote_device()

    return device
Ejemplo n.º 6
0
def show_packages():
    global device
    global remote
    try:
        remote = request.args.get('remote')
        if device == None:
            if len(remote) != 0:
                # check remote ip address
                try:
                    socket.inet_aton(remote)
                    print("adding remote device to device manager : ", remote)
                    device=frida.get_device_manager().add_remote_device(remote)
                    print("remote device : ", device)
                except socket.error:
                    return render_template('intro.html')
            else:
                device = frida.get_remote_device()

        # get list of apps
        packages=device.enumerate_processes()
        print(packages)
    except frida.ServerNotRunningError :
        return render_template('error.html',error="cannot connect to remote :(")
    return render_template('packages_list.html',
                           packages=packages)
Ejemplo n.º 7
0
    def set_device(self):
        """
            Set's the target device to work with.

            :return:
        """

        if self.config.device_id is not None:
            self.device = frida.get_device(self.config.device_id)

        elif (self.config.host is not None) or (self.config.device_type
                                                == 'remote'):
            if self.config.host is None:
                self.device = frida.get_remote_device()
            else:
                host = self.config.host
                port = self.config.port
                self.device = frida.get_device_manager() \
                    .add_remote_device(f'{host}:{port}' if host is not None else f'127.0.0.1:{port}')

        elif self.config.device_type is not None:
            for dev in frida.enumerate_devices():
                if dev.type == self.config.device_type:
                    self.device = dev
        else:
            self.device = frida.get_local_device()

        # surely we have a device by now?
        if self.device is None:
            raise Exception('Unable to find a device')

        self.device.on('output', self.handlers.device_output)
        self.device.on('lost', self.handlers.device_lost)

        debug_print(f'device determined as: {self.device}')
Ejemplo n.º 8
0
def main(target_process):
    dev = frida.get_remote_device()
    session = dev.attach(target_process)

    j = """
        Process.enumerateModules({
            onMatch: function(module){
                        console.log('Module name: ' + module.name + " - " + "Base Address: " + module.base.toString());

                        Module.enumerateImports("%s", {
                            onMatch: function(module){
                                console.log('Module type: ' + module.type + ' - Name: ' + module.name + ' - Module: ' + moudle.module + ' - Address: ' + module.address.toString());
                            }, 
                            onComplete: function(){}
                        });

                    }, 
            onComplete: function(){}
        });

        


        """

    script = session.create_script(j)

    script.on('message', on_message)
    script.load()
    raw_input(
        '[!] Press <Enter> at any time to detach from instrumented program.\n\n'
    )
    session.detach()
Ejemplo n.º 9
0
def hook_by_method(activity,method_name):
    pkg, ac = activity.split('/')
    activity = activity.replace('/','')
    js_code = """
    Java.perform(
    setTimeout(function(){
    var hookClass = Java.use('%s')
    console.log('HookClass',hookClass)
    hookClass.%s.implementation = function(args){
        send('crack successful',%s)
        console.log('入参',args)
        return this.%s(args)
    }

},1000)
    );
    """%(activity,method_name,method_name,method_name)
    print(js_code)

    process = frida.get_remote_device().attach(pkg)
    script = process.create_script(js_code)
    def on_message(message, data):
        if message['type'] == 'send':
            print("[*] {0}".format(message['payload']))
        else:
            print(message)

    script.on('message', on_message)
    print('开始hook')
    script.load()
    sys.stdin.read()
Ejemplo n.º 10
0
def connect_device(timeout=15):
    try:
        device = frida.get_usb_device(timeout=timeout)
    except:
        device = frida.get_remote_device()

    return device
Ejemplo n.º 11
0
def main():
    argv = sys.argv
    process = None
    so_name = None
    func_name = None
    arg_count = len(argv)
    if arg_count < 2:
        print "this.py (pid|pName) [soName [funcName]]"
        return 1
    else:
        try:
            process = int(argv[1])
        except:
            process = argv[1]

    if arg_count > 2:
        so_name = argv[2]
    if arg_count > 3:
        func_name = argv[3]

    remote_dev = frida.get_remote_device()
    session = remote_dev.attach(process)
    modules = session.enumerate_modules()
    for module in modules:
        if so_name is None or so_name in module.name:
            print module
            export_funcs = module.enumerate_exports()
            for export_func in export_funcs:
                if func_name is None or func_name in export_func.name:
                    print "\t%s\t%s" % (export_func.name,
                                        hex(export_func.absolute_address))
Ejemplo n.º 12
0
def start_hook():
    device = frida.get_remote_device()
    print(device)

    # 应用包名
    app_package_name = "com.luojilab.player"  # dedao
    try:
        # pid = device.spawn([app_package_name])
        # device.resume(pid)
        # time.sleep(1)  # 2
        session = device.attach(app_package_name)
        # session = device.attach(target=16803)
        print("[*] start hook")
        print(session)

        # 加载脚本
        with open("test.js", "r", encoding="utf-8") as file:
            # with open("hook_dedao.js", "r", encoding="utf-8") as file:
            js_code = file.read()

        script = session.create_script(js_code)
        script.on('message', on_message)
        script.load()
        # sys.stdin.read()  # 等待程序触发,调试时打开
        # print('script', script)
        return script
    except frida.NotSupportedError:
        print("请检查包名的有效性.")
Ejemplo n.º 13
0
def attach(target):
    packageName = target
    if is_number(target):  #pid
        packageName = getPidMap()[target]
    online_session = None
    online_script = None
    rdev = None
    remoteDriver = run_env.getRemoteDriver()  #ip:port
    try:
        if remoteDriver:
            rdev = frida.get_device_manager().add_remote_device(remoteDriver)
        elif platform.system().find("Windows") != -1:
            warn("推荐使用linux或mac操作系统获得更好的兼容性.")
            rdev = frida.get_remote_device()
        else:
            rdev = frida.get_usb_device(1000)
        #print(f"attach {target}")
        if is_number(target):
            pid = int(target)
            online_session = frida.core.Session(rdev._impl.attach(pid))
        else:
            online_session = rdev.attach(target)
        if online_session == None:
            warn("attaching fail to " + target)
        online_script = online_session.create_script(run_env.rpc_jscode)
        online_script.on('message', on_message)
        online_script.load()
        checkRadarDex(packageName, online_script)
        createHookingEnverment(packageName,
                               online_script.exports.mainactivity())
    except Exception:
        warn(traceback.format_exc())
    return online_session, online_script, packageName
Ejemplo n.º 14
0
def startHook(packageName, jsCode):
    rdev = frida.get_remote_device()
    session = rdev.attach(packageName)
    script = session.create_script(jsCode)
    script.on('message', on_message)
    print(' Start attach')
    script.load()
    sys.stdin.read()
Ejemplo n.º 15
0
def test_frida():
    rdev = frida.get_remote_device()
    print rdev
    front_app = rdev.get_frontmost_application()
    print front_app
    processes = rdev.enumerate_processes()
    for process in processes:
        print process
Ejemplo n.º 16
0
def spawn_remote_default(appname):
    print("[*] Spawn process on remote machine (with frida-server)")

    device  = frida.get_remote_device()
    pid     = device.spawn([appname])
    session = device.attach(pid)
    device.resume(pid)
    waitinterrupt()
Ejemplo n.º 17
0
 def hooking(self):
     print('【开始Hook】.....\n\n')
     try:
         process = frida.get_remote_device().attach(self.arg)
         script = process.create_script(self.js_code)
         script.on("message", self.message)
         script.load()
         sys.stdin.read()
     except frida.ServerNotRunningError:
         print('没有开启对应app, 或没有开启映射端口')
Ejemplo n.º 18
0
    def get_session(self):
        """
            Attempt to get a Frida session.
        """

        if state_connection.get_comms_type() == state_connection.TYPE_USB:
            return frida.get_usb_device().attach(state_connection.gadget_name)

        if state_connection.get_comms_type() == state_connection.TYPE_REMOTE:
            return frida.get_remote_device().attach(state_connection.gadget_name)
Ejemplo n.º 19
0
def main():
    remote_dev = frida.get_remote_device()
    session = remote_dev.attach("com.example.wechat01")
    modules = session.enumerate_modules()
    for module in modules:
        print module
        export_funcs = module.enumerate_exports()
        for export_func in export_funcs:
            if "strlen" == export_func.name:
                print "\t%s\t%s" % (export_func.name,
                                    hex(export_func.absolute_address))
Ejemplo n.º 20
0
def attach_spawn_target(args, user_script=None):
    if not args.target and not args.device:
        print('missing session type. use -t local|android|ios|remote to define the session type'
              ' or specify a device id with --device')
        exit(0)

    if args.any is None or args.any == '':
        print('missing file or package name to attach')
        exit(0)

    device = None
    try:
        if args.device:
            device = frida.get_device(id=args.device)
        else:
            session_type = args.target.lower()
            if session_type == 'local':
                device = frida.get_local_device()
            elif session_type == 'android' or session_type == 'ios':
                device = frida.get_usb_device(5)
            elif session_type == 'remote':
                device = frida.get_remote_device()
    except Exception as e:
        print('failed to get frida device')
        print(e)

    if device is not None:
        try:
            # parse target as pid
            args.pid = int(args.any)
        except ValueError:
            args.pid = 0

        if args.pid > 0:
            print('* Trying to attach to {0}'.format(args.pid))
            try:
                attach(args, device)
                print('* Dwarf attached to {0}'.format(args.pid))
            except Exception as e:  # pylint: disable=broad-except
                print('-failed-')
                print('Reason: ' + str(e))
                print('Help: you can use -sp to force spawn')
                exit(0)
        else:
            print('* Trying to spawn {0}'.format(args.any))
            try:
                _pid = spawn(args, device, user_script)
                print('* Dwarf attached to {0}'.format(_pid))
            except Exception as e:  # pylint: disable=broad-except
                print('-failed-')
                print('Reason: ' + str(e))
                exit(0)

        sys.stdin.read()
Ejemplo n.º 21
0
def dump_pkg(pkg):
    try:
        print('Availlable devices:')
        devices = frida.enumerate_devices()
        i = 0

        for dv in devices:
            print('{}) {}'.format(i, dv))
            i += 1
        j = input('Enter the index of device to use:')
        device = devices[int(j)]
    except:
        device = frida.get_remote_device()

    bring_to_front = input(
        'Bring the application you want to dump to the front and press enter.....\n'
    )

    target = device.get_frontmost_application()

    pkg_name = pkg  #target.identifier
    print('---------' + pkg)
    processes = get_all_process(device, pkg_name)
    if len(processes) == 1:
        target = processes[0]
    else:
        s_processes = ""
        for index in range(len(processes)):
            s_processes += "\t[{}] {}\n".format(index, str(processes[index]))
        input_id = int(
            input(
                "[{}] has multiprocess: \n{}\nplease choose target process: ".
                format(pkg_name, s_processes)))
        target = processes[input_id]
        try:
            for index in range(len(processes)):
                if index == input_id:
                    os.system("adb shell \"su -c 'kill -18 {}'\"".format(
                        processes[index].pid))
                else:
                    os.system("adb shell \"su -c 'kill -19 {}'\"".format(
                        processes[index].pid))
        except:
            pass

    logging.info("[DEXDump]: found target [{}] {}".format(
        target.pid, pkg_name))
    session = device.attach(target.pid)
    path = '.'  #os.path.dirname(save_path)
    #path = path if path else "."
    script = session.create_script(open(path + "/dexdump.js").read())
    script.load()

    dump(pkg_name, script.exports)
Ejemplo n.º 22
0
def connect():
    global script
    try:
        process = frida.get_remote_device().attach(
            'CT-Young+'
        )  #得到设备并劫持进程com.example.testfrida(该开始用get_usb_device函数用来获取设备,但是一直报错找不到设备,改用get_remote_device函数即可解决这个问题)
    except frida.ServerNotRunningError:
        adbforward()
        try:
            process = frida.get_remote_device().attach(
                'CT-Young+'
            )  #得到设备并劫持进程com.example.testfrida(该开始用get_usb_device函数用来获取设备,但是一直报错找不到设备,改用get_remote_device函数即可解决这个问题)
        except frida.TransportError:
            device = frida.get_remote_device()
            pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
            device.resume(pid)
            process = device.attach(pid)
        except frida.ProcessNotFoundError:
            device = frida.get_remote_device()
            pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
            device.resume(pid)
            process = device.attach(pid)
        except frida.ProcessNotRespondingError:
            device = frida.get_remote_device()
            pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
            device.resume(pid)
            process = device.attach(pid)
        except frida.TransportError:
            adbforward()
            device = frida.get_remote_device()
            pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
            device.resume(pid)
            process = device.attach(pid)
    except frida.ProcessNotFoundError:
        device = frida.get_remote_device()
        pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
        device.resume(pid)
        process = device.attach(pid)
    except frida.ProcessNotRespondingError:
        device = frida.get_remote_device()
        pid = device.spawn(["com.cndatacom.campus.cdccportalhainan"])
        device.resume(pid)
        process = device.attach(pid)
    jscode = open("C:\\Users\\qcnhy\\Documents\\py\\test.js",
                  encoding='utf-8').read()
    #jscode = "var by = " + str(data) + ";\n" + jscode

    script = process.create_script(jscode)  #创建js脚本
    #script.on('message',on_message) #加载回调函数,也就是js中执行send函数规定要执行的python函数
    script.load()  #加载脚本
    time.sleep(2)
Ejemplo n.º 23
0
def startHook(packageName, jsCode):
    rdev = frida.get_remote_device()
    #脚本控制app启动 
#    pid = rdev.spawn(packageName)
#    session = rdev.attach(pid)
#    rdev.resume(pid)
    session = rdev.attach(packageName)
    script = session.create_script(jsCode)
    script.on('message', on_message)
    print(' Start attach')
    script.load()
    sys.stdin.read()
Ejemplo n.º 24
0
def gorgon_hook_prepare():

    # host = '127.0.0.1:27042'
    # process_name = "com.ss.android.ugc.aweme"
    # manager = frida.get_device_manager()
    # remote_device = manager.add_remote_device(host)
    # process = remote_device.attach(process_name)

    process = frida.get_remote_device().attach('com.ss.android.ugc.aweme')
    script = process.create_script(hook_code)
    script.on('message', on_message)
    script.load()
    return script.exports
Ejemplo n.º 25
0
def start_frida_script(network, adbpath):
    # Would be better to use frida.get_usb_device().spawn to spawn the app
    # But it seems that it is broken on some version so we use adb to spawn the game
    os.system(
        adbpath +
        " shell monkey -p com.supercell.clashroyale -c android.intent.category.LAUNCHER 1"
    )
    time.sleep(0.5)

    try:
        if network:
            device = frida.get_remote_device()
        else:
            device = frida.get_usb_device()

    except Exception as exception:
        print('[*] Can\'t connect to your device ({}) !'.format(
            exception.__class__.__name__))
        exit()

    retry_count = 0
    process = None

    while not process:
        try:
            process = device.attach('com.supercell.clashroyale')

        except Exception as exception:
            if retry_count == MAX_FRIDA_RETRY:
                print(
                    '[*] Can\'t attach frida to the game ({}) ! Start the frida server on your device'
                    .format(exception.__class__.__name__))
                exit()

            retry_count += 1
            time.sleep(0.5)

    print('[*] Frida attached !')

    if os.path.isfile("urandom_hook.js"):
        script = process.create_script(open("urandom_hook.js").read())

    else:
        print(
            '[*] urandom_hook.js script is missing, cannot inject the script !'
        )
        exit()

    script.load()

    print('[*] Script injected !')
Ejemplo n.º 26
0
def injectJs2App_1(processname, jsFilename):
    rdev = frida.get_remote_device()
    print(rdev)
    session = rdev.attach(processname)
    print(session)

    jsFile = open(jsFilename, "r")
    src = jsFile.read()

    script = session.create_script(src)

    script.on("message", on_message)
    script.load()
    sys.stdin.read()
Ejemplo n.º 27
0
 def Session(self):
     print(self.App_Name)
     try:
         if self.USB:
             self.session = frida.get_usb_device().attach(self.App_Name)
         elif self.Remote:
             self.session = frida.get_remote_device().attach(self.App_Name)
         else:
             self.session = frida.attach(self.App_Name)
     except Exception as e:
         print(
             "Cant connect to application. Have you connected the device?")
         logging.debug(str(e))
         sys.exit()
Ejemplo n.º 28
0
def injectJs2App(pkgname, version):
    rdev = frida.get_remote_device()
    print(rdev)
    session = rdev.attach(pkgname)
    #pid = rdev.spawn(pkgname)
    #print(pid)
    print(session)

    jsFilename = "module/"+pkgname+"/"+ version + ".js"
    print(jsFilename)
    jsFile = open(jsFilename, mode='r', encoding='UTF-8')
    src = jsFile.read()
    script = session.create_script(src)

    script.on("message", on_message)
    script.load()
    sys.stdin.read()
Ejemplo n.º 29
0
def button_call_back():
    global script
    global script_sdk

    if script != 0:
        script.unload()

    file_object = open('hook.js', encoding="utf-8")
    text = file_object.read()
    file_object.close()
    device = frida.get_remote_device()

    process = device.attach("com.tencent.mm")
    if process:
        script = process.create_script(text)
        script.on('message', on_message)
        script.load()
Ejemplo n.º 30
0
def get_data():
    device = frida.get_remote_device()
    session = device.attach("com.猿人学.onlinejudge2020")
    jscode = """
    Java.perform(function(){
    var OnlineJudgeApp = Java.use("com.猿人学.onlinejudge2020.OnlineJudgeApp");
    OnlineJudgeApp.getSign.implementation = function(i){
    for(var j =0;j<=9999;j++){
        var sign = this.getSign(j);
        send(j + ":" + sign);
    }
        return this.getSign(i);
    }
    })
    """
    script = session.create_script(jscode)
    script.on("message", on_message)
    script.load()
    sys.stdin.read()
Ejemplo n.º 31
0
                print data
                print

        except Exception, arg:
            print "SSL_read Exception", arg

        script_obj.post({'type': 'input', 'payload': None, 'num': None, "do": "ignore", "id": payload['id']})


if __name__ == "__main__":

    print 'SSL hook tool'
    check()
    print 'check pass'

    session = frida.get_remote_device().attach(package_name)

    fp = open("main.js", "r")
    script_context = fp.read()
    fp.close()

    script = session.create_script(script_context)

    script_obj = script

    script.on("message", on_message)
    script.load()

    print "Press Ctrl+C to stop logging."
    try:
        signal.pause()
Ejemplo n.º 32
0
    except Exception as e:
        print(message)
        print(e)


if __name__ == '__main__':
    try:
	path = "hooks"
	parser = OptionParser(usage="usage: %prog [options] <process_to_hook>",version="%prog 1.0")
	parser.add_option("-A", "--attach", action="store_true", default=False,help="Attach to a running process")
	parser.add_option("-S", "--spawn", action="store_true", default=False,help="Spawn a new process and attach")

	(options, args) = parser.parse_args()
	if (options.spawn):
		print ("[*] Spawning "+ str(args[0]))
       		pid = frida.get_remote_device().spawn([args[0]])
		session = frida.get_remote_device().attach(pid) 
	elif (options.attach):
		print ("[*] Attaching to "+str(args[0]))
       		session = frida.get_remote_device().attach(str(args[0]))
	else:
		print ("Error")
		print ("[X] Option not selected. View --help option.")
		sys.exit(0)

	for filename in os.listdir(path):
		name, ext = os.path.splitext(filename)
		if (ext == ".enabled"):
			print "[*] Parsing hook: "+filename
			hook = open(path+os.sep+filename, "r")
			script = session.create_script(hook.read())
Ejemplo n.º 33
0
import frida

session = frida.get_remote_device().attach("com.android.settings")

modulesList = session.enumerate_modules()

for i in range(0, len(modulesList)):
	if "libc.so" in modulesList[i].name:
		print i
		print modulesList[i]
		print " "

# print([x.name for x in session.enumerate_modules()])

Ejemplo n.º 34
0
def init_session():
    try:
        session = None
        if platform == 'ios' or platform == 'android':
            try:
                device = frida.get_usb_device(3) # added timeout to wait for 3 seconds
            except Exception as e:
                print colored(str(e), "red")
                traceback.print_exc()
                if platform == 'android':
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Is USB Debugging enabled?", "blue")
                    print colored("HINT: Is `frida-server` running on mobile device (with +x permissions)?", "blue")
                    print colored("HINT: Is `adb` daemon running?", "blue")
                    sys.exit(1)
                elif platform == "ios":
                    print colored("Troubleshooting Help", "blue")
                    print colored("HINT: Have you installed `frida` module from Cydia?", "blue")
                    print colored("HINT: Have used `ipa_installer` to inject the `FridaGadget` shared lbrary?", "blue")
                    sys.exit(1)
        elif platform == 'iossim':
            try:
                device = frida.get_remote_device()
            except Exception as e:
                # print traceback.print_exc()
                print colored("Troubleshooting Help", "blue")
                print colored("HINT: Have you successfully integrated the FridaGadget dylib with the XCode Project?", "blue")
                print colored("HINT: Do you see a message similar to \"[Frida INFO] Listening on 127.0.0.1 TCP port 27042\" on XCode console logs?", "blue")
                sys.exit(1)
        elif platform == 'macos':
            device = frida.get_local_device()
        else:
            print colored('[ERROR] Unsupported Platform', 'red')
            sys.exit(1)
        pid = None
        if app_name:
            try:
                if platform == 'android' and spawn == 1:
                    print colored("Now Spawning %s" % app_name, "green")
                    pid = device.spawn([app_name])
                    #time.sleep(5)
                    session = device.attach(pid)
                    #time.sleep(5)
                elif (platform == 'ios' or platform == 'macos') and spawn == 1:
                    bundleID = getBundleID(device, app_name, platform)
                    if bundleID:
                        print colored("Now Spawning %s" % bundleID, "green")
                        pid = device.spawn([bundleID])
                        #time.sleep(5)
                        session = device.attach(pid)
                    else:
                        print colored("[ERROR] Can't spawn %s" % app_name, "red")
                        traceback.print_exc()
                        sys.exit(1)
                else:
                    arg_to_attach = app_name
                    if app_name.isdigit():
                        arg_to_attach = int(app_name)

                    session = device.attach(arg_to_attach)
            except Exception as e:
                print colored('[ERROR] ' + str(e), 'red')
                traceback.print_exc()
        if session:
            print colored('[INFO] Attached to %s' % (app_name), 'yellow')
            session.on('detached', on_detached)
    except Exception as e:
        print colored('[ERROR] ' + str(e), 'red')
        traceback.print_exc()
        sys.exit(1)
    return device, session, pid