mac使用frida

mac使用frida

安装

https://github.com/frida/frida/releases

根据手机的cpu的版本,选择相应的文件,一般通过手机信息可以看到
我这里是frida-server-12.6.7-android-arm64.xz
下载地址
链接: https://pan.baidu.com/s/15_026MJ4RULG6AJ5L3rejw 密码: 7kn7
解压frida-server-12.6.7-android-arm64.xz,然后把解压后的文件重命名frida-server
后来我使用genymotion,查看系统为x86。

补充arm64手机截图

所以下载了frida-server-12.7.5-android-x86.xz文件,然后解压并重命名为frida-server。
执行命令frida-server。
依次执行下面命令

$ adb push frida-server /data/local/tmp/ 
$ adb shell "chmod 755 /data/local/tmp/frida-server"
$ adb shell "/data/local/tmp/frida-server &"

然后在电脑上测试手机是否连通

$ adb devices -l

Frida大致原理是手机端安装一个server程序,然后把手机端的端口转到PC端,PC端写python脚本进行通信,而python脚本中需要hook的代码采用javascript语言。所以这么看来我们首先需要安装开始安装frida了,直接运行命令:

 /Applications/Python\ 3.6/Install\ Certificates.command
python3.6 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn frida frida-tools

我这大概要等很长时间才下载完。
然后执行命令

frida-ps -U -ai | grep -v '@' | grep -v '    -  '

看到类似的结果

  PID  Name
-----  -----------------------------------------------------------------
 2681  .dataservices
  835  ATFWD-daemon
12174  adbd
  844  adsprpcd
  845  adsprpcd
  745  android.hardware.audio@2.

即可。

插曲okttp3

okhttp3没混淆的hook

try {

    var CertificatePinner = Java.use('okhttp3.CertificatePinner');

    quiet_send('OkHTTP 3.x Found');

    CertificatePinner.check.overload('java.lang.String', 'java.util.List').implementation = function () {

        quiet_send('OkHTTP 3.x check() called. Not throwing an exception.');
    }

} 

okhttp3混淆的话
改为混淆的名字我这里是d.k.a,
Java.use表示使用d包的k类,然后后面CertificatePinner.a.overload
表示hook a方法

/*** okhttp3.x unpinning ***/

// Wrap the logic in a try/catch as not all applications will have
// okhttp as part of the app.
try {
    var CertificatePinner = Java.use('d.k');

    quiet_send('OkHTTP 3.x Found');

    CertificatePinner.a.overload('java.lang.String', 'java.util.List').implementation = function () {

        quiet_send('OkHTTP 3.x check() called. Not throwing an exception.');
    }

} catch (err) {

    // If we dont have a ClassNotFoundException exception, raise the
    // problem encountered.
    if (err.message.indexOf('ClassNotFoundException') === 0) {

        throw new Error(err);
    }
}

application脚本

# -*- coding: utf-8 -*-
import frida, sys, re, sys, os
from subprocess import Popen, PIPE, STDOUT
import codecs, time 

if (len(sys.argv) > 1):
    APP_NAME = str(sys.argv[1])
else:
    APP_NAME = "com.loco.example.OkHttp3SSLPinning"

def sbyte2ubyte(byte):
    return (byte % 256)

def print_result(message):
    print ("[!] Received: [%s]" %(message))

def on_message(message, data):
    if 'payload' in message:
        data = message['payload']
        if type(data) is str:
            print_result(data)
        elif type(data) is list:
            a = data[0]
            if type(a) is int:
                hexstr = "".join([("%02X" % (sbyte2ubyte(a))) for a in data])
                print_result(hexstr)
                print_result(hexstr.decode('hex'))
            else:
                print_result(data)
                print_result(hexstr.decode('hex'))
        else:
            print_result(data)
    else:
        if message['type'] == 'error':
            print (message['stack'])
        else:
            print_result(message)


def kill_process():
    cmd = "adb shell pm clear {} 1> /dev/null".format(APP_NAME)
    os.system(cmd)

#kill_process()

try:
    with codecs.open("hooks.js", 'r', encoding='utf8') as f:
        jscode  = f.read()
        device  = frida.get_usb_device(timeout=5)
        #pid     = device.spawn([APP_NAME])
        session = device.attach("com.loco.example.OkHttp3SSLPinning")
        script  = session.create_script(jscode)
        #device.resume(APP_NAME)
        script.on('message', on_message)
        print ("[*] Intercepting on {} ...".format(APP_NAME))
        script.load()
        sys.stdin.read()
except KeyboardInterrupt:
        print ("[!] Killing app...")
        kill_process()
        time.sleep(1)
        kill_process()

异常处理

frida Unable to load SELinux policy from the kernel: Failed to open file ?/sys/fs/selinux/policy?: Permission denied

主要原因是没有开启su权限。

综合脚本:

# -*- coding: utf-8 -*-
# @时间 : 2020/10/28 10:48 下午
# @作者 : 陈祥安
# @文件名 : install_frida.py
# @公众号: Python学习开发
import subprocess
import sys
import six
import os
from loguru import logger
import requests
from tqdm import tqdm


_temp = os.path.dirname(os.path.abspath(__file__))
frida_server_path = os.path.join(_temp, "fs1280")
if not os.path.exists(frida_server_path):
    os.makedirs(frida_server_path)


def download_from_url(url, dst):
    response = requests.get(url, stream=True)  # (1)
    file_size = int(response.headers['content-length'])  # (2)
    if os.path.exists(dst):
        first_byte = os.path.getsize(dst)  # (3)
    else:
        first_byte = 0
    if first_byte >= file_size:  # (4)
        return file_size
    header = {"Range": f"bytes={first_byte}-{file_size}"}
    pbar = tqdm(
        total=file_size, initial=first_byte,
        unit='B', unit_scale=True, desc=dst)
    req = requests.get(url, headers=header, stream=True)  # (5)
    with(open(dst, 'ab')) as f:
        for chunk in req.iter_content(chunk_size=1024):  # (6)
            if chunk:
                f.write(chunk)
                pbar.update(1024)
    pbar.close()
    return file_size


class IsNotPython3(ValueError):
    def __str__(self):
        return "请安装python3"


def adb_operation(fs_file):
    """

    :param fs_file:
    :return:
    """

    command = f"""
        adb push {fs_file} /data/local/tmp/;
        adb shell "chmod 755 /data/local/tmp/fs1280";
        adb shell "/data/local/tmp/fs1280 &";
    """
    completed = subprocess.run(command, check=True, shell=True,
                               stdout=subprocess.PIPE)
    logger.info(completed.stdout.decode("utf-8"))


def get_python_version():
    python_version = sys.version_info
    py3 = six.PY3
    if py3:
        if python_version > (3, 6) and python_version < (3, 7):
            logger.info("完美的python3.6环境")
        else:
            logger.warning("如果出现问题请尝试使用Python3.6")
    else:
        raise IsNotPython3


def get_frida_server():
    # arm64
    logger.info("开始下载frida-server 版本arm64")
    file_name = "fs1280"
    url = "https://github.com/frida/frida/releases/download/12.8.0/frida-server-12.8.0-android-arm64.xz"
    frida_full_path = os.path.join(frida_server_path, file_name)
    download_from_url(url, dst=frida_full_path)
    logger.info("下载frida-server成功!")
    adb_operation(frida_full_path)


def main():
    get_python_version()
    install_list = ["frida==12.8.0", "frida-tools==5.3.0", "objection==1.8.4"]
    python_path = sys.executable
    for install_item in install_list:
        logger.info(f"当前安装的是:{install_item.split('==')[0]}")

        try:
            command = f'{python_path} -m pip install {install_item}'
            completed = subprocess.run(command, check=True, shell=True,
                                       stdout=subprocess.PIPE)
            result = completed.stdout.decode("utf-8")
            logger.info(result)
        except subprocess.CalledProcessError:
            raise ValueError(f"{install_item},安装失败")
    get_frida_server()


if __name__ == '__main__':
    main()

posted @ 2019-06-20 09:10  公众号python学习开发  阅读(4431)  评论(0编辑  收藏  举报