frida基础应用

一、获取第一个USB设备

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import frida
import threading

def get_usb_iphone():
    dManager = frida.get_device_manager();
    changed = threading.Event()
    def on_changed():
        changed.set()
    dManager.on('changed',on_changed)

    device = None
    while device is None:
        devices = [dev for dev in dManager.enumerate_devices() if dev.type =='usb']
        if len(devices) == 0:
            print ('Waiting for usb device...')
            changed.wait()
        else:
            device = devices[0]

    dManager.off('changed',on_changed)

    return device

def main():
    device = get_usb_iphone()
    print ('设备信息:' + str(device))

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit()
    else:
        pass
    finally:
        pass

二、枚举进程信息

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import frida
import threading

#系统标准输出,支持grep
def outWrite(text):
    sys.stdout.write(text.encode('utf8') + '\n');

#获取设备信息
def get_usb_iphone():
    dManager = frida.get_device_manager();
    changed = threading.Event()
    def on_changed():
        changed.set()
    dManager.on('changed',on_changed)

    device = None
    while device is None:
        devices = [dev for dev in dManager.enumerate_devices() if dev.type =='usb']
        if len(devices) == 0:
            print ('Waiting for usb device...')
            changed.wait()
        else:
            device = devices[0]

    dManager.off('changed',on_changed)

    return device

#枚举运行进程
def listRunningProcess():
    device = get_usb_iphone();
    processes = device.enumerate_processes();
    processes.sort(key = lambda item : item.pid)
    outWrite('%-10s\t%s' % ('pid', 'name'))
    for process in processes:
        outWrite('%-10s\t%s' % (str(process.pid),process.name))

def main():
    listRunningProcess()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit()
    else:
        pass
    finally:
        pass

三、列出所有已安装应用

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import frida
import codecs
import threading

global session

finished = threading.Event()

APP_JS = './js/app.js'

#系统标准输出,支持grep
def outWrite(text):
    sys.stdout.write(text.encode('utf8') + '\n');

#从JS接受信息
def on_message(message, data):
    if message.has_key('payload'):
        payload = message['payload']
        if isinstance(payload, dict):
            deal_message(payload)
        else:
            print payload

#处理JS调用后返回的信息
def deal_message(payload):
    #基本信息输出
    if payload.has_key('mes'):
        print payload['mes']

    #安装app信息
    if payload.has_key('app'):
        app = payload['app']
        lines = app.split('\n')
        for line in lines:
            if len(line):
                arr = line.split('\t')
                if len(arr) == 3:
                    outWrite('%-40s\t%-70s\t%-80s' % (arr[0], arr[1], arr[2]))

    #处理完成事件
    if payload.has_key('finished'):
        finished.set()

#获取设备信息
def get_usb_iphone():
    dManager = frida.get_device_manager();
    changed = threading.Event()
    def on_changed():
        changed.set()
    dManager.on('changed',on_changed)

    device = None
    while device is None:
        devices = [dev for dev in dManager.enumerate_devices() if dev.type =='usb']
        if len(devices) == 0:
            print ('Waiting for usb device...')
            changed.wait()
        else:
            device = devices[0]

    dManager.off('changed',on_changed)

    return device

#加载JS文件脚本
def loadJSFile(session, filename):
    source = ''
    with codecs.open(filename, 'r', 'utf-8') as f:
        source = source + f.read()
    script = session.create_script(source)
    script.on('message', on_message)                    #调用JS后返回数据,Python做的回调
    script.load()                                       #加载JS脚本
    return script

def main():
    global session

    device = get_usb_iphone()

    session = device.attach('SpringBoard')              #注入SpringBoard来获取一个session
    script = loadJSFile(session, APP_JS)                #加载JS脚本
    script.post({'cmd' : 'installed'})                  #获取所有已安装应用信息          
    finished.wait()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if session:
            session.detatch()
        sys.exit()
    else:
        pass
    finally:
        pass

四、枚举进程加载的所有模块

原实现提示session没有enumerate_modules这个API

#枚举某个进程的所有模块信息
def listModulesoOfProcess(session):
    moduels = session.enumerate_modules()
    moduels.sort(key = lambda item : item.base_address)
    for module in moduels:
        outWrite('%-40s\t%-10s\t%-10s\t%s' % (module.name, hex(module.base_address), hex(module.size), module.path))
    session.detach()

使用以下实现

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import frida
import threading

global session

#系统标准输出,支持grep
def outWrite(text):
    sys.stdout.write(text.encode('utf8') + '\n');

#获取设备信息
def get_usb_iphone():
    dManager = frida.get_device_manager();
    changed = threading.Event()
    def on_changed():
        changed.set()
    dManager.on('changed',on_changed)

    device = None
    while device is None:
        devices = [dev for dev in dManager.enumerate_devices() if dev.type =='usb']
        if len(devices) == 0:
            print ('Waiting for usb device...')
            changed.wait()
        else:
            device = devices[0]

    dManager.off('changed',on_changed)

    return device

def on_message(message, data):
    print("[on_message] message:", message, "data:", data)

#列出程序加载的模块
def listModulesOfProcess(session):
    script = session.create_script("""
        'use strict';
        rpc.exports.enumerateModules = function () {
        return Process.enumerateModulesSync();
        };"""
        )
    script.on("message", on_message)
    script.load()
    modules = script.exports.enumerate_modules()
    modules.sort(key = lambda item : item['base'])
    outWrite('%-40s\t%-10s\t%-10s\t%s' % ('module name', 'module base', 'module size', 'module path'))
    for module in modules:
        outWrite('%-40s\t%-10s\t%-10s\t%s' % (module['name'],module['base'], module['size'], module['path']))

def main():
    global session
    device = get_usb_iphone()
    session = device.attach(1771)   #1771为pid
    listModulesOfProcess(session)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if session:
            session.detach()
        sys.exit()
    else:
        pass
    finally:
        pass

五、 显示当前界面UI

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import sys
import frida
import codecs
import threading

global session

UI_JS = '/Users/ruanjianqin/ReverseTool/frida脚本分析调试/js/ui.js'

#带颜色打印输出
def colorPrint(color, s):
    return "%s[31;%dm%s%s[0m" % (chr(27), color, s , chr(27))

#获取设备
def get_usb_iphone():
    dManager = frida.get_device_manager();   #获取设备管理器
    changed = threading.Event()
    def on_changed():
        changed.set()
    dManager.on('changed',on_changed)        #监听添加设备的事件

    device = None
    while device is None:
        devices = [dev for dev in dManager.enumerate_devices() if dev.type =='usb']  #类型为tether为USB连接的设备
        if len(devices) == 0:
            print 'Waiting for usb device...'
            changed.wait()
        else:
            device = devices[0]              #获取第一个设备

    dManager.off('changed',on_changed)    

    return device

#从JS接受信息
def on_message(message, data):
    if message.has_key('payload'):
        payload = message['payload']
        if isinstance(payload, dict):
            deal_message(payload)
        else:
            print payload

#处理JS中不同的信息
def deal_message(payload):
    #基本信息输出
    if payload.has_key('mes'):
        print payload['mes']

    #处理UI界面输出
    if payload.has_key('ui'):
        print colorPrint(31, payload['ui'])

#加载JS文件脚本
def loadJsFile(session, filename):
    source = ''
    with codecs.open(filename, 'r', 'utf-8') as f:
        source = source + f.read()
    script = session.create_script(source)
    script.on('message', on_message)
    script.load()
    return script

def main():
    global session
    
    device = get_usb_iphone()
    session = device.attach(long(sys.argv[1]))
    script = loadJsFile(session, UI_JS)
    print device
    print session
    print script
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        script.post(line[:-1])


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if session:
            session.detach()
        sys.exit()
    else:
        pass
    finally:
        pass