Tiktok data acquisition Frida tutorial, Frida Java Hook detailed explanation: code and sample (Part 2)

TiToData 2021-01-20 21:49:19
tiktok data acquisition frida tutorial


Tiktok data acquisition Frida course ,Frida Java Hook Detailed explanation : Code and examples ( Next )

<br>

Short video 、 Live data real time acquisition interface , Please view the document : TiToData

<br> disclaimer : This document is for learning and reference only , Do not use for illegal purposes ! Otherwise, I will bear all the consequences .<br>

1.1 Java Layer intercepts inner class functions

We've learned before HOOK Ordinary function 、 Method overloading 、 Constructors , Now let's learn more HOOK stay Android In reverse , We often meet in Java The inner class of the layer .Java Inner class functions , It makes it harder to analyze the code . We have a basic understanding and use of inner classes in this chapter FRIDA Hook interception of inner classes . What is an inner class ? The so-called inner class is the nesting operation of other class structures within a class , Its advantage is that internal and external classes can easily access each other's private domains ( Including private methods 、 Private property ), therefore Android Inner classes are used in many places in , Let's see an example, which is also the most intuitive , Here's the picture 4-17.<br><br> chart 4-17 User Class clz class <br> In the figure 4-17 see User Class clz, This kind of operation is also common . stay frida in , We can use $ Symbols are used to deal with . Start by opening jadxgui The software decompiles the code , After decompilation, enter User class , There will be one below smali The button , Click on smali You will enter smali Code , Get into smali The code directly presses ctrl+f Local search string clz, because clz Is the name of the inner class , Then you'll find Lcom/roysue/roysueapplication/User\$clz;, We will translate it into java The code is :com.roysue.roysueapplication.User\$clz, Remove the first string of L and / as well as ; It forms the specific class name of the inner class , See the picture below 4-18.<br>image.pngimage.gif<br> chart 4-18 smali Code <br> After the above analysis, we have learned the most important part of the class path :com.roysue.roysueapplication.User\$clz, Now let's do the inner class HOOK, So let's start writing js Script .

1.1.1 Example of intercepting inner class function code

function hook_overload_3() {
if(Java.available) {
Java.perform(function () {
console.log("start hook");
// Note here that the path of the class is filled in to change the analyzed path 
var clz = Java.use('com.roysue.roysueapplication.User$clz');
if(clz != undefined) {
// This is also like a normal function hook that will do 
clz.toString.implementation = function (){
console.log(" success hook clz class ");
return this.toString();
}
} else {
console.log("clz: undefined");
}
console.log("start end");
});
}
}

After script execution , We can see that the control has been attached and printed successfully hook clz class , In this way, we can do the same to Java The inner class of the layer .

[Google Pixel::com.roysue.roysueapplication]-> success hook clz class
success hook clz class

1.2 Java Layer enumerates all classes and locates classes

In front of us, we learned how to java All kinds of functions of layer HOOK Operation , Now we're going to learn how to enumerate all the classes and locate them ~, Before we study, we should understand API Medium enumerateLoadedClasses Method , It belongs to Java One of the methods in the object . Can enumerate all classes loaded now ,enumerateLoadedClasses There is 2 Callback functions , Namely onMatch:function(ClassName): For each loaded with className Class call to , Every ClassName All returned are class names ; and onComplete:function(): Call back once after enumerating all classes .

1.2.1 Enumerate all classes and locate class code examples


setTimeout(function (){
Java.perform(function (){
console.log("n[*] enumerating classes...");
//Java Object's API enumerateLoadedClasses
Java.enumerateLoadedClasses({
// In this callback function _className The parameter is the name of the class , Each callback returns the name of a class 
onMatch: function(_className){
// It's output here 
console.log("[*] found instance of '"+_className+"'");
// If you just need to print out com.roysue Package all the classes and just comment this paragraph , I want to print the others and replace them indexOf You can navigate to ~
//if(_className.toString().indexOf("com.roysue")!=-1)
//{
// console.log("[*] found instance of '"+_className+"'");
//}
},
onComplete: function(){
// This function is called back once after the enumeration class ends 
console.log("[*] class enuemration complete");
}
});
});
});

When we execute the script , After the target process is injected, it starts calling onMatch function , Each call prints the name of the class , When onMatch The function is called once after the callback is complete onComplete function , It will print out class enuemration complete, See the picture below .<br><br> chart 4-19 Enumerate all classes

1.3 Java Layer enumerates all the methods of the class and locates the methods

The class and instance have been enumerated above , Now let's enumerate all the methods , Print the internal method names of the specified class or all classes , The main core function is through the reflection method of class getDeclaredMethods(), The api Belong to JAVAJDK The built-in API, Belong to java.lang.Class Functions defined in the package . This method gets all the methods declared by the class or interface , Including public 、 Protect 、 Default ( package ) Access and private methods , But not including the method of inheritance . Of course, it also includes the methods of the interface it implements . stay Java It's defined in this way :public Method[] getDeclaredMethods(); Its return value is a Method Array ,Method It's actually a method name string , An array of objects, of course , And then we print it out .

1.3.1 Enumerate all the methods of the class and locate the method code example

function enumMethods(targetClass)
{
var hook = Java.use(targetClass);
var ownMethods = hook.class.getDeclaredMethods();
hook.$dispose;
return ownMethods;
}
function hook_overload_5() {
if(Java.available) {
Java.perform(function () {
var a = enumMethods("com.roysue.roysueapplication.User$clz")
a.forEach(function(s) {
console.log(s);
});
});
}
}

Let's define a enumMethods Method , Its parameters targetClass Is the path name of the class , be used for Java.use Get the class object itself , Get the class object and then pass it .class.getDeclaredMethods() Method to get an array of all the method names of the target class , When the call is over getDeclaredMethods() Method and then call $dispose Method to release the target class object , Returns all the method names of the target class 、 Return type and function permissions , This is the core method to get the method name , The following method is mainly used to inject logic code into the target process , stay hook_overload_5 In this method, we first used Java.perform Method , And then call... Internally enumMethods Method to get all the method names of the target class 、 Return type and function permissions , Back to a Method Array , adopt forEach The iterator loops through each value in the array , Because it is actually a string, you can get the method name by directly outputting it , The script execution effect is shown in the figure below 4-20.<br>image.gifimage.png<br> chart 4-20 After the script is executed, the effect is shown in the figure 4-17 in clz only one toString Method , Let's fill in the parameter as com.roysue.roysueapplication.User$clz, You can locate all the methods in the class .

1.4 Java All method overloads of layer interception methods

After we have learned to enumerate all classes and the methods of classes , We also want to know how to get all the method overloaded functions , After all, Android In decompiled source code, method overloading is not rare , Regarding this , Disposable hook All method overloading is necessary to learn . We already know that hook To overload a method, write overload('x'), That is to say, we need to construct an overloaded array , And print out every overload .

1.4.1 Examples of all method overload code for intercepting methods

function hook_overload_8() {
if(Java.available) {
Java.perform(function () {
console.log("start hook");
var targetMethod = 'add';
var targetClass = 'com.roysue.roysueapplication.Ordinary_Class';
var targetClassMethod = targetClass + '.' + targetMethod;
// Target class 
var hook = Java.use(targetClass);
// Overload times 
var overloadCount = hook[targetMethod].overloads.length;
// Print log : How many overloads does the tracing method have 
console.log("Tracing " + targetClassMethod + " [" + overloadCount + " overload(s)]");
// Every overload goes in once 
for (var i = 0; i < overloadCount; i++) {
//hook Every overload 
hook[targetMethod].overloads[i].implementation = function() {
console.warn("n*** entered " + targetClassMethod);
// You can print the call stack for each overload , Great for debugging , Of course , There's a lot of information , Try not to print , Unless the analysis is deadlocked 
Java.perform(function() {
var bt = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new());
console.log("nBacktrace:n" + bt);
});
// Printing parameters 
if (arguments.length) console.log();
for (var j = 0; j < arguments.length; j++) {
console.log("arg[" + j + "]: " + arguments[j]);
}
// Print return value 
var retval = this[targetMethod].apply(this, arguments); // rare crash (Frida bug?)
console.log("nretval: " + retval);
console.warn("n*** exiting " + targetClassMethod);
return retval;
}
}
console.log("hook end");
});
}
}

1.4.2 Interception method of all methods overloaded code example details

The above code can print out com.roysue.roysueapplication.Ordinary_Class Class add The number of overloaded methods and hook All methods in this class overload functions , Now let's analyze why the above code can overload all methods in a class HOOK Hang up the hook . First, we define three variables, which are targetMethod、targetClass、targetClassMethod, These three variables are mainly used to define the name of the method 、 Class name 、 And the class name + Assignment of method name , First of all, I used Java.use Got the target class object , Get the number of overloads . Here's how to get it in detail :var method_overload = cls[<func_name>].overloads[index]; This code can be seen through cls Indexes func_name To methods in a class , And then it says overloads[index] Is the second... Of a method overload index A function , It means to return a method Object number index Function of position . And in the code it says :var overloadCount = hook[targetMethod].overloads.length;, The method is to get the number of overloaded methods of a function in the class . Keep going down , Start loop method overloaded function , At the beginning of the cycle hook[targetMethod].overloads[i].implementation This sentence applies to every overloaded function HOOK. Let's also talk about Arguments:Arguments yes js One of the objects in ,js Each function in is built with a Arguments Object instances arguments, It refers to method arguments , Call its instance object through arguments[] Subscript to refer to the actual element ,arguments.length Is the number of function arguments ,arguments.callee Reference function itself . That's why you don't see arguments The reason why the definition of can be called directly , Because it's a built-in object . Okay , Finished. arguments Let's go on , Print parameters through arguments.length To cycle and arguments[j] To get the elements of the actual parameters . Now let's see apply,apply stay js What kind of existence is there in the world ,apply The meaning is : A method of applying an object , Replace the current object with another object ,this[targetMethod].apply(this, arguments); In short, this code implements the current overload Method . Complete the current overload Method and print and return to the function that is actually called , This will not make the program error . Then the final implementation effect is shown in the figure below 4-21:<br>image.pngimage.gif<br> chart 4-21 Terminal display <br> You can see that it's printed successfully add The number of method overloads and the hook Printed parameter values 、 Return value !

1.5 Java Layer intercepts all methods of the class

Learned how to HOOK After all methods overload functions , We can integrate what we learned before , Come on hook Specify all methods in the class , It also includes methods overloaded functions . below js The core of the code is to use the characteristics of overloaded functions to HOOK All the way , A common method is also a special method overload , It's just that it's just a method , Just think of it as a method overload HOOK Just fine , For example, a square is a special rectangle , And the rectangle is not a special square . This square is a normal function , And rectangle is overload method, so we should understand it very well ~ I've learned how to hook Method overloading , Only the method name and class name are dead , Just put the members of targetClass、targetMethod Just define the parameters in the method , In this example, we get all the method names of the specified class , More flexible use of , The code is as follows .

1.5.1 Examples of all method code for intercepting classes

function traceClass(targetClass)
{
//Java.use It's a new object , You remember that ?
var hook = Java.use(targetClass);
// Using reflection , Get all the methods of the current class 
var methods = hook.class.getDeclaredMethods();
// Remember to release the object after building it 
hook.$dispose;
// Save the method name to an array 
var parsedMethods = [];
methods.forEach(function(method) {
// adopt getName() Method to get the function name 
parsedMethods.push(method.getName());
});
// Remove some duplicate values 
var targets = uniqBy(parsedMethods, JSON.stringify);
// All the methods in the array are hook
targets.forEach(function(targetMethod) {
traceMethod(targetClass + "." + targetMethod);
});
}
function hook_overload_9() {
if(Java.available) {
Java.perform(function () {
console.log("start hook");
traceClass("com.roysue.roysueapplication.Ordinary_Class");
console.log("hook end");
});
}
}
s1etImmediate(hook_overload_9);

The effect of executing the script can be seen ,hook here we are com.roysue.roysueapplication.Ordinary_Class All the functions in the class , In the course of its execution, it is hook The way to intercept , The parameters and return values of each method are also printed , See the picture below 4-22.<br><br> chart 4-22 Terminal operation display effect

1.6 Java Layer intercepts all subclasses of a class

The core functions here also use the functions defined in the previous section traceClass function , This function only needs to pass in a class The path is right class The function in completes the injection hook. So in this little chapter hook Drop subclasses of all classes , Make our script more flexible and convenient . Through the previous study, we have learned that enumerateLoadedClasses This api You can enumerate all the classes , Use it to get all the classes and then call traceClass Function can be a comprehensive analysis of all subclasses hook. But generally not hook All functions , because AndroidAPI There are too many functions , Here we need to match our own needs hook Class of , The code is as follows .

// Enumerate all classes that have been loaded 
Java.enumerateLoadedClasses({
onMatch: function(aClass) {
// Iteration and judgment 
if (aClass.match(pattern)) {
// Make some more judgments , Fit more pattern
var className = aClass.match(/[L]?(.*);?/)[1].replace(///g, ".");
// Enter into traceClass In go to 
traceClass(className);
}
},
onComplete: function() {}
});

1.7 RPC The remote invocation Java Layer function

stay FRIDA in , Not only does it provide perfect HOOK Mechanism , And it also provides rpc Interface . You can export a specified function , Realize in python Layer calls it at will , And call whenever and wherever you want , Very convenient , Because it's outside the supply python, This makes rpc The interface provided can be connected with python Do some wonderful things , These derived functions can be arbitrary java Methods of inner classes , Call our own objects and specific methods . Let's get started , Now let's go through RPC The export function of will be shown in Fig 4-9 Medium add Methods provide external calls , Start writing rpc_demo.py file , This time it is python I've got the papers ~ No js The file

1.7.1 rpc export Java Layer function code example

import codecs
import frida
from time import sleep
# The attached process name is :com.roysue.roysueapplication
session = frida.get_remote_device().attach('com.roysue.roysueapplication')
# This needs to be carried out js Script ,rpc Need to be in js In the definition of 
source = """
// Definition RPC
rpc.exports = {
// Here we define a method for external calls :sms
sms: function () {
var result = "";
// The embedded HOOK Code
Java.perform(function () {
// Get class class
var Ordinary_Class = Java.use("com.roysue.roysueapplication.Ordinary_Class");
// Final rpc Of sms Method will return add(1,3) Result !
result = Ordinary_Class.add(1,3);
});
return result;
},
};
"""
# establish js Script 
script = session.create_script(source)
script.load()
# Here you can call java The function in 
rpc = script.exports
# So here it is python Go straight through rpc call sms() Method 
print(rpc.sms())
sleep(1)
session.detach()

When we execute python rpc_demo.py The script is created and injected into the target process , Above source It's actually js Logic code . stay js In the code we define rpc You can give python Called sms function , and sms Nested calls inside functions Java.perform And then call the class of the function you need to get , Return the final result as sms The return value of , When we're in python Layer can be called at will sms Prototype in add Method ~

1.8 Comprehensive case 1 : On Android 8.1 On dump Bluetooth interface and examples

A good comprehensive case :dump Bluetooth information “ Enhanced Edition ”——BlueCrawl.

VERSION="1.0.0"
setTimeout(function(){
Java.perform(function(){
Java.enumerateLoadedClasses({
onMatch: function(instance){
if (instance.split(".")[1] == "bluetooth"){
console.log("[->]t"+lightBlueCursor()+instance+closeCursor());
}
},
onComplete: function() {}
});
Java.choose("android.bluetooth.BluetoothGattServer",{
onMatch: function (instance){
...
onComplete: function() { console.log("[*] -----");}
});
Java.choose("android.bluetooth.BluetoothGattService",{
onMatch: function (instance){
...
onComplete: function() { console.log("[*] -----");}
});
Java.choose("android.bluetooth.BluetoothSocket",{
onMatch: function (instance){
...
onComplete: function() { console.log("[*] -----");}
});
Java.choose("android.bluetooth.BluetoothServerSocket",{
onMatch: function (instance){
...
onComplete: function() { console.log("[*] -----");}
});
Java.choose("android.bluetooth.BluetoothDevice",{
onMatch: function (instance){
...
onComplete: function() { console.log("[*] -----");}
});
});
},0);

The script first enumerates a lot of Bluetooth related classes , then choose There are many classes , Including Bluetooth interface information and Bluetooth service interface object, etc , It also loads the Bluetooth device object that has been allocated in memory , That's what we've demonstrated above . We can use this script to “ see ”App Which Bluetooth interfaces are loaded ,App Looking for Bluetooth devices 、 Or whether to steal Bluetooth device information, etc . Run the command on the computer :$ frida -U -l bluecrawl-1.0.0.js com.android.bluetooth When the script is executed, all Bluetooth interface information and service interface objects will be printed in detail ~~

1.9 Comprehensive case 2 : Dynamic and static combined with reverse WhatsApp

Let's try some of its main functions , The first is the export function of the local library .


setTimeout(function() {
Java.perform(function() {
trace("exports:*!open*");
//trace("exports:*!write*");
//trace("exports:*!malloc*");
//trace("exports:*!free*");
});
}, 0);

We hook Yes. open() function , Run and see the effect :<br>

$ frida -U -f com.whatsapp -l raptor_frida_android_trace_fixed.js --no-pause

As shown in the figure *!open* According to the regular match, we got openlogopen64 And so on , and hook All of these functions are described , Print out its parameters and return values . Which part do you want to see next , Just throw it at jadx in , static state “ analysis ” Once , I'm going to flip it myself , Or search by string . For example, we want to see com.whatsapp.app.protocol The contents of the bag , You can set trace("com.whatsapp.app.protocol"). You can see the functions in the package 、 Method 、 Including heavy haul 、 Parameters and return values are all printed out . This is it. frida The charm of scripts . Of course , Script is just a tool after all , You are right about Java、 Android App The understanding of the , And your creativity is crucial . Next you can match it with Xposed module Look at what other people give whatsapp What modules have been made ,hook Which functions of , What functions have been realized , Learn to write by yourself .

Short video 、 Live data real time acquisition interface , Please view the document : TiToData

<br> disclaimer : This document is for learning and reference only , Do not use for illegal purposes ! Otherwise, I will bear all the consequences .

版权声明
本文为[TiToData]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210120214755966v.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云